diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000000..34d3f1aec82a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,44 @@ +# C/C++ +[*.{c,cc,h,hh,inl,glsl}] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = tab +indent_size = 4 +max_line_length = 120 + +# CMake & Text +[*.{cmake,txt}] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = tab +indent_size = 4 +max_line_length = 120 + +# Python +[*.py] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 4 +max_line_length = 120 + +# Shell +[*.sh] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = tab +indent_size = 4 +max_line_length = 120 + +# reStructuredText +[*.rst] +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 3 +max_line_length = 120 diff --git a/CMakeLists.txt b/CMakeLists.txt index bf923f0a7601..c1693200bf7c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,6 +62,11 @@ if(NOT DEFINED CMAKE_BUILD_TYPE_INIT) set(CMAKE_BUILD_TYPE_INIT "Release") endif() +# Omit superfluous "Up-to-date" messages. +if(NOT DEFINED CMAKE_INSTALL_MESSAGE) + set(CMAKE_INSTALL_MESSAGE "LAZY") +endif() + # quiet output for Makefiles, 'make -s' helps too # set_property(GLOBAL PROPERTY RULE_MESSAGES OFF) @@ -110,7 +115,11 @@ enable_testing() set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin CACHE INTERNAL "" FORCE) set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib CACHE INTERNAL "" FORCE) -set(TESTS_OUTPUT_DIR ${EXECUTABLE_OUTPUT_PATH}/tests CACHE INTERNAL "" FORCE) +if(MSVC) + set(TESTS_OUTPUT_DIR ${EXECUTABLE_OUTPUT_PATH}/tests/$/ CACHE INTERNAL "" FORCE) +else() + set(TESTS_OUTPUT_DIR ${EXECUTABLE_OUTPUT_PATH}/tests/ CACHE INTERNAL "" FORCE) +endif() #----------------------------------------------------------------------------- # Set default config options @@ -158,6 +167,7 @@ option_defaults_init( _init_FFTW3 _init_GAMEENGINE _init_OPENSUBDIV + _init_SYSTEM_OPENJPG ) # customize... @@ -174,11 +184,13 @@ if(UNIX AND NOT APPLE) set(_init_SDL OFF) set(_init_FFTW3 OFF) set(_init_OPENSUBDIV OFF) + set(_init_SYSTEM_OPENJPG OFF) elseif(WIN32) set(_init_JACK OFF) elseif(APPLE) set(_init_JACK OFF) set(_init_OPENSUBDIV OFF) + set(_init_SYSTEM_OPENJPG OFF) endif() @@ -305,7 +317,7 @@ endif() # (unix defaults to System OpenJPEG On) -option(WITH_SYSTEM_OPENJPEG "Use the operating systems OpenJPEG library" OFF) +option(WITH_SYSTEM_OPENJPEG "Use the operating systems OpenJPEG library" ${_init_SYSTEM_OPENJPG}) if(UNIX AND NOT APPLE) option(WITH_SYSTEM_EIGEN3 "Use the systems Eigen3 library" OFF) @@ -414,6 +426,8 @@ option(WITH_CYCLES_OSL "Build Cycles with OSL support" ${_init_CYCLES_OSL}) option(WITH_CYCLES_OPENSUBDIV "Build Cycles with OpenSubdiv support" ${_init_CYCLES_OPENSUBDIV}) option(WITH_CYCLES_CUDA_BINARIES "Build Cycles CUDA binaries" OFF) option(WITH_CYCLES_CUBIN_COMPILER "Build cubins with nvrtc based compiler instead of nvcc" OFF) +option(WITH_CYCLES_CUDA_BUILD_SERIAL "Build cubins one after another (useful on machines with limited RAM)" OFF) +mark_as_advanced(WITH_CYCLES_CUDA_BUILD_SERIAL) set(CYCLES_CUDA_BINARIES_ARCH sm_30 sm_35 sm_37 sm_50 sm_52 sm_60 sm_61 CACHE STRING "CUDA architectures to build binaries for") mark_as_advanced(CYCLES_CUDA_BINARIES_ARCH) unset(PLATFORM_DEFAULT) @@ -460,7 +474,7 @@ mark_as_advanced(WITH_MEM_VALGRIND) option(WITH_CXX_GUARDEDALLOC "Enable GuardedAlloc for C++ memory allocation tracking (only enable for development)" OFF) mark_as_advanced(WITH_CXX_GUARDEDALLOC) -option(WITH_ASSERT_ABORT "Call abort() when raising an assertion through BLI_assert()" OFF) +option(WITH_ASSERT_ABORT "Call abort() when raising an assertion through BLI_assert()" ON) mark_as_advanced(WITH_ASSERT_ABORT) option(WITH_BOOST "Enable features depending on boost" ON) @@ -516,27 +530,6 @@ if(WIN32) set(CPACK_INSTALL_PREFIX ${CMAKE_GENERIC_PROGRAM_FILES}/${}) endif() -# Experimental support of C11 and C++11 -# -# We default options to whatever default standard in the current compiler. -if(APPLE) - set(_c11_init ON) - set(_cxx11_init ON) - set(WITH_C11 ON) - set(WITH_CXX11 ON) -elseif(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11)) - set(_c11_init ON) - set(_cxx11_init ON) -else() - set(_c11_init OFF) - set(_cxx11_init OFF) -endif() - -option(WITH_C11 "Build with C11 standard enabled, for development use only!" ${_c11_init}) -mark_as_advanced(WITH_C11) -option(WITH_CXX11 "Build with C++11 standard enabled, for development use only!" ${_cxx11_init}) -mark_as_advanced(WITH_CXX11) - # Compiler toolchain if(CMAKE_COMPILER_IS_GNUCC) option(WITH_LINKER_GOLD "Use ld.gold linker which is usually faster than ld.bfd" ON) @@ -664,10 +657,12 @@ endif() if(NOT WITH_AUDASPACE) if(WITH_OPENAL) - message(FATAL_ERROR "WITH_OPENAL requires WITH_AUDASPACE") + message(WARNING "WITH_OPENAL requires WITH_AUDASPACE which is disabled") + set(WITH_OPENAL OFF) endif() if(WITH_JACK) - message(FATAL_ERROR "WITH_JACK requires WITH_AUDASPACE") + message(WARNING "WITH_JACK requires WITH_AUDASPACE which is disabled") + set(WITH_JACK OFF) endif() endif() @@ -719,11 +714,8 @@ elseif(WITH_CYCLES OR WITH_OPENIMAGEIO OR WITH_AUDASPACE OR WITH_INTERNATIONAL O WITH_OPENVDB OR WITH_OPENCOLORIO) # Keep enabled else() - # New dependency graph needs either Boost or C++11 for function bindings. - if(NOT WITH_CXX11) - # Enabled but we don't need it - set(WITH_BOOST OFF) - endif() + # Disable boost if not needed. + set(WITH_BOOST OFF) endif() # auto enable openimageio for cycles @@ -781,9 +773,6 @@ if(WITH_BUILDINFO) endif() endif() -TEST_SHARED_PTR_SUPPORT() -TEST_UNORDERED_MAP_SUPPORT() - if(WITH_AUDASPACE) if(WITH_SYSTEM_AUDASPACE) set(AUDASPACE_DEFINITIONS @@ -877,7 +866,8 @@ set(C_WARNINGS) set(CXX_WARNINGS) # for gcc -Wno-blah-blah -set(CC_REMOVE_STRICT_FLAGS) +set(C_REMOVE_STRICT_FLAGS) +set(CXX_REMOVE_STRICT_FLAGS) # libraries to link the binary with passed to target_link_libraries() # known as LLIBS to scons @@ -897,11 +887,11 @@ if (NOT CMAKE_BUILD_TYPE MATCHES "Release") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${COMPILER_ASAN_CXXFLAGS}") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ${COMPILER_ASAN_CXXFLAGS}") if(MSVC) - set(COMPILER_ASAN_LINKER_FLAGS "/FUNCTIONPADMIN:6") + set(COMPILER_ASAN_LINKER_FLAGS "/FUNCTIONPADMIN:6") endif() set(PLATFORM_LINKLIBS "${PLATFORM_LINKLIBS};${COMPILER_ASAN_LIBRARY}") set(PLATFORM_LINKFLAGS "${COMPILER_ASAN_LIBRARY} ${COMPILER_ASAN_LINKER_FLAGS}") - set(PLATFORM_LINKFLAGS_DEBUG "${COMPILER_ASAN_LIBRARY} ${COMPILER_ASAN_LINKER_FLAGS}") + set(PLATFORM_LINKFLAGS_DEBUG "${COMPILER_ASAN_LIBRARY} ${COMPILER_ASAN_LINKER_FLAGS}") endif() endif() @@ -1386,42 +1376,8 @@ endif() # Configure Ceres if(WITH_LIBMV) - set(CERES_DEFINES) - - if(WITH_CXX11) - # nothing to be done - elseif(SHARED_PTR_FOUND) - if(SHARED_PTR_TR1_MEMORY_HEADER) - list(APPEND CERES_DEFINES -DCERES_TR1_MEMORY_HEADER) - endif() - if(SHARED_PTR_TR1_NAMESPACE) - list(APPEND CERES_DEFINES -DCERES_TR1_SHARED_PTR) - endif() - else() - message(FATAL_ERROR "Ceres: Unable to find shared_ptr.") - endif() - - if(WITH_CXX11) - list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP) - elseif(HAVE_STD_UNORDERED_MAP_HEADER) - if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE) - list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP) - else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) - else() - list(APPEND CERES_DEFINES -DCERES_NO_UNORDERED_MAP) - message(STATUS "Ceres: Replacing unordered_map/set with map/set (warning: slower!)") - endif() - endif() - else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - list(APPEND CERES_DEFINES -DCERES_TR1_UNORDERED_MAP) - else() - list(APPEND CERES_DEFINES -DCERES_NO_UNORDERED_MAP) - message(STATUS "Ceres: Replacing unordered_map/set with map/set (warning: slower!)") - endif() - endif() + # We always have C++11 which includes unordered_map. + set(CERES_DEFINES -DCERES_STD_UNORDERED_MAP) endif() #----------------------------------------------------------------------------- @@ -1512,16 +1468,22 @@ if(CMAKE_COMPILER_IS_GNUCC) endif() # flags to undo strict flags - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_DEPRECATED_DECLARATIONS -Wno-deprecated-declarations) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_FUNCTION -Wno-unused-function) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_DEPRECATED_DECLARATIONS -Wno-deprecated-declarations) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_FUNCTION -Wno-unused-function) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_TYPE_LIMITS -Wno-type-limits) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INT_IN_BOOL_CONTEXT -Wno-int-in-bool-context) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_FORMAT -Wno-format) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_SWITCH -Wno-switch) + + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CLASS_MEMACCESS -Wno-class-memaccess) if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "7.0")) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_IMPLICIT_FALLTHROUGH -Wno-implicit-fallthrough) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_IMPLICIT_FALLTHROUGH -Wno-implicit-fallthrough) endif() if(NOT APPLE) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_ERROR_UNUSED_BUT_SET_VARIABLE -Wno-error=unused-but-set-variable) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_ERROR_UNUSED_BUT_SET_VARIABLE -Wno-error=unused-but-set-variable) endif() elseif(CMAKE_C_COMPILER_ID MATCHES "Clang") @@ -1550,23 +1512,23 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Clang") # ADD_CHECK_CXX_COMPILER_FLAG(CXX_WARNINGS CXX_WARN_UNUSED_MACROS -Wunused-macros) # flags to undo strict flags - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_MACROS -Wno-unused-macros) - - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_VARIABLE_DECLARATIONS -Wno-missing-variable-declarations) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_INCOMPAT_PTR_DISCARD_QUAL -Wno-incompatible-pointer-types-discards-qualifiers) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_FUNCTION -Wno-unused-function) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_INT_TO_VOID_POINTER_CAST -Wno-int-to-void-pointer-cast) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_PROTOTYPES -Wno-missing-prototypes) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_DUPLICATE_ENUM -Wno-duplicate-enum) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_UNDEF -Wno-undef) - ADD_CHECK_C_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_NORETURN -Wno-missing-noreturn) - - ADD_CHECK_CXX_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_PRIVATE_FIELD -Wno-unused-private-field) - ADD_CHECK_CXX_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS CXX_WARN_NO_CXX11_NARROWING -Wno-c++11-narrowing) - ADD_CHECK_CXX_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS CXX_WARN_NO_NON_VIRTUAL_DTOR -Wno-non-virtual-dtor) - ADD_CHECK_CXX_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_MACROS -Wno-unused-macros) - ADD_CHECK_CXX_COMPILER_FLAG(CC_REMOVE_STRICT_FLAGS CXX_WARN_NO_REORDER -Wno-reorder) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_PARAMETER -Wno-unused-parameter) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_MACROS -Wno-unused-macros) + + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_VARIABLE_DECLARATIONS -Wno-missing-variable-declarations) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INCOMPAT_PTR_DISCARD_QUAL -Wno-incompatible-pointer-types-discards-qualifiers) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNUSED_FUNCTION -Wno-unused-function) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_INT_TO_VOID_POINTER_CAST -Wno-int-to-void-pointer-cast) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_PROTOTYPES -Wno-missing-prototypes) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_DUPLICATE_ENUM -Wno-duplicate-enum) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_UNDEF -Wno-undef) + ADD_CHECK_C_COMPILER_FLAG(C_REMOVE_STRICT_FLAGS C_WARN_NO_MISSING_NORETURN -Wno-missing-noreturn) + + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_PRIVATE_FIELD -Wno-unused-private-field) + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_CXX11_NARROWING -Wno-c++11-narrowing) + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_NON_VIRTUAL_DTOR -Wno-non-virtual-dtor) + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_UNUSED_MACROS -Wno-unused-macros) + ADD_CHECK_CXX_COMPILER_FLAG(CXX_REMOVE_STRICT_FLAGS CXX_WARN_NO_REORDER -Wno-reorder) elseif(CMAKE_C_COMPILER_ID MATCHES "Intel") @@ -1637,24 +1599,17 @@ if(WITH_PYTHON) endif() endif() -if(WITH_CXX11) - if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang") - # TODO(sergey): Do we want c++11 or gnu-c++11 here? - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - elseif(MSVC) - # Nothing special is needed, C++11 features are available by default. - else() - message(FATAL_ERROR "Compiler ${CMAKE_C_COMPILER_ID} is not supported for C++11 build yet") - endif() +if( + CMAKE_COMPILER_IS_GNUCC OR + CMAKE_C_COMPILER_ID MATCHES "Clang" OR + CMAKE_C_COMPILER_ID MATCHES "Intel" +) + # TODO(sergey): Do we want c++11 or gnu-c++11 here? + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") +elseif(MSVC) + # Nothing special is needed, C++11 features are available by default. else() - # GCC-6 switched to C++11 by default, which would break linking with existing libraries - # by default. So we explicitly disable C++11 for a new GCC so no linking issues happens. - if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0")) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++98") - # We also disable any of C++11 ABI from usage, so we wouldn't even try to - # link to stuff from std::__cxx11 namespace. - add_definitions("-D_GLIBCXX_USE_CXX11_ABI=0") - endif() + message(FATAL_ERROR "Unknown compiler ${CMAKE_C_COMPILER_ID}, can't enable C++11 build") endif() # Visual Studio has all standards it supports available by default diff --git a/GNUmakefile b/GNUmakefile index 23903d36e63b..26d931ae6649 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -89,6 +89,16 @@ ifneq "$(findstring bpy, $(MAKECMDGOALS))" "" endif +# ----------------------------------------------------------------------------- +# Blender binary path + +ifeq ($(OS), Darwin) + BLENDER_BIN="$(BUILD_DIR)/bin/blender.app/Contents/MacOS/blender" +else + BLENDER_BIN="$(BUILD_DIR)/bin/blender" +endif + + # ----------------------------------------------------------------------------- # Get the number of cores for threaded build ifndef NPROCS @@ -140,7 +150,7 @@ all: .FORCE $(MAKE) -C "$(BUILD_DIR)" -s -j $(NPROCS) install @echo @echo edit build configuration with: "$(BUILD_DIR)/CMakeCache.txt" run make again to rebuild. - @echo Blender successfully built, run from: "$(BUILD_DIR)/bin/blender" + @echo Blender successfully built, run from: $(BLENDER_BIN) @echo debug: all @@ -236,7 +246,9 @@ help: .FORCE @echo " * check_descriptions - check for duplicate/invalid descriptions" @echo "" @echo "Utilities (not associated with building blender)" - @echo " * icons - updates PNG icons from SVG files." + @echo " * icons - Updates PNG icons from SVG files." + @echo " Set environment variables 'BLENDER_BIN' and 'INKSCAPE_BIN'" + @echo " to define your own commands." @echo " * tgz - create a compressed archive of the source code." @echo " * update - updates git and all submodules" @echo "" @@ -409,7 +421,7 @@ check_spelling_osl: .FORCE "$(BLENDER_DIR)/intern/cycles/kernel/shaders" check_descriptions: .FORCE - "$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup --python \ + $(BLENDER_BIN) --background -noaudio --factory-startup --python \ "$(BLENDER_DIR)/source/tools/check_source/check_descriptions.py" # ----------------------------------------------------------------------------- @@ -443,7 +455,7 @@ update: .FORCE # Simple version of ./doc/python_api/sphinx_doc_gen.sh with no PDF generation. doc_py: .FORCE - "$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup \ + $(BLENDER_BIN) --background -noaudio --factory-startup \ --python doc/python_api/sphinx_doc_gen.py cd doc/python_api ; sphinx-build -b html sphinx-in sphinx-out @echo "docs written into: '$(BLENDER_DIR)/doc/python_api/sphinx-out/contents.html'" @@ -453,12 +465,12 @@ doc_doxy: .FORCE @echo "docs written into: '$(BLENDER_DIR)/doc/doxygen/html/index.html'" doc_dna: .FORCE - "$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup \ + $(BLENDER_BIN) --background -noaudio --factory-startup \ --python doc/blender_file_format/BlendFileDnaExporter_25.py @echo "docs written into: '$(BLENDER_DIR)/doc/blender_file_format/dna.html'" doc_man: .FORCE - $(PYTHON) doc/manpage/blender.1.py "$(BUILD_DIR)/bin/blender" + $(PYTHON) doc/manpage/blender.1.py $(BLENDER_BIN) blender.1 help_features: .FORCE @$(PYTHON) -c \ diff --git a/build_files/build_environment/CMakeLists.txt b/build_files/build_environment/CMakeLists.txt index f177560c5f63..5270a2e2b3da 100644 --- a/build_files/build_environment/CMakeLists.txt +++ b/build_files/build_environment/CMakeLists.txt @@ -45,6 +45,17 @@ cmake_minimum_required(VERSION 3.5) include(ExternalProject) include(cmake/options.cmake) include(cmake/versions.cmake) + +if(ENABLE_MINGW64) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + include(cmake/setup_mingw64.cmake) + else() + include(cmake/setup_mingw32.cmake) + endif() +else() + set(mingw_LIBDIR ${LIBDIR}) +endif() + include(cmake/zlib.cmake) include(cmake/blendthumb.cmake) include(cmake/openal.cmake) @@ -68,6 +79,9 @@ include(cmake/opencollada.cmake) include(cmake/opencolorio.cmake) include(cmake/llvm.cmake) include(cmake/clang.cmake) +if(APPLE) + include(cmake/openmp.cmake) +endif() include(cmake/openimageio.cmake) include(cmake/tiff.cmake) include(cmake/flexbison.cmake) @@ -77,21 +91,19 @@ include(cmake/openvdb.cmake) include(cmake/python.cmake) include(cmake/python_site_packages.cmake) include(cmake/numpy.cmake) +include(cmake/pugixml.cmake) + if(WITH_WEBP) include(cmake/webp.cmake) endif() if(WIN32) + #hmd_branch_deps include(cmake/hidapi.cmake) -endif() - -if(ENABLE_MINGW64) - if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - include(cmake/setup_mingw64.cmake) - else() - include(cmake/setup_mingw32.cmake) - endif() -else() - set(mingw_LIBDIR ${LIBDIR}) + #ocio deps + include(cmake/tinyxml.cmake) + include(cmake/yamlcpp.cmake) + #lcms is an ocio dep, but only if you build the apps, leaving it here for convenience + #include(cmake/lcms.cmake) endif() if(NOT WIN32 OR ENABLE_MINGW64) @@ -105,8 +117,6 @@ if(NOT WIN32 OR ENABLE_MINGW64) include(cmake/vorbis.cmake) include(cmake/theora.cmake) include(cmake/vpx.cmake) - include(cmake/orc.cmake) - include(cmake/schroedinger.cmake) include(cmake/x264.cmake) include(cmake/xvidcore.cmake) include(cmake/faad.cmake) @@ -115,7 +125,6 @@ if(NOT WIN32 OR ENABLE_MINGW64) include(cmake/sndfile.cmake) if(WIN32) include(cmake/iconv.cmake) - include(cmake/lapack.cmake) endif() if(UNIX) include(cmake/flac.cmake) @@ -128,4 +137,12 @@ if(NOT WIN32 OR ENABLE_MINGW64) endif() endif() +if(UNIX AND NOT APPLE) + include(cmake/bzip2.cmake) + include(cmake/ffi.cmake) + include(cmake/lzma.cmake) + include(cmake/ssl.cmake) + include(cmake/sqlite.cmake) +endif() + include(cmake/harvest.cmake) diff --git a/build_files/build_environment/cmake/alembic.cmake b/build_files/build_environment/cmake/alembic.cmake index cf2cefa2e7ae..e6323d536615 100644 --- a/build_files/build_environment/cmake/alembic.cmake +++ b/build_files/build_environment/cmake/alembic.cmake @@ -26,6 +26,12 @@ if(ALEMBIC_HDF5) endif() endif() +if(WIN32) + set(ALEMBIC_ILMBASE ${LIBDIR}/openexr) +else() + set(ALEMBIC_ILMBASE ${LIBDIR}/ilmbase) +endif() + set(ALEMBIC_EXTRA_ARGS -DBUILDSTATIC=ON -DLINKSTATIC=ON @@ -38,12 +44,13 @@ set(ALEMBIC_EXTRA_ARGS -DBoost_DEBUG=ON -DBOOST_ROOT=${LIBDIR}/boost -DBoost_NO_SYSTEM_PATHS=ON - -DILMBASE_ROOT=${LIBDIR}/ilmbase - -DALEMBIC_ILMBASE_INCLUDE_DIRECTORY=${LIBDIR}/ilmbase/include/OpenEXR - -DALEMBIC_ILMBASE_HALF_LIB=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Half${LIBEXT} - -DALEMBIC_ILMBASE_IMATH_LIB=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath-2_2${LIBEXT} - -DALEMBIC_ILMBASE_ILMTHREAD_LIB=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread-2_2${LIBEXT} - -DALEMBIC_ILMBASE_IEX_LIB=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex-2_2${LIBEXT} + -DILMBASE_ROOT=${ALEMBIC_ILMBASE} + -DALEMBIC_ILMBASE_INCLUDE_DIRECTORY=${ALEMBIC_ILMBASE}/include/OpenEXR + -DALEMBIC_ILMBASE_HALF_LIB=${ALEMBIC_ILMBASE}/lib/${LIBPREFIX}Half${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DALEMBIC_ILMBASE_IMATH_LIB=${ALEMBIC_ILMBASE}/lib/${LIBPREFIX}Imath${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DALEMBIC_ILMBASE_ILMTHREAD_LIB=${ALEMBIC_ILMBASE}/lib/${LIBPREFIX}IlmThread${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DALEMBIC_ILMBASE_IEX_LIB=${ALEMBIC_ILMBASE}/lib/${LIBPREFIX}Iex${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DALEMBIC_ILMBASE_IEXMATH_LIB=${ALEMBIC_ILMBASE}/lib/${LIBPREFIX}IexMath${ILMBASE_VERSION_POSTFIX}${LIBEXT} -DUSE_PYILMBASE=0 -DUSE_PYALEMBIC=0 -DUSE_ARNOLD=0 @@ -72,9 +79,27 @@ ExternalProject_Add(external_alembic INSTALL_DIR ${LIBDIR}/alembic ) +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_alembic after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/alembic ${HARVEST_TARGET}/alembic + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_alembic after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/alembic/lib/alembic.lib ${HARVEST_TARGET}/alembic/lib/alembic_d.lib + DEPENDEES install + ) + endif() +endif() + + + add_dependencies( external_alembic external_boost external_zlib external_ilmbase + external_openexr ) diff --git a/build_files/build_environment/cmake/blosc.cmake b/build_files/build_environment/cmake/blosc.cmake index 606fe8c61ccb..18f258357c95 100644 --- a/build_files/build_environment/cmake/blosc.cmake +++ b/build_files/build_environment/cmake/blosc.cmake @@ -25,8 +25,18 @@ set(BLOSC_EXTRA_ARGS -DThreads_FOUND=1 -DPTHREAD_LIBS=${LIBDIR}/pthreads/lib/pthreadVC2.lib -DPTHREAD_INCLUDE_DIR=${LIBDIR}/pthreads/inc + -DDEACTIVATE_SNAPPY=ON + -DCMAKE_POSITION_INDEPENDENT_CODE=ON ) +if(WIN32) + #prevent blosc from including it's own local copy of zlib in the object file + #and cause linker errors with everybody else + set(BLOSC_EXTRA_ARGS ${BLOSC_EXTRA_ARGS} + -DPREFER_EXTERNAL_ZLIB=ON + ) +endif() + ExternalProject_Add(external_blosc URL ${BLOSC_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} @@ -47,3 +57,19 @@ if(WIN32) external_pthreads ) endif() + +if (WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_blosc after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/blosc/lib/libblosc.lib ${HARVEST_TARGET}/blosc/lib/libblosc.lib + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/blosc/include/ ${HARVEST_TARGET}/blosc/include/ + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_blosc after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/blosc/lib/libblosc_d.lib ${HARVEST_TARGET}/blosc/lib/libblosc_d.lib + DEPENDEES install + ) + endif() +endif() diff --git a/build_files/build_environment/cmake/boost.cmake b/build_files/build_environment/cmake/boost.cmake index 46840b7ead45..33bfa1d4e821 100644 --- a/build_files/build_environment/cmake/boost.cmake +++ b/build_files/build_environment/cmake/boost.cmake @@ -16,6 +16,8 @@ # # ***** END GPL LICENSE BLOCK ***** +set(BOOST_ADDRESS_MODEL 64) + if(WIN32) if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") set(PYTHON_ARCH x64) @@ -25,16 +27,11 @@ if(WIN32) set(PYTHON_ARCH x86) set(PYTHON_ARCH2 win32) set(PYTHON_OUTPUTDIR ${BUILD_DIR}/python/src/external_python/pcbuild/win32/) - endif() - if(MSVC12) - set(BOOST_TOOLSET toolset=msvc-12.0) - set(BOOST_COMPILER_STRING -vc120) - set(PYTHON_COMPILER_STRING v120) + set(BOOST_ADDRESS_MODEL 32) endif() if(MSVC14) set(BOOST_TOOLSET toolset=msvc-14.0) set(BOOST_COMPILER_STRING -vc140) - set(PYTHON_COMPILER_STRING v140) endif() set(JAM_FILE ${BUILD_DIR}/boost/src/external_boost/user-config.jam) set(semi_path "${PATCH_DIR}/semi.txt") @@ -51,22 +48,26 @@ if(WIN32) #set(BOOST_WITH_PYTHON --with-python) set(BOOST_HARVEST_CMD ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/boost/lib/ ${HARVEST_TARGET}/boost/lib/ ) if(BUILD_MODE STREQUAL Release) - set(BOOST_HARVEST_CMD ${BOOST_HARVEST_CMD} && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/boost/include/boost-1_60/ ${HARVEST_TARGET}/boost/include/) + set(BOOST_HARVEST_CMD ${BOOST_HARVEST_CMD} && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/boost/include/boost-1_68/ ${HARVEST_TARGET}/boost/include/) endif() - set(BOOST_PATCH_COMMAND ${PATCH_CMD} --verbose -p 1 -N -d ${BUILD_DIR}/boost/src/external_boost < ${PATCH_DIR}/boost.diff) elseif(APPLE) set(BOOST_CONFIGURE_COMMAND ./bootstrap.sh) - set(BOOST_BUILD_COMMAND ./bjam) - set(BOOST_BUILD_OPTIONS toolset=clang cxxflags=${PLATFORM_CXXFLAGS} linkflags=${PLATFORM_LDFLAGS} --disable-icu boost.locale.icu=off) + set(BOOST_BUILD_COMMAND ./b2) + set(BOOST_BUILD_OPTIONS toolset=darwin cxxflags=${PLATFORM_CXXFLAGS} linkflags=${PLATFORM_LDFLAGS} --disable-icu boost.locale.icu=off) set(BOOST_HARVEST_CMD echo .) set(BOOST_PATCH_COMMAND echo .) else() set(BOOST_HARVEST_CMD echo .) set(BOOST_CONFIGURE_COMMAND ./bootstrap.sh) - set(BOOST_BUILD_COMMAND ./bjam) + set(BOOST_BUILD_COMMAND ./b2) set(BOOST_BUILD_OPTIONS cxxflags=${PLATFORM_CXXFLAGS} --disable-icu boost.locale.icu=off) set(BOOST_PATCH_COMMAND echo .) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + set(BOOST_ADDRESS_MODEL 64) + else() + set(BOOST_ADDRESS_MODEL 32) + endif() endif() set(BOOST_OPTIONS @@ -85,23 +86,17 @@ set(BOOST_OPTIONS ${BOOST_TOOLSET} ) -if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - set(BOOST_ADDRESS_MODEL 64) -else() - set(BOOST_ADDRESS_MODEL 32) -endif() - string(TOLOWER ${BUILD_MODE} BOOST_BUILD_TYPE) ExternalProject_Add(external_boost URL ${BOOST_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH MD5=${BOOST_MD5} + URL_HASH MD5=${BOOST_HASH} PREFIX ${BUILD_DIR}/boost UPDATE_COMMAND "" PATCH_COMMAND ${BOOST_PATCH_COMMAND} CONFIGURE_COMMAND ${BOOST_CONFIGURE_COMMAND} - BUILD_COMMAND ${BOOST_BUILD_COMMAND} ${BOOST_BUILD_OPTIONS} -j${MAKE_THREADS} architecture=x86 address-model=${BOOST_ADDRESS_MODEL} variant=${BOOST_BUILD_TYPE} link=static threading=multi ${BOOST_OPTIONS} --prefix=${LIBDIR}/boost install + BUILD_COMMAND ${BOOST_BUILD_COMMAND} ${BOOST_BUILD_OPTIONS} -j${MAKE_THREADS} architecture=x86 address-model=${BOOST_ADDRESS_MODEL} link=static threading=multi ${BOOST_OPTIONS} --prefix=${LIBDIR}/boost install BUILD_IN_SOURCE 1 INSTALL_COMMAND "${BOOST_HARVEST_CMD}" ) diff --git a/build_files/build_environment/cmake/bzip2.cmake b/build_files/build_environment/cmake/bzip2.cmake new file mode 100644 index 000000000000..6c515d10d619 --- /dev/null +++ b/build_files/build_environment/cmake/bzip2.cmake @@ -0,0 +1,39 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(BZIP2_PREFIX "${LIBDIR}/bzip2") +set(BZIP2_CONFIGURE_ENV echo .) +set(BZIP2_CONFIGURATION_ARGS) + +if(UNIX AND NOT APPLE) + set(BZIP2_LDFLAGS "-Wl,--as-needed") + set(BZIP2_CFLAGS "-fPIC -Wall -Winline -O2 -g -D_FILE_OFFSET_BITS=64") + set(BZIP2_CONFIGURE_ENV ${BZIP2_CONFIGURE_ENV} && export LDFLAGS=${BZIP2_LDFLAGS} && export CFLAGS=${BZIP2_CFLAGS} + && export PREFIX=${BZIP2_PREFIX}) +endif() + +ExternalProject_Add(external_bzip2 + URL ${BZIP2_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH SHA256=${BZIP2_HASH} + PREFIX ${BUILD_DIR}/bzip2 + CONFIGURE_COMMAND echo . + BUILD_COMMAND ${BZIP2_CONFIGURE_ENV} && cd ${BUILD_DIR}/bzip2/src/external_bzip2/ && make CFLAGS=${BZIP2_CFLAGS} LDFLAGS=${BZIP2_LDFLAGS} -j${MAKE_THREADS} + INSTALL_COMMAND ${BZIP2_CONFIGURE_ENV} && cd ${BUILD_DIR}/bzip2/src/external_bzip2/ && make CFLAGS=${BZIP2_CFLAGS} LDFLAGS=${BZIP2_LDFLAGS} PREFIX=${BZIP2_PREFIX} install + INSTALL_DIR ${LIBDIR}/bzip2 +) diff --git a/build_files/build_environment/cmake/clang.cmake b/build_files/build_environment/cmake/clang.cmake index 9a2705bc8bea..699c38a293af 100644 --- a/build_files/build_environment/cmake/clang.cmake +++ b/build_files/build_environment/cmake/clang.cmake @@ -21,13 +21,22 @@ set(CLANG_EXTRA_ARGS -DCLANG_PATH_TO_LLVM_BUILD=${LIBDIR}/llvm -DLLVM_USE_CRT_RELEASE=MT -DLLVM_USE_CRT_DEBUG=MTd + -DLLVM_CONFIG=${LIBDIR}/llvm/bin/llvm-config ) + +if(WIN32) + set(CLANG_GENERATOR "Ninja") +else() + set(CLANG_GENERATOR "Unix Makefiles") +endif() + + ExternalProject_Add(external_clang URL ${CLANG_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH MD5=${CLANG_HASH} - PATCH_COMMAND ${PATCH_CMD} -p 2 -N -R -d ${BUILD_DIR}/clang/src/external_clang < ${PATCH_DIR}/clang.diff PREFIX ${BUILD_DIR}/clang + CMAKE_GENERATOR ${CLANG_GENERATOR} CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/clang ${DEFAULT_CMAKE_FLAGS} ${CLANG_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/clang ) diff --git a/build_files/build_environment/cmake/faad.cmake b/build_files/build_environment/cmake/faad.cmake index 3dd90971b84d..df940c423a35 100644 --- a/build_files/build_environment/cmake/faad.cmake +++ b/build_files/build_environment/cmake/faad.cmake @@ -18,13 +18,18 @@ set(FAAD_EXTRA_ARGS) +if (WIN32) + set(FAAD_EXTRA_CONFIGURE "utils\\win32\\ac2ver.exe" "faad2" "configure.ac" > libfaad\\win32_ver.h) +else() + set(FAAD_EXTRA_CONFIGURE echo .) +endif() + ExternalProject_Add(external_faad URL ${FAAD_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH MD5=${FAAD_HASH} PREFIX ${BUILD_DIR}/faad - PATCH_COMMAND ${PATCH_CMD} --verbose -p 0 -N -d ${BUILD_DIR}/faad/src/external_faad < ${PATCH_DIR}/libfaad.diff - CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/faad/src/external_faad/ && ${CONFIGURE_COMMAND} --disable-shared --enable-static --prefix=${LIBDIR}/faad + CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/faad/src/external_faad/ && ${FAAD_EXTRA_CONFIGURE} && ${CONFIGURE_COMMAND} --disable-shared --enable-static --prefix=${LIBDIR}/faad BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/faad/src/external_faad/ && make -j${MAKE_THREADS} INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/faad/src/external_faad/ && make install INSTALL_DIR ${LIBDIR}/faad diff --git a/build_files/build_environment/cmake/ffi.cmake b/build_files/build_environment/cmake/ffi.cmake new file mode 100644 index 000000000000..18531fd79067 --- /dev/null +++ b/build_files/build_environment/cmake/ffi.cmake @@ -0,0 +1,38 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +ExternalProject_Add(external_ffi + URL ${FFI_URI} + URL_HASH SHA256=${FFI_HASH} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + PREFIX ${BUILD_DIR}/ffi + CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ffi/src/external_ffi/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/ffi + --enable-shared=no + --enable-static=yes + --with-pic + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ffi/src/external_ffi/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ffi/src/external_ffi/ && make install + INSTALL_DIR ${LIBDIR}/ffi +) + +if (UNIX AND NOT APPLE) + ExternalProject_Add_Step(external_ffi after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/ffi/lib/libffi.a ${LIBDIR}/ffi/lib/libffi_pic.a + DEPENDEES install + ) +endif() diff --git a/build_files/build_environment/cmake/ffmpeg.cmake b/build_files/build_environment/cmake/ffmpeg.cmake index bd49621bf26c..5c8347cd40e1 100644 --- a/build_files/build_environment/cmake/ffmpeg.cmake +++ b/build_files/build_environment/cmake/ffmpeg.cmake @@ -16,10 +16,10 @@ # # ***** END GPL LICENSE BLOCK ***** -set(FFMPEG_CFLAGS "-I${mingw_LIBDIR}/lame/include -I${mingw_LIBDIR}/openjpeg/include/ -I${mingw_LIBDIR}/ogg/include -I${mingw_LIBDIR}/vorbis/include -I${mingw_LIBDIR}/theora/include -I${mingw_LIBDIR}/vpx/include -I${mingw_LIBDIR}/x264/include -I${mingw_LIBDIR}/xvidcore/include -I${mingw_LIBDIR}/dirac/include/dirac -I${mingw_LIBDIR}/schroedinger/include/schroedinger-1.0 -I${mingw_LIBDIR}/zlib/include") -set(FFMPEG_LDFLAGS "-L${mingw_LIBDIR}/lame/lib -L${mingw_LIBDIR}/openjpeg/lib -L${mingw_LIBDIR}/ogg/lib -L${mingw_LIBDIR}/vorbis/lib -L${mingw_LIBDIR}/theora/lib -L${mingw_LIBDIR}/vpx/lib -L${mingw_LIBDIR}/x264/lib -L${mingw_LIBDIR}/xvidcore/lib -L${mingw_LIBDIR}/dirac/lib -L${mingw_LIBDIR}/schroedinger/lib -L${mingw_LIBDIR}/orc/lib -L${mingw_LIBDIR}/zlib/lib") -set(FFMPEG_EXTRA_FLAGS --extra-cflags=${FFMPEG_CFLAGS} --extra-ldflags=${FFMPEG_LDFLAGS}) -set(FFMPEG_ENV PKG_CONFIG_PATH=${mingw_LIBDIR}/schroedinger/lib/pkgconfig:${mingw_LIBDIR}/orc/lib/pkgconfig:${mingw_LIBDIR}/x264/lib/pkgconfig:${mingw_LIBDIR}) +set(FFMPEG_CFLAGS "-I${mingw_LIBDIR}/lame/include -I${mingw_LIBDIR}/openjpeg/include/ -I${mingw_LIBDIR}/ogg/include -I${mingw_LIBDIR}/vorbis/include -I${mingw_LIBDIR}/theora/include -I${mingw_LIBDIR}/vpx/include -I${mingw_LIBDIR}/x264/include -I${mingw_LIBDIR}/xvidcore/include -I${mingw_LIBDIR}/zlib/include") +set(FFMPEG_LDFLAGS "-L${mingw_LIBDIR}/lame/lib -L${mingw_LIBDIR}/openjpeg/lib -L${mingw_LIBDIR}/ogg/lib -L${mingw_LIBDIR}/vorbis/lib -L${mingw_LIBDIR}/theora/lib -L${mingw_LIBDIR}/vpx/lib -L${mingw_LIBDIR}/x264/lib -L${mingw_LIBDIR}/xvidcore/lib -L${mingw_LIBDIR}/zlib/lib") +set(FFMPEG_EXTRA_FLAGS --pkg-config-flags=--static --extra-cflags=${FFMPEG_CFLAGS} --extra-ldflags=${FFMPEG_LDFLAGS}) +set(FFMPEG_ENV PKG_CONFIG_PATH=${mingw_LIBDIR}/openjpeg/lib/pkgconfig:${mingw_LIBDIR}/x264/lib/pkgconfig:${mingw_LIBDIR}/vorbis/lib/pkgconfig:${mingw_LIBDIR}/ogg/lib/pkgconfig:${mingw_LIBDIR}) if(WIN32) set(FFMPEG_ENV set ${FFMPEG_ENV} &&) @@ -31,6 +31,12 @@ if(WIN32) --disable-pthreads --enable-libopenjpeg ) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "4") + set(FFMPEG_EXTRA_FLAGS + ${FFMPEG_EXTRA_FLAGS} + --x86asmexe=yasm + ) + endif() else() set(FFMPEG_EXTRA_FLAGS ${FFMPEG_EXTRA_FLAGS} @@ -51,6 +57,11 @@ ExternalProject_Add(external_ffmpeg URL ${FFMPEG_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH MD5=${FFMPEG_HASH} + # OpenJpeg is compiled with pthread support on Linux, which is all fine and is what we + # want for maximum runtime performance, but due to static nature of that library we + # need to force ffmpeg to link against pthread, otherwise test program used by autoconf + # will fail. This patch does that in a way that is compatible with multiple distributions. + PATCH_COMMAND ${PATCH_CMD} --verbose -p 1 -N -d ${BUILD_DIR}/ffmpeg/src/external_ffmpeg < ${PATCH_DIR}/ffmpeg.diff PREFIX ${BUILD_DIR}/ffmpeg CONFIGURE_COMMAND ${CONFIGURE_ENV_NO_PERL} && cd ${BUILD_DIR}/ffmpeg/src/external_ffmpeg/ && @@ -63,7 +74,6 @@ ExternalProject_Add(external_ffmpeg --disable-libspeex --enable-libvpx --prefix=${LIBDIR}/ffmpeg - --enable-libschroedinger --enable-libtheora --enable-libvorbis --enable-zlib @@ -73,7 +83,6 @@ ExternalProject_Add(external_ffmpeg --disable-nonfree --enable-gpl --disable-postproc - --disable-x11grab --enable-libmp3lame --disable-librtmp --enable-libx264 @@ -91,9 +100,8 @@ ExternalProject_Add(external_ffmpeg --disable-securetransport --disable-indev=avfoundation --disable-indev=qtkit - --disable-sdl + --disable-sdl2 --disable-gnutls - --disable-vda --disable-videotoolbox --disable-libxcb --disable-xlib @@ -103,7 +111,7 @@ ExternalProject_Add(external_ffmpeg --disable-indev=jack --disable-indev=alsa --disable-outdev=alsa - PATCH_COMMAND ${PATCH_CMD} --verbose -p 0 -N -d ${BUILD_DIR}/ffmpeg/src/external_ffmpeg < ${PATCH_DIR}/ffmpeg.diff + --disable-crystalhd BUILD_COMMAND ${CONFIGURE_ENV_NO_PERL} && cd ${BUILD_DIR}/ffmpeg/src/external_ffmpeg/ && make -j${MAKE_THREADS} INSTALL_COMMAND ${CONFIGURE_ENV_NO_PERL} && cd ${BUILD_DIR}/ffmpeg/src/external_ffmpeg/ && make install CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/ffmpeg ${DEFAULT_CMAKE_FLAGS} @@ -121,7 +129,6 @@ add_dependencies( external_openjpeg external_xvidcore external_x264 - external_schroedinger external_vpx external_theora external_vorbis @@ -134,3 +141,11 @@ if(WIN32) external_zlib_mingw ) endif() + +if(BUILD_MODE STREQUAL Release AND WIN32) + ExternalProject_Add_Step(external_ffmpeg after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ffmpeg/include ${HARVEST_TARGET}/ffmpeg/include + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ffmpeg/bin ${HARVEST_TARGET}/ffmpeg/lib + DEPENDEES install + ) +endif() diff --git a/build_files/build_environment/cmake/fftw.cmake b/build_files/build_environment/cmake/fftw.cmake index 3044e28078de..d85d7bc75388 100644 --- a/build_files/build_environment/cmake/fftw.cmake +++ b/build_files/build_environment/cmake/fftw.cmake @@ -37,4 +37,11 @@ ExternalProject_Add(external_fftw3 if(MSVC) set_target_properties(external_fftw3 PROPERTIES FOLDER Mingw) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_fftw3 after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/fftw3/lib/libfftw3.a ${HARVEST_TARGET}/fftw3/lib/libfftw.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/fftw3/include/fftw3.h ${HARVEST_TARGET}/fftw3/include/fftw3.h + DEPENDEES install + ) + endif() endif() diff --git a/build_files/build_environment/cmake/freetype.cmake b/build_files/build_environment/cmake/freetype.cmake index 751b2b1f383e..1034e9f20296 100644 --- a/build_files/build_environment/cmake/freetype.cmake +++ b/build_files/build_environment/cmake/freetype.cmake @@ -16,7 +16,15 @@ # # ***** END GPL LICENSE BLOCK ***** -set(FREETYPE_EXTRA_ARGS -DCMAKE_RELEASE_POSTFIX:STRING=2ST -DCMAKE_DEBUG_POSTFIX:STRING=2ST_d -DWITH_BZip2=OFF -DWITH_HarfBuzz=OFF) +set(FREETYPE_EXTRA_ARGS + -DCMAKE_RELEASE_POSTFIX:STRING=2ST + -DCMAKE_DEBUG_POSTFIX:STRING=2ST_d + -DWITH_BZip2=OFF + -DWITH_HarfBuzz=OFF + -DFT_WITH_HARFBUZZ=OFF + -DFT_WITH_BZIP2=OFF + -DCMAKE_DISABLE_FIND_PACKAGE_HarfBuzz=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_BZip2=TRUE) ExternalProject_Add(external_freetype URL ${FREETYPE_URI} @@ -24,5 +32,13 @@ ExternalProject_Add(external_freetype URL_HASH MD5=${FREETYPE_HASH} PREFIX ${BUILD_DIR}/freetype CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/freetype ${DEFAULT_CMAKE_FLAGS} ${FREETYPE_EXTRA_ARGS} + PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/freetype/src/external_freetype < ${PATCH_DIR}/freetype.diff INSTALL_DIR ${LIBDIR}/freetype ) + +if(BUILD_MODE STREQUAL Release AND WIN32) + ExternalProject_Add_Step(external_freetype after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/freetype ${HARVEST_TARGET}/freetype + DEPENDEES install + ) +endif() diff --git a/build_files/build_environment/cmake/harvest.cmake b/build_files/build_environment/cmake/harvest.cmake index 9ebd5206d27b..d47a5e65d3c9 100644 --- a/build_files/build_environment/cmake/harvest.cmake +++ b/build_files/build_environment/cmake/harvest.cmake @@ -28,43 +28,16 @@ message("HARVEST_TARGET = ${HARVEST_TARGET}") if(WIN32) if(BUILD_MODE STREQUAL Release) add_custom_target(Harvest_Release_Results - # Zlib Rename the lib file and copy the include/bin folders - COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/zlibstatic.lib ${HARVEST_TARGET}/zlib/lib/libz_st.lib && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/zlib/include/ ${HARVEST_TARGET}/zlib/include/ && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/zlib/bin/ ${HARVEST_TARGET}/zlib/bin/ && - # jpeg rename libfile + copy include + COMMAND # jpeg rename libfile + copy include ${CMAKE_COMMAND} -E copy ${LIBDIR}/jpg/lib/jpeg-static.lib ${HARVEST_TARGET}/jpeg/lib/libjpeg.lib && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/jpg/include/ ${HARVEST_TARGET}/jpeg/include/ && - # FreeType, straight up copy - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/freetype ${HARVEST_TARGET}/freetype && - # pthreads, rename include dir - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/pthreads/inc/ ${HARVEST_TARGET}/pthreads/include/ && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/pthreads/lib/ ${HARVEST_TARGET}/pthreads/lib && - # ffmpeg copy include+bin - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ffmpeg/include ${HARVEST_TARGET}/ffmpeg/include && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ffmpeg/bin ${HARVEST_TARGET}/ffmpeg/lib && - # sdl merge bin/lib folder, copy include - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/include/sdl2 ${HARVEST_TARGET}/sdl/include && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/lib ${HARVEST_TARGET}/sdl/lib && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/bin ${HARVEST_TARGET}/sdl/lib && - # openal - ${CMAKE_COMMAND} -E copy ${LIBDIR}/openal/lib/openal32.lib ${HARVEST_TARGET}/openal/lib/openal32.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/openal/bin/openal32.dll ${HARVEST_TARGET}/openal/lib/openal32.dll && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openal/include/ ${HARVEST_TARGET}/openal/include/ && # OpenImageIO ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/OpenImageIO/include ${HARVEST_TARGET}/OpenImageIO/include && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/OpenImageIO/lib ${HARVEST_TARGET}/OpenImageIO/lib && ${CMAKE_COMMAND} -E copy ${LIBDIR}/OpenImageIO/bin/idiff.exe ${HARVEST_TARGET}/OpenImageIO/bin/idiff.exe && - # openEXR - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ilmbase ${HARVEST_TARGET}/openexr && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openexr/lib ${HARVEST_TARGET}/openexr/lib && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openexr/include ${HARVEST_TARGET}/openexr/include && # png ${CMAKE_COMMAND} -E copy ${LIBDIR}/png/lib/libpng16_static.lib ${HARVEST_TARGET}/png/lib/libpng.lib && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/png/include/ ${HARVEST_TARGET}/png/include/ && - # fftw3 - ${CMAKE_COMMAND} -E copy ${LIBDIR}/fftw3/lib/libfftw3.a ${HARVEST_TARGET}/fftw3/lib/libfftw.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/fftw3/include/fftw3.h ${HARVEST_TARGET}/fftw3/include/fftw3.h && # freeglut-> opengl ${CMAKE_COMMAND} -E copy ${LIBDIR}/freeglut/lib/freeglut_static.lib ${HARVEST_TARGET}/opengl/lib/freeglut_static.lib && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/freeglut/include/ ${HARVEST_TARGET}/opengl/include/ && @@ -78,37 +51,9 @@ if(BUILD_MODE STREQUAL Release) # tiff ${CMAKE_COMMAND} -E copy ${LIBDIR}/tiff/lib/tiff.lib ${HARVEST_TARGET}/tiff/lib/libtiff.lib && ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/tiff/include/ ${HARVEST_TARGET}/tiff/include/ && - # iconv - ${CMAKE_COMMAND} -E copy ${LIBDIR}/iconv/lib/libiconv.a ${HARVEST_TARGET}/iconv/lib/iconv.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/iconv/include/iconv.h ${HARVEST_TARGET}/iconv/include/iconv.h && - # opencolorIO - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/OpenColorIO/ ${HARVEST_TARGET}/opencolorio && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/OpenColorIO/lib/OpenColorIO.dll ${HARVEST_TARGET}/opencolorio/bin/OpenColorIO.dll && - # Osl - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/osl/ ${HARVEST_TARGET}/osl && - # OpenVDB - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openVDB/ ${HARVEST_TARGET}/openVDB && - # blosc - ${CMAKE_COMMAND} -E copy ${LIBDIR}/blosc/lib/libblosc.lib ${HARVEST_TARGET}/blosc/lib/libblosc.lib && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/blosc/include/ ${HARVEST_TARGET}/blosc/include/ && - # tbb - ${CMAKE_COMMAND} -E copy ${LIBDIR}/tbb/lib/tbb_static.lib ${HARVEST_TARGET}/tbb/lib/tbb.lib && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/tbb/include/ ${HARVEST_TARGET}/tbb/include/ && - # opencollada - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opencollada/ ${HARVEST_TARGET}/opencollada/ && - # opensubdiv - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opensubdiv ${HARVEST_TARGET}/opensubdiv && - # python - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/python/ ${HARVEST_TARGET}/python/ && - # alembic - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/alembic ${HARVEST_TARGET}/alembic && # BlendThumb ${CMAKE_COMMAND} -E copy ${LIBDIR}/BlendThumb64/bin/blendthumb.dll ${HARVEST_TARGET}/ThumbHandler/lib/BlendThumb64.dll && ${CMAKE_COMMAND} -E copy ${LIBDIR}/BlendThumb32/bin/blendthumb.dll ${HARVEST_TARGET}/ThumbHandler/lib/BlendThumb.dll && - # python - ${CMAKE_COMMAND} -E copy ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}.tar.gz ${HARVEST_TARGET}/Release/python${PYTHON_SHORT_VERSION_NO_DOTS}.tar.gz && - # numpy - ${CMAKE_COMMAND} -E copy ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}_numpy_${NUMPY_SHORT_VERSION}.tar.gz ${HARVEST_TARGET}/Release/python${PYTHON_SHORT_VERSION_NO_DOTS}_numpy_${NUMPY_SHORT_VERSION}.tar.gz && # hidapi ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/hidapi/ ${HARVEST_TARGET}/hidapi/ && # webp, straight up copy @@ -122,43 +67,8 @@ if(BUILD_MODE STREQUAL Debug) # OpenImageIO COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openimageio/lib/OpenImageIO.lib ${HARVEST_TARGET}/openimageio/lib/OpenImageIO_d.lib && ${CMAKE_COMMAND} -E copy ${LIBDIR}/openimageio/lib/OpenImageIO_Util.lib ${HARVEST_TARGET}/openimageio/lib/OpenImageIO_Util_d.lib && - # ilmbase+openexr - ${CMAKE_COMMAND} -E copy ${LIBDIR}/ilmbase/lib/Half.lib ${HARVEST_TARGET}/openexr/lib/Half_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/ilmbase/lib/Iex-2_2.lib ${HARVEST_TARGET}/openexr/lib/Iex-2_2_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/ilmbase/lib/IexMath-2_2.lib ${HARVEST_TARGET}/openexr/lib/IexMath-2_2_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/ilmbase/lib/IlmThread-2_2.lib ${HARVEST_TARGET}/openexr/lib/IlmThread-2_2_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/ilmbase/lib/Imath-2_2.lib ${HARVEST_TARGET}/openexr/lib/Imath-2_2_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/openexr/lib/IlmImf-2_2.lib ${HARVEST_TARGET}/openexr/lib/IlmImf-2_2_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/openexr/lib/IlmImfUtil-2_2.lib ${HARVEST_TARGET}/openexr/lib/IlmImfUtil-2_2_d.lib && - # opencollada - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/buffer.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/buffer_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/ftoa.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/ftoa_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/GeneratedSaxParser.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/GeneratedSaxParser_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/MathMLSolver.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/MathMLSolver_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADABaseUtils.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADABaseUtils_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADAFramework.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADAFramework_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADASaxFrameworkLoader.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADASaxFrameworkLoader_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADAStreamWriter.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADAStreamWriter_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/pcre.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/pcre_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/UTF.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/UTF_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/xml.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/xml_d.lib && - # blosc - ${CMAKE_COMMAND} -E copy ${LIBDIR}/blosc/lib/libblosc_d.lib ${HARVEST_TARGET}/blosc/lib/libblosc_d.lib && - # osl - ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslcomp.lib ${HARVEST_TARGET}/osl/lib/oslcomp_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslexec.lib ${HARVEST_TARGET}/osl/lib/oslexec_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslquery.lib ${HARVEST_TARGET}/osl/lib/oslquery_d.lib && - # opensubdiv - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opensubdiv/lib/osdCPU.lib ${HARVEST_TARGET}/opensubdiv/lib/osdCPU_d.lib && - ${CMAKE_COMMAND} -E copy ${LIBDIR}/opensubdiv/lib/osdGPU.lib ${HARVEST_TARGET}/opensubdiv/lib/osdGPU_d.lib && - # tbb - ${CMAKE_COMMAND} -E copy ${LIBDIR}/tbb/lib/tbb_static.lib ${HARVEST_TARGET}/tbb/lib/tbb_debug.lib && - # openvdb - ${CMAKE_COMMAND} -E copy ${LIBDIR}/openvdb/lib/openvdb.lib ${HARVEST_TARGET}/openvdb/lib/openvdb_d.lib && # python ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/python/ ${HARVEST_TARGET}/python/ && - # alembic - ${CMAKE_COMMAND} -E copy ${LIBDIR}/alembic/lib/alembic.lib ${HARVEST_TARGET}/alembic/lib/alembic_d.lib && # hdf5 ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/hdf5/lib ${HARVEST_TARGET}/hdf5/lib && # numpy @@ -200,8 +110,6 @@ endfunction() harvest(alembic/include alembic/include "*.h") harvest(alembic/lib/libAlembic.a alembic/lib/libAlembic.a) -harvest(alembic/bin alembic/bin "*") -harvest(blosc/lib openvdb/lib "*.a") harvest(boost/include boost/include "*") harvest(boost/lib boost/lib "*.a") harvest(ffmpeg/include ffmpeg/include "*.h") @@ -226,11 +134,24 @@ harvest(ogg/lib ffmpeg/lib "*.a") harvest(openal/include openal/include "*.h") if(UNIX AND NOT APPLE) harvest(openal/lib openal/lib "*.a") + + harvest(blosc/include blosc/include "*.h") + harvest(blosc/lib blosc/lib "*.a") + + harvest(zlib/include zlib/include "*.h") + harvest(zlib/lib zlib/lib "*.a") + + harvest(xml2/include xml2/include "*.h") + harvest(xml2/lib xml2/lib "*.a") +else() + harvest(blosc/lib openvdb/lib "*.a") + harvest(xml2/lib opencollada/lib "*.a") endif() harvest(opencollada/include/opencollada opencollada/include "*.h") harvest(opencollada/lib/opencollada opencollada/lib "*.a") harvest(opencolorio/include opencolorio/include "*.h") harvest(opencolorio/lib opencolorio/lib "*.a") +harvest(opencolorio/lib/static opencolorio/lib "*.a") harvest(openexr/include openexr/include "*.h") harvest(openexr/lib openexr/lib "*.a") harvest(openimageio/bin openimageio/bin "idiff") @@ -238,13 +159,12 @@ harvest(openimageio/bin openimageio/bin "maketx") harvest(openimageio/bin openimageio/bin "oiiotool") harvest(openimageio/include openimageio/include "*") harvest(openimageio/lib openimageio/lib "*.a") -harvest(openjpeg/include/openjpeg-1.5 openjpeg/include "*.h") +harvest(openjpeg/include/openjpeg-2.3 openjpeg/include "*.h") harvest(openjpeg/lib openjpeg/lib "*.a") harvest(opensubdiv/include opensubdiv/include "*.h") harvest(opensubdiv/lib opensubdiv/lib "*.a") -harvest(openvdb/include/openvdb/openvdb openvdb/include/openvdb "*.h") +harvest(openvdb/include/openvdb openvdb/include/openvdb "*.h") harvest(openvdb/lib openvdb/lib "*.a") -harvest(orc/lib/liborc-0.4.a ffmpeg/lib/liborc.a) harvest(osl/bin osl/bin "oslc") harvest(osl/include osl/include "*.h") harvest(osl/lib osl/lib "*.a") @@ -254,7 +174,6 @@ harvest(png/lib png/lib "*.a") harvest(python/bin python/bin "python${PYTHON_SHORT_VERSION}m") harvest(python/include python/include "*h") harvest(python/lib python/lib "*") -harvest(schroedinger/lib/libschroedinger-1.0.a ffmpeg/lib/libschroedinger.a) harvest(sdl/include/SDL2 sdl/include "*.h") harvest(sdl/lib sdl/lib "libSDL2.a") harvest(sndfile/include sndfile/include "*.h") @@ -270,7 +189,6 @@ harvest(vorbis/lib ffmpeg/lib "*.a") harvest(vpx/lib ffmpeg/lib "*.a") harvest(webp/lib ffmpeg/lib "*.a") harvest(x264/lib ffmpeg/lib "*.a") -harvest(xml2/lib opencollada/lib "*.a") harvest(xvidcore/lib ffmpeg/lib "*.a") endif() diff --git a/build_files/build_environment/cmake/iconv.cmake b/build_files/build_environment/cmake/iconv.cmake index cd6cf9547df0..18f8f60b4f50 100644 --- a/build_files/build_environment/cmake/iconv.cmake +++ b/build_files/build_environment/cmake/iconv.cmake @@ -31,4 +31,11 @@ ExternalProject_Add(external_iconv if(MSVC) set_target_properties(external_iconv PROPERTIES FOLDER Mingw) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_iconv after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/iconv/lib/libiconv.a ${HARVEST_TARGET}/iconv/lib/iconv.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/iconv/include/iconv.h ${HARVEST_TARGET}/iconv/include/iconv.h + DEPENDEES install + ) + endif() endif() diff --git a/build_files/build_environment/cmake/ilmbase.cmake b/build_files/build_environment/cmake/ilmbase.cmake index 0639848346f4..22be39c3ff1a 100644 --- a/build_files/build_environment/cmake/ilmbase.cmake +++ b/build_files/build_environment/cmake/ilmbase.cmake @@ -18,18 +18,41 @@ if(WIN32) set(ILMBASE_CMAKE_CXX_STANDARD_LIBRARIES "kernel32${LIBEXT} user32${LIBEXT} gdi32${LIBEXT} winspool${LIBEXT} shell32${LIBEXT} ole32${LIBEXT} oleaut32${LIBEXT} uuid${LIBEXT} comdlg32${LIBEXT} advapi32${LIBEXT} psapi${LIBEXT}") -endif() + set(ILMBASE_EXTRA_ARGS + -DBUILD_SHARED_LIBS=OFF + -DCMAKE_CXX_STANDARD_LIBRARIES=${ILMBASE_CMAKE_CXX_STANDARD_LIBRARIES} + ) + + ExternalProject_Add(external_ilmbase + URL ${ILMBASE_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${ILMBASE_HASH} + PREFIX ${BUILD_DIR}/ilmbase + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/ilmbase ${DEFAULT_CMAKE_FLAGS} ${ILMBASE_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/openexr + ) -set(ILMBASE_EXTRA_ARGS - -DBUILD_SHARED_LIBS=OFF - -DCMAKE_CXX_STANDARD_LIBRARIES=${ILMBASE_CMAKE_CXX_STANDARD_LIBRARIES} -) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_ilmbase after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/ilmbase ${HARVEST_TARGET}/openexr + DEPENDEES install + ) + endif() -ExternalProject_Add(external_ilmbase - URL ${ILMBASE_URI} - DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH MD5=${ILMBASE_HASH} - PREFIX ${BUILD_DIR}/ilmbase - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/ilmbase ${DEFAULT_CMAKE_FLAGS} ${ILMBASE_EXTRA_ARGS} - INSTALL_DIR ${LIBDIR}/openexr -) +else() + set(ILMBASE_EXTRA_ARGS + --enable-static + --disable-shared + --enable-cxxstd=11 + ) + ExternalProject_Add(external_ilmbase + URL ${ILMBASE_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${ILMBASE_HASH} + PREFIX ${BUILD_DIR}/ilmbase + CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ilmbase/src/external_ilmbase/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/ilmbase ${ILMBASE_EXTRA_ARGS} + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ilmbase/src/external_ilmbase/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ilmbase/src/external_ilmbase/ && make install + INSTALL_DIR ${LIBDIR}/openexr + ) +endif() diff --git a/build_files/build_environment/cmake/jpeg.cmake b/build_files/build_environment/cmake/jpeg.cmake index 1f2b04387f02..9975bb9c4f60 100644 --- a/build_files/build_environment/cmake/jpeg.cmake +++ b/build_files/build_environment/cmake/jpeg.cmake @@ -18,7 +18,7 @@ if(WIN32) # cmake for windows - set(JPEG_EXTRA_ARGS -DWITH_JPEG8=ON -DCMAKE_DEBUG_POSTFIX=d) + set(JPEG_EXTRA_ARGS -DNASM=${NASM_PATH} -DWITH_JPEG8=ON -DCMAKE_DEBUG_POSTFIX=d) ExternalProject_Add(external_jpeg URL ${JPEG_URI} diff --git a/build_files/build_environment/cmake/lame.cmake b/build_files/build_environment/cmake/lame.cmake index a489b2302ce0..b7b9275bf5ee 100644 --- a/build_files/build_environment/cmake/lame.cmake +++ b/build_files/build_environment/cmake/lame.cmake @@ -36,7 +36,7 @@ ExternalProject_Add(external_lame --disable-mp3x --disable-mp3rtp --disable-gtktest - --enable-export=full + --disable-frontend BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lame/src/external_lame/ && make -j${MAKE_THREADS} INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lame/src/external_lame/ && make install INSTALL_DIR ${LIBDIR}/lame diff --git a/build_files/build_environment/cmake/lapack.cmake b/build_files/build_environment/cmake/lapack.cmake deleted file mode 100644 index 3110503db52f..000000000000 --- a/build_files/build_environment/cmake/lapack.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# ***** END GPL LICENSE BLOCK ***** - -set(LAPACK_EXTRA_ARGS) - -if(WIN32) - if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - set(LAPACK_EXTRA_ARGS -G "MSYS Makefiles" -DCMAKE_Fortran_COMPILER=${DOWNLOAD_DIR}/mingw/mingw64/bin/gfortran.exe) - else() - set(LAPACK_EXTRA_ARGS -G "MSYS Makefiles" -DCMAKE_Fortran_COMPILER=${DOWNLOAD_DIR}/mingw/mingw32/bin/gfortran.exe) - endif() -endif() - -ExternalProject_Add(external_lapack - URL ${LAPACK_URI} - DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH MD5=${LAPACK_HASH} - PREFIX ${BUILD_DIR}/lapack - CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lapack/src/external_lapack/ && ${CMAKE_COMMAND} ${LAPACK_EXTRA_ARGS} -DBUILD_TESTING=Off -DCMAKE_INSTALL_PREFIX=${LIBDIR}/lapack . - BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lapack/src/external_lapack/ && make -j${MAKE_THREADS} - INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lapack/src/external_lapack/ && make install - - INSTALL_DIR ${LIBDIR}/lapack -) - -if(MSVC) - set_target_properties(external_lapack PROPERTIES FOLDER Mingw) -endif() diff --git a/build_files/build_environment/cmake/orc.cmake b/build_files/build_environment/cmake/lcms.cmake similarity index 59% rename from build_files/build_environment/cmake/orc.cmake rename to build_files/build_environment/cmake/lcms.cmake index aac7884f49e6..852d2b8d04ce 100644 --- a/build_files/build_environment/cmake/orc.cmake +++ b/build_files/build_environment/cmake/lcms.cmake @@ -16,17 +16,16 @@ # # ***** END GPL LICENSE BLOCK ***** -ExternalProject_Add(external_orc - URL ${ORC_URI} - DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH SHA256=${ORC_HASH} - PREFIX ${BUILD_DIR}/orc - CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/orc/src/external_orc/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/orc --disable-shared --enable-static - BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/orc/src/external_orc/ && make -j${MAKE_THREADS} - INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/orc/src/external_orc/ && make install - INSTALL_DIR ${LIBDIR}/orc +set(LCMS_EXTRA_ARGS ) -if(MSVC) - set_target_properties(external_orc PROPERTIES FOLDER Mingw) -endif() +ExternalProject_Add(external_lcms + URL ${LCMS_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${LCMS_HASH} + PREFIX ${BUILD_DIR}/lcms + #patch taken from ocio + PATCH_COMMAND ${CMAKE_COMMAND} -E copy ${PATCH_DIR}/cmakelists_lcms.txt ${BUILD_DIR}/lcms/src/external_lcms/CMakeLists.txt + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/lcms ${DEFAULT_CMAKE_FLAGS} ${LCMS_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/lcms +) diff --git a/build_files/build_environment/cmake/llvm.cmake b/build_files/build_environment/cmake/llvm.cmake index 60f94b3a4992..1aa31bc9d32e 100644 --- a/build_files/build_environment/cmake/llvm.cmake +++ b/build_files/build_environment/cmake/llvm.cmake @@ -26,7 +26,7 @@ set(LLVM_EXTRA_ARGS ) if(WIN32) - set(LLVM_GENERATOR "NMake Makefiles") + set(LLVM_GENERATOR "Ninja") else() set(LLVM_GENERATOR "Unix Makefiles") endif() @@ -38,7 +38,6 @@ ExternalProject_Add(ll URL_HASH MD5=${LLVM_HASH} CMAKE_GENERATOR ${LLVM_GENERATOR} PREFIX ${BUILD_DIR}/ll - PATCH_COMMAND ${PATCH_CMD} -p 0 -d ${BUILD_DIR}/ll/src/ll < ${PATCH_DIR}/llvm-alloca-fix.diff CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/llvm ${DEFAULT_CMAKE_FLAGS} ${LLVM_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/llvm ) @@ -48,9 +47,7 @@ if(MSVC) set(LLVM_HARVEST_COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/llvm/ ${HARVEST_TARGET}/llvm/ ) else() set(LLVM_HARVEST_COMMAND - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/llvm/lib/ ${HARVEST_TARGET}/llvm/debug/lib/ && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/llvm/bin/ ${HARVEST_TARGET}/llvm/debug/bin/ && - ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/llvm/include/ ${HARVEST_TARGET}/llvm/debug/include/ + ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/llvm/lib/ ${HARVEST_TARGET}/llvm/debug/lib/ ) endif() ExternalProject_Add_Step(ll after_install @@ -58,4 +55,3 @@ if(MSVC) DEPENDEES mkdir update patch download configure build install ) endif() - diff --git a/build_files/build_environment/cmake/lzma.cmake b/build_files/build_environment/cmake/lzma.cmake new file mode 100644 index 000000000000..ef8adde29302 --- /dev/null +++ b/build_files/build_environment/cmake/lzma.cmake @@ -0,0 +1,32 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(LZMA_PATCH_CMD echo .) + +ExternalProject_Add(external_lzma + URL ${LZMA_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH SHA256=${LZMA_HASH} + PREFIX ${BUILD_DIR}/lzma + PATCH_COMMAND ${LZMA_PATCH_CMD} + CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lzma/src/external_lzma/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/lzma + --disable-shared + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lzma/src/external_lzma/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/lzma/src/external_lzma/ && make install + INSTALL_DIR ${LIBDIR}/lzma +) diff --git a/build_files/build_environment/cmake/numpy.cmake b/build_files/build_environment/cmake/numpy.cmake index 0d5d8abf7ab4..698fae4f666d 100644 --- a/build_files/build_environment/cmake/numpy.cmake +++ b/build_files/build_environment/cmake/numpy.cmake @@ -36,7 +36,6 @@ if(WIN32) ${CMAKE_COMMAND} -E chdir "${BUILD_DIR}/numpy/src/external_numpy/build/lib.${PYTHON_ARCH2}-${PYTHON_SHORT_VERSION}${NUMPY_DIR_POSTFIX}" ${CMAKE_COMMAND} -E tar "cfvz" "${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}_numpy_${NUMPY_SHORT_VERSION}${NUMPY_ARCHIVE_POSTFIX}.tar.gz" "." ) - set(NUMPY_PATCH ${PATCH_CMD} --verbose -p 1 -N -d ${BUILD_DIR}/numpy/src/external_numpy < ${PATCH_DIR}/numpy.diff ) else() set(NUMPY_INSTALL echo .) set(NUMPY_PATCH echo .) @@ -54,6 +53,13 @@ ExternalProject_Add(external_numpy INSTALL_COMMAND ${NUMPY_INSTALL} ) +if(WIN32) + ExternalProject_Add_Step(external_numpy after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}_numpy_${NUMPY_SHORT_VERSION}${NUMPY_ARCHIVE_POSTFIX}.tar.gz ${HARVEST_TARGET}/Release/python${PYTHON_SHORT_VERSION_NO_DOTS}_numpy_${NUMPY_SHORT_VERSION}${NUMPY_ARCHIVE_POSTFIX}.tar.gz + DEPENDEES install + ) +endif() + add_dependencies( external_numpy Make_Python_Environment diff --git a/build_files/build_environment/cmake/openal.cmake b/build_files/build_environment/cmake/openal.cmake index 0bc0452dd8cd..3cd3a0aac728 100644 --- a/build_files/build_environment/cmake/openal.cmake +++ b/build_files/build_environment/cmake/openal.cmake @@ -41,4 +41,14 @@ if(BUILD_MODE STREQUAL Release) INSTALL_DIR ${LIBDIR}/openal PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/openal/src/external_openal < ${PATCH_DIR}/openal.diff ) + + if(WIN32) + ExternalProject_Add_Step(external_openal after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openal/lib/openal32.lib ${HARVEST_TARGET}/openal/lib/openal32.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openal/bin/openal32.dll ${HARVEST_TARGET}/openal/lib/openal32.dll + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openal/include/ ${HARVEST_TARGET}/openal/include/ + DEPENDEES install + ) + endif() + endif() diff --git a/build_files/build_environment/cmake/opencollada.cmake b/build_files/build_environment/cmake/opencollada.cmake index 3872b08ced22..2f5360ba958f 100644 --- a/build_files/build_environment/cmake/opencollada.cmake +++ b/build_files/build_environment/cmake/opencollada.cmake @@ -38,3 +38,28 @@ if(UNIX AND NOT APPLE) external_xml2 ) endif() + +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_opencollada after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opencollada/ ${HARVEST_TARGET}/opencollada/ + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_opencollada after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/buffer.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/buffer_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/ftoa.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/ftoa_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/GeneratedSaxParser.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/GeneratedSaxParser_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/MathMLSolver.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/MathMLSolver_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADABaseUtils.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADABaseUtils_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADAFramework.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADAFramework_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADASaxFrameworkLoader.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADASaxFrameworkLoader_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/OpenCOLLADAStreamWriter.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/OpenCOLLADAStreamWriter_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/pcre.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/pcre_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/UTF.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/UTF_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencollada/lib/opencollada/xml.lib ${HARVEST_TARGET}/opencollada/lib/opencollada/xml_d.lib + DEPENDEES install + ) + endif() +endif() \ No newline at end of file diff --git a/build_files/build_environment/cmake/opencolorio.cmake b/build_files/build_environment/cmake/opencolorio.cmake index d33c03eaa8d1..c0187e8a27e0 100644 --- a/build_files/build_environment/cmake/opencolorio.cmake +++ b/build_files/build_environment/cmake/opencolorio.cmake @@ -17,34 +17,46 @@ # ***** END GPL LICENSE BLOCK ***** set(OPENCOLORIO_EXTRA_ARGS - -DBoost_COMPILER:STRING=${BOOST_COMPILER_STRING} - -DBoost_USE_MULTITHREADED=ON - -DBoost_USE_STATIC_LIBS=ON - -DBoost_USE_STATIC_RUNTIME=ON - -DBOOST_ROOT=${LIBDIR}/boost - -DBOOST_INCLUDEDIR=${LIBDIR}/boost/include/boost_1_60/boost - -DBoost_NO_SYSTEM_PATHS=ON - -DBoost_DEBUG=ON - -DBoost_MAJOR_VERSION=1 - -DBoost_MINOR_VERSION=60 -DOCIO_BUILD_APPS=OFF -DOCIO_BUILD_PYGLUE=OFF -DOCIO_BUILD_NUKE=OFF + -DOCIO_USE_BOOST_PTR=OFF + -DOCIO_BUILD_STATIC=ON + -DOCIO_BUILD_SHARED=OFF + -DOCIO_BUILD_TRUELIGHT=OFF + -DOCIO_BUILD_DOCS=OFF + -DOCIO_BUILD_PYGLUE=OFF + -DOCIO_BUILD_JNIGLUE=OFF + -DOCIO_STATIC_JNIGLUE=OFF ) if(WIN32) + set(OCIO_PATCH opencolorio_win.diff) set(OPENCOLORIO_EXTRA_ARGS ${OPENCOLORIO_EXTRA_ARGS} - -DOCIO_USE_BOOST_PTR=ON - -DOCIO_BUILD_STATIC=OFF - -DOCIO_BUILD_SHARED=ON + -DOCIO_BUILD_TESTS=OFF + -DOCIO_USE_SSE=ON + -DOCIO_INLINES_HIDDEN=OFF + -DOCIO_PYGLUE_LINK=OFF + -DOCIO_PYGLUE_RESPECT_ABI=OFF + -DOCIO_PYGLUE_SONAME=OFF + -DOCIO_PYGLUE_LIB_PREFIX=OFF + -DUSE_EXTERNAL_TINYXML=ON + -DTINYXML_INCLUDE_DIR=${LIBDIR}/tinyxml/include + -DTINYXML_LIBRARY=${LIBDIR}/tinyxml/lib/tinyxml${libext} + -DUSE_EXTERNAL_YAML=ON + -DYAML_CPP_FOUND=ON + -DYAML_CPP_VERSION=${YAMLCPP_VERSION} + -DUSE_EXTERNAL_LCMS=ON + -DINC_1=${LIBDIR}/tinyxml/include + -DINC_2=${LIBDIR}/yamlcpp/include + #lie because ocio cmake is demanding boost even though it is not needed + -DYAML_CPP_VERSION=0.5.0 ) else() + set(OCIO_PATCH opencolorio.diff) set(OPENCOLORIO_EXTRA_ARGS ${OPENCOLORIO_EXTRA_ARGS} - -DOCIO_USE_BOOST_PTR=OFF - -DOCIO_BUILD_STATIC=ON - -DOCIO_BUILD_SHARED=OFF ) endif() @@ -53,7 +65,7 @@ ExternalProject_Add(external_opencolorio DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH MD5=${OPENCOLORIO_HASH} PREFIX ${BUILD_DIR}/opencolorio - PATCH_COMMAND ${PATCH_CMD} -p 0 -N -d ${BUILD_DIR}/opencolorio/src/external_opencolorio < ${PATCH_DIR}/opencolorio.diff + PATCH_COMMAND ${PATCH_CMD} -p 1 -N -d ${BUILD_DIR}/opencolorio/src/external_opencolorio < ${PATCH_DIR}/${OCIO_PATCH} CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/opencolorio ${DEFAULT_CMAKE_FLAGS} ${OPENCOLORIO_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/opencolorio ) @@ -71,3 +83,30 @@ add_dependencies( external_opencolorio external_boost ) + +if(WIN32) + add_dependencies( + external_opencolorio + external_tinyxml + external_yamlcpp + + ) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_opencolorio after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opencolorio/include ${HARVEST_TARGET}/opencolorio/include + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opencolorio/lib/static ${HARVEST_TARGET}/opencolorio/lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/yamlcpp/lib/libyaml-cppmt.lib ${HARVEST_TARGET}/opencolorio/lib/libyaml-cpp.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/tinyxml/lib/tinyxml.lib ${HARVEST_TARGET}/opencolorio/lib/tinyxml.lib + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_opencolorio after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opencolorio/lib/static/Opencolorio.lib ${HARVEST_TARGET}/opencolorio/lib/OpencolorIO_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/yamlcpp/lib/libyaml-cppmtd.lib ${HARVEST_TARGET}/opencolorio/lib/libyaml-cpp_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/tinyxml/lib/tinyxml.lib ${HARVEST_TARGET}/opencolorio/lib/tinyxml_d.lib + DEPENDEES install + ) + endif() + +endif() diff --git a/build_files/build_environment/cmake/openexr.cmake b/build_files/build_environment/cmake/openexr.cmake index 36283951750f..59e9a46b4f8a 100644 --- a/build_files/build_environment/cmake/openexr.cmake +++ b/build_files/build_environment/cmake/openexr.cmake @@ -18,25 +18,58 @@ if(WIN32) set(OPENEXR_CMAKE_CXX_STANDARD_LIBRARIES "kernel32${LIBEXT} user32${LIBEXT} gdi32${LIBEXT} winspool${LIBEXT} shell32${LIBEXT} ole32${LIBEXT} oleaut32${LIBEXT} uuid${LIBEXT} comdlg32${LIBEXT} advapi32${LIBEXT} psapi${LIBEXT}") -endif() + set(OPENEXR_EXTRA_ARGS + -DCMAKE_CXX_STANDARD_LIBRARIES=${OPENEXR_CMAKE_CXX_STANDARD_LIBRARIES} + -DZLIB_LIBRARY=${LIBDIR}/zlib/lib/${ZLIB_LIBRARY} + -DZLIB_INCLUDE_DIR=${LIBDIR}/zlib/include/ + -DILMBASE_PACKAGE_PREFIX=${LIBDIR}/ilmbase + -DOPENEXR_BUILD_ILMBASE=On + -DOPENEXR_BUILD_OPENEXR=On + -DOPENEXR_BUILD_PYTHON_LIBS=Off + -DOPENEXR_BUILD_STATIC=On + -DOPENEXR_BUILD_SHARED=Off + -DOPENEXR_BUILD_TESTS=Off + -DOPENEXR_BUILD_VIEWERS=Off + -DOPENEXR_BUILD_UTILS=Off + -DOPENEXR_NAMESPACE_VERSIONING=Off + ) + ExternalProject_Add(external_openexr + URL ${OPENEXR_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${OPENEXR_HASH} + PREFIX ${BUILD_DIR}/openexr + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openexr ${DEFAULT_CMAKE_FLAGS} ${OPENEXR_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/openexr + ) -set(OPENEXR_EXTRA_ARGS - -DBUILD_SHARED_LIBS=OFF - -DCMAKE_CXX_STANDARD_LIBRARIES=${OPENEXR_CMAKE_CXX_STANDARD_LIBRARIES} - -DZLIB_LIBRARY=${LIBDIR}/zlib/lib/${ZLIB_LIBRARY} - -DZLIB_INCLUDE_DIR=${LIBDIR}/zlib/include/ - -DILMBASE_PACKAGE_PREFIX=${LIBDIR}/ilmbase -) + ExternalProject_Add_Step(external_openexr after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openexr/lib ${HARVEST_TARGET}/openexr/lib + #libs have moved between versions, just duplicate it for now. + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openexr/lib ${LIBDIR}/ilmbase/lib + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openexr/include ${HARVEST_TARGET}/openexr/include + DEPENDEES install + ) -ExternalProject_Add(external_openexr - URL ${OPENEXR_URI} - DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH MD5=${OPENEXR_HASH} - PREFIX ${BUILD_DIR}/openexr - PATCH_COMMAND ${PATCH_CMD} -p 0 -d ${BUILD_DIR}/openexr/src/external_openexr < ${PATCH_DIR}/openexr.diff - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openexr ${DEFAULT_CMAKE_FLAGS} ${OPENEXR_EXTRA_ARGS} - INSTALL_DIR ${LIBDIR}/openexr -) +else() + set(OPENEXR_PKG_CONFIG_PATH ${LIBDIR}/zlib/share/pkgconfig) + set(OPENEXR_EXTRA_ARGS + --enable-static + --disable-shared + --enable-cxxstd=11 + --with-ilmbase-prefix=${LIBDIR}/ilmbase + ) + + ExternalProject_Add(external_openexr + URL ${OPENEXR_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${OPENEXR_HASH} + PREFIX ${BUILD_DIR}/openexr + CONFIGURE_COMMAND ${CONFIGURE_ENV} && export PKG_CONFIG_PATH=${OPENEXR_PKG_CONFIG_PATH} && cd ${BUILD_DIR}/openexr/src/external_openexr/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/openexr ${OPENEXR_EXTRA_ARGS} + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/openexr/src/external_openexr/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/openexr/src/external_openexr/ && make install + INSTALL_DIR ${LIBDIR}/openexr + ) +endif() add_dependencies( external_openexr diff --git a/build_files/build_environment/cmake/openimageio.cmake b/build_files/build_environment/cmake/openimageio.cmake index fdc71508e472..73d1f4a78712 100644 --- a/build_files/build_environment/cmake/openimageio.cmake +++ b/build_files/build_environment/cmake/openimageio.cmake @@ -51,8 +51,8 @@ if(MSVC) set(OPENJPEG_FLAGS -DOPENJPEG_HOME=${LIBDIR}/openjpeg_msvc -DOPENJPEG_INCLUDE_DIR=${LIBDIR}/openjpeg_msvc/include/openjpeg-${OPENJPEG_SHORT_VERSION} - -DOPENJPEG_LIBRARY=${LIBDIR}/openjpeg_msvc/lib/openjpeg${LIBEXT} - -DOPENJPEG_LIBRARY_DEBUG=${LIBDIR}/openjpeg_msvc/lib/openjpeg${LIBEXT} + -DOPENJPEG_LIBRARY=${LIBDIR}/openjpeg_msvc/lib/openjp2${LIBEXT} + -DOPENJPEG_LIBRARY_DEBUG=${LIBDIR}/openjpeg_msvc/lib/openjp2${LIBEXT} ) else() set(OPENJPEG_FLAGS @@ -65,7 +65,7 @@ set(OPENIMAGEIO_EXTRA_ARGS -DBUILDSTATIC=ON ${OPENIMAGEIO_LINKSTATIC} -DOPENEXR_INCLUDE_DIR=${LIBDIR}/openexr/include/openexr/ - -DOPENEXR_ILMIMF_LIBRARIES=${LIBDIR}/openexr/lib/IlmImf-2_2${LIBEXT} + -DOPENEXR_ILMIMF_LIBRARIES=${LIBDIR}/openexr/lib/IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT} -DBoost_COMPILER:STRING=${BOOST_COMPILER_STRING} -DBoost_USE_MULTITHREADED=ON -DBoost_USE_STATIC_LIBS=ON @@ -109,12 +109,12 @@ set(OPENIMAGEIO_EXTRA_ARGS -DILMBASE_INCLUDE_PATH=${LIBDIR}/ilmbase/ -DILMBASE_PACKAGE_PREFIX=${LIBDIR}/ilmbase/ -DILMBASE_INCLUDE_DIR=${LIBDIR}/ilmbase/include/ - -DOPENEXR_HALF_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Half${LIBEXT} - -DOPENEXR_IMATH_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath-2_2${LIBEXT} - -DOPENEXR_ILMTHREAD_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread-2_2${LIBEXT} - -DOPENEXR_IEX_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex-2_2${LIBEXT} + -DOPENEXR_HALF_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Half${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_IMATH_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_ILMTHREAD_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_IEX_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex${ILMBASE_VERSION_POSTFIX}${LIBEXT} -DOPENEXR_INCLUDE_DIR=${LIBDIR}/openexr/include/ - -DOPENEXR_ILMIMF_LIBRARY=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf-2_2${LIBEXT} + -DOPENEXR_ILMIMF_LIBRARY=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT} -DSTOP_ON_WARNING=OFF ${WEBP_FLAGS} ${OIIO_SIMD_FLAGS} @@ -127,7 +127,7 @@ ExternalProject_Add(external_openimageio PREFIX ${BUILD_DIR}/openimageio PATCH_COMMAND ${PATCH_CMD} -p 0 -N -d ${BUILD_DIR}/openimageio/src/external_openimageio/src/include < ${PATCH_DIR}/openimageio_gdi.diff && - ${PATCH_CMD} -p 0 -N -d ${BUILD_DIR}/openimageio/src/external_openimageio/ < ${PATCH_DIR}/openimageio_staticexr.diff + ${PATCH_CMD} -p 1 -N -d ${BUILD_DIR}/openimageio/src/external_openimageio/ < ${PATCH_DIR}/openimageio_static_libs.diff CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openimageio ${DEFAULT_CMAKE_FLAGS} ${OPENIMAGEIO_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/openimageio ) diff --git a/build_files/build_environment/cmake/openjpeg.cmake b/build_files/build_environment/cmake/openjpeg.cmake index 5cc49b1e519f..ae320b788807 100644 --- a/build_files/build_environment/cmake/openjpeg.cmake +++ b/build_files/build_environment/cmake/openjpeg.cmake @@ -22,7 +22,7 @@ set(OPENJPEG_EXTRA_ARGS -DBUILD_SHARED_LIBS=OFF) if(WIN32) - set(OPENJPEG_EXTRA_ARGS -G "MSYS Makefiles") + set(OPENJPEG_EXTRA_ARGS -G "MSYS Makefiles" -DBUILD_PKGCONFIG_FILES=On) else() set(OPENJPEG_EXTRA_ARGS ${DEFAULT_CMAKE_FLAGS}) endif() @@ -58,7 +58,7 @@ if(MSVC) endif() endif() -set(OPENJPEG_LIBRARY libopenjpeg${LIBEXT}) +set(OPENJPEG_LIBRARY libopenjp2${LIBEXT}) if(MSVC) set_target_properties(external_openjpeg PROPERTIES FOLDER Mingw) endif() diff --git a/build_files/build_environment/cmake/openmp.cmake b/build_files/build_environment/cmake/openmp.cmake new file mode 100644 index 000000000000..ba8e6248126b --- /dev/null +++ b/build_files/build_environment/cmake/openmp.cmake @@ -0,0 +1,32 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + + +ExternalProject_Add(external_openmp + URL ${OPENMP_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${OPENMP_HASH} + PREFIX ${BUILD_DIR}/openmp + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openmp ${DEFAULT_CMAKE_FLAGS} + INSTALL_DIR ${LIBDIR}/clang +) + +add_dependencies( + external_openmp + external_clang +) diff --git a/build_files/build_environment/cmake/opensubdiv.cmake b/build_files/build_environment/cmake/opensubdiv.cmake index 930ef4e6ed3a..217274431d52 100644 --- a/build_files/build_environment/cmake/opensubdiv.cmake +++ b/build_files/build_environment/cmake/opensubdiv.cmake @@ -33,22 +33,28 @@ set(OPENSUBDIV_EXTRA_ARGS ) if(WIN32) - #no cuda support for vc15 yet - if(msvc15) - set(OPENSUBDIV_CUDA ON) - else() - set(OPENSUBDIV_CUDA ON) - endif() - set(OPENSUBDIV_EXTRA_ARGS ${OPENSUBDIV_EXTRA_ARGS} - -DNO_CUDA=${OPENSUBDIV_CUDA} + -DTBB_INCLUDE_DIR=${LIBDIR}/tbb/include + -DTBB_LIBRARIES=${LIBDIR}/tbb/lib/tbb_static.lib -DCLEW_INCLUDE_DIR=${LIBDIR}/clew/include/CL -DCLEW_LIBRARY=${LIBDIR}/clew/lib/clew${LIBEXT} -DCUEW_INCLUDE_DIR=${LIBDIR}/cuew/include -DCUEW_LIBRARY=${LIBDIR}/cuew/lib/cuew${LIBEXT} -DCMAKE_EXE_LINKER_FLAGS_RELEASE=libcmt.lib ) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + set(OPENSUBDIV_EXTRA_ARGS + ${OPENSUBDIV_EXTRA_ARGS} + -DNO_CUDA=OFF + ) + else() + set(OPENSUBDIV_EXTRA_ARGS + ${OPENSUBDIV_EXTRA_ARGS} + -DNO_CUDA=ON + ) + endif() + else() set(OPENSUBDIV_EXTRA_ARGS ${OPENSUBDIV_EXTRA_ARGS} @@ -69,10 +75,28 @@ ExternalProject_Add(external_opensubdiv INSTALL_DIR ${LIBDIR}/opensubdiv ) +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_opensubdiv after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opensubdiv/lib ${HARVEST_TARGET}/opensubdiv/lib + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/opensubdiv/include ${HARVEST_TARGET}/opensubdiv/include + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_opensubdiv after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opensubdiv/lib/osdCPU.lib ${HARVEST_TARGET}/opensubdiv/lib/osdCPU_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/opensubdiv/lib/osdGPU.lib ${HARVEST_TARGET}/opensubdiv/lib/osdGPU_d.lib + DEPENDEES install + ) + endif() +endif() + add_dependencies( external_opensubdiv external_glew external_glfw external_clew external_cuew + external_tbb ) diff --git a/build_files/build_environment/cmake/openvdb.cmake b/build_files/build_environment/cmake/openvdb.cmake index 26791012688a..a550ed5decbc 100644 --- a/build_files/build_environment/cmake/openvdb.cmake +++ b/build_files/build_environment/cmake/openvdb.cmake @@ -21,23 +21,6 @@ if(BUILD_MODE STREQUAL Debug) endif() set(OPENVDB_EXTRA_ARGS - -DILMBASE_HOME=${LIBDIR}/ilmbase/ - -DILMBASE_CUSTOM=ON - -DILMBASE_CUSTOM_LIBRARIES=Half;Imath-2_2;IlmThread-2_2;Iex-2_2 - -DILMBASE_INCLUDE_DIR=${LIBDIR}/ilmbase/include/ - -DILMBASE_HALF_LIBRARIES=${LIBDIR}/ilmbase/lib/Half${LIBEXT} - -DILMBASE_IMATH_LIBRARIES=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath-2_2${LIBEXT} - -DILMBASE_ILMTHREAD_LIBRARIES=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread-2_2${LIBEXT} - -DILMBASE_IEX_LIBRARIES=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex-2_2${LIBEXT} - -DOPENEXR_HOME=${LIBDIR}/openexr/ - -DOPENEXR_USE_STATIC_LIBS=ON - -DOPENEXR_CUSTOM=ON - -DOPENEXR_CUSTOM_LIBRARY=IlmImf-2_2 - -DOPENEXR_INCLUDE_DIR=${LIBDIR}/openexr/include/ - -DOPENEXR_ILMIMF_LIBRARIES=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf-2_2${LIBEXT} - -DTBB_ROOT_DIR=${LIBDIR}/tbb/ - -DTBB_INCLUDE_DIRS=${LIBDIR}/tbb/include - -DTBB_LIBRARY=${LIBDIR}/tbb/lib/tbb_static${LIBEXT} -DBoost_COMPILER:STRING=${BOOST_COMPILER_STRING} -DBoost_USE_MULTITHREADED=ON -DBoost_USE_STATIC_LIBS=ON @@ -49,22 +32,48 @@ set(OPENVDB_EXTRA_ARGS -DWITH_BLOSC=ON -DBLOSC_INCLUDE_DIR=${LIBDIR}/blosc/include/ -DBLOSC_LIBRARY=${LIBDIR}/blosc/lib/libblosc${BLOSC_POST}${LIBEXT} + -DBLOSC_blosc_LIBRARY=${LIBDIR}/blosc/lib/libblosc${BLOSC_POST}${LIBEXT} + -DOPENVDB_ENABLE_3_ABI_COMPATIBLE=OFF + -DOPENVDB_BUILD_UNITTESTS=Off + -DOPENVDB_BUILD_PYTHON_MODULE=Off + -DGLEW_LOCATION=${LIBDIR}/glew/ + -DBLOSC_LOCATION=${LIBDIR}/blosc/ + -DTBB_LOCATION=${LIBDIR}/tbb/ + -DTBB_ROOT=${LIBDIR}/tbb/ + -DOPENEXR_LOCATION=${LIBDIR}/openexr + -DILMBASE_LOCATION=${LIBDIR}/ilmbase + -DIlmbase_HALF_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Half${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DIlmbase_IEX_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DIlmbase_ILMTHREAD_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOpenexr_ILMIMF_LIBRARY=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT} + -DTBB_LIBRARYDIR=${LIBDIR}/tbb/lib + -DTbb_TBB_LIBRARY=${LIBDIR}/tbb/lib/${LIBPREFIX}tbb_static${LIBEXT} + -DTBB_LIBRARY_DIR=${LIBDIR}/tbb/lib + -DTBB_LIBRARY_PATH=${LIBDIR}/tbb/lib ) -set(OPENVDB_EXTRA_ARGS ${OPENVDB_EXTRA_ARGS}) - -# CMake script for OpenVDB based on https://raw.githubusercontent.com/diekev/openvdb-cmake/master/CMakeLists.txt -# can't be in external_openvdb because of how the includes are setup. +if(WIN32) + #Namespaces seem to be buggy and cause linker erorrs due to things not + #being in the correct namespace + #needs to link pthreads due to it being a blosc dependency + set(OPENVDB_EXTRA_ARGS ${OPENVDB_EXTRA_ARGS} + -DOPENEXR_NAMESPACE_VERSIONING=OFF + -DEXTRA_LIBS:FILEPATH=${LIBDIR}/pthreads/lib/pthreadVC2.lib + ) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "4") + set(OPENVDB_EXTRA_ARGS ${OPENVDB_EXTRA_ARGS} + -DCMAKE_SHARED_LINKER_FLAGS="/safeseh:no" + -DCMAKE_EXE_LINKER_FLAGS="/safeseh:no" + ) + endif() +endif() ExternalProject_Add(openvdb URL ${OPENVDB_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH MD5=${OPENVDB_HASH} PREFIX ${BUILD_DIR}/openvdb - PATCH_COMMAND COMMAND - ${CMAKE_COMMAND} -E copy ${PATCH_DIR}/cmakelists_openvdb.txt ${BUILD_DIR}/openvdb/src/openvdb/CMakeLists.txt && - ${CMAKE_COMMAND} -E copy_directory ${PATCH_DIR}/cmake/ ${BUILD_DIR}/openvdb/src/openvdb/cmake/ && - ${PATCH_CMD} --verbose -p 0 -N -d ${BUILD_DIR}/openvdb/src/openvdb < ${PATCH_DIR}/openvdb_vc2013.diff + PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/openvdb/src/openvdb < ${PATCH_DIR}/openvdb.diff CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/openvdb ${DEFAULT_CMAKE_FLAGS} ${OPENVDB_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/openvdb ) @@ -78,3 +87,19 @@ add_dependencies( external_zlib external_blosc ) + +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(openvdb after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/openvdb/include ${HARVEST_TARGET}/openvdb/include + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openvdb/lib/libopenvdb.lib ${HARVEST_TARGET}/openvdb/lib/openvdb.lib + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(openvdb after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/openvdb/lib/libopenvdb.lib ${HARVEST_TARGET}/openvdb/lib/openvdb_d.lib + DEPENDEES install + ) + endif() +endif() diff --git a/build_files/build_environment/cmake/options.cmake b/build_files/build_environment/cmake/options.cmake index 08d43d6a0a2c..7bf971208ae5 100644 --- a/build_files/build_environment/cmake/options.cmake +++ b/build_files/build_environment/cmake/options.cmake @@ -59,7 +59,7 @@ if(WIN32) if(MSVC_VERSION GREATER 1909) set(COMMON_MSVC_FLAGS "/Wv:18") #some deps with warnings as error aren't quite ready for dealing with the new 2017 warnings. endif() - + set(COMMON_MSVC_FLAGS "${COMMON_MSVC_FLAGS} /bigobj") if(WITH_OPTIMIZED_DEBUG) set(BLENDER_CMAKE_C_FLAGS_DEBUG "/MTd ${COMMON_MSVC_FLAGS} /O2 /Ob2 /DNDEBUG /DPSAPI_VERSION=1 /DOIIO_STATIC_BUILD /DTINYFORMAT_ALLOW_WCHAR_STRINGS") else() @@ -126,7 +126,7 @@ else() ) set(OSX_ARCHITECTURES x86_64) set(OSX_DEPLOYMENT_TARGET 10.9) - set(OSX_SDK_VERSION 10.12) + set(OSX_SDK_VERSION 10.13) set(OSX_SYSROOT ${XCODE_DEV_PATH}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${OSX_SDK_VERSION}.sdk) set(PLATFORM_CFLAGS "-isysroot ${OSX_SYSROOT} -mmacosx-version-min=${OSX_DEPLOYMENT_TARGET}") @@ -147,13 +147,13 @@ else() endif() if(WITH_OPTIMIZED_DEBUG) - set(BLENDER_CMAKE_C_FLAGS_DEBUG "-O2 -DNDEBUG") + set(BLENDER_CMAKE_C_FLAGS_DEBUG "-O2 -DNDEBUG ${PLATFORM_CFLAGS}") else() - set(BLENDER_CMAKE_C_FLAGS_DEBUG "-g") + set(BLENDER_CMAKE_C_FLAGS_DEBUG "-g ${PLATFORM_CFLAGS}") endif() - set(BLENDER_CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG") - set(BLENDER_CMAKE_C_FLAGS_RELEASE "-O2 -DNDEBUG") - set(BLENDER_CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g -DNDEBUG") + set(BLENDER_CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG ${PLATFORM_CFLAGS}") + set(BLENDER_CMAKE_C_FLAGS_RELEASE "-O2 -DNDEBUG ${PLATFORM_CFLAGS}") + set(BLENDER_CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g -DNDEBUG ${PLATFORM_CFLAGS}") if(WITH_OPTIMIZED_DEBUG) set(BLENDER_CMAKE_CXX_FLAGS_DEBUG "-O2 -DNDEBUG ${PLATFORM_CXXFLAGS}") @@ -202,7 +202,11 @@ endif() if(WIN32) - set(ZLIB_LIBRARY zlibstatic${LIBEXT}) + if(BUILD_MODE STREQUAL Debug) + set(ZLIB_LIBRARY zlibstaticd${LIBEXT}) + else() + set(ZLIB_LIBRARY zlibstatic${LIBEXT}) + endif() else() set(ZLIB_LIBRARY libz${LIBEXT}) endif() diff --git a/build_files/build_environment/cmake/osl.cmake b/build_files/build_environment/cmake/osl.cmake index ad4d0ee6038e..eaf6a62d18a8 100644 --- a/build_files/build_environment/cmake/osl.cmake +++ b/build_files/build_environment/cmake/osl.cmake @@ -19,20 +19,22 @@ if(WIN32) set(OSL_CMAKE_CXX_STANDARD_LIBRARIES "kernel32${LIBEXT} user32${LIBEXT} gdi32${LIBEXT} winspool${LIBEXT} shell32${LIBEXT} ole32${LIBEXT} oleaut32${LIBEXT} uuid${LIBEXT} comdlg32${LIBEXT} advapi32${LIBEXT} psapi${LIBEXT}") set(OSL_FLEX_BISON -DFLEX_EXECUTABLE=${LIBDIR}/flexbison/win_flex.exe -DFLEX_EXTRA_OPTIONS="--wincompat" -DBISON_EXECUTABLE=${LIBDIR}/flexbison/win_bison.exe) - set(OSL_OPENIMAGEIO_LIBRARY "${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO${LIBEXT};${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO_Util${LIBEXT};${LIBDIR}/png/lib/libpng16${LIBEXT};${LIBDIR}/jpg/lib/${LIBPREFIX}jpeg${LIBEXT};${LIBDIR}/tiff/lib/${LIBPREFIX}tiff${LIBEXT};${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf-2_2${LIBEXT}") + set(OSL_OPENIMAGEIO_LIBRARY "${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO${LIBEXT};${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO_Util${LIBEXT};${LIBDIR}/png/lib/libpng16${LIBEXT};${LIBDIR}/jpg/lib/${LIBPREFIX}jpeg${LIBEXT};${LIBDIR}/tiff/lib/${LIBPREFIX}tiff${LIBEXT};${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT}") if("${CMAKE_SIZEOF_VOID_P}" EQUAL "4") set(OSL_SIMD_FLAGS -DOIIO_NOSIMD=1 -DOIIO_SIMD=0) else() set(OSL_SIMD_FLAGS -DOIIO_NOSIMD=1 -DOIIO_SIMD=sse2) endif() + SET(OSL_PLATFORM_FLAGS -DLINKSTATIC=ON) else() set(OSL_CMAKE_CXX_STANDARD_LIBRARIES) set(OSL_FLEX_BISON) - set(OSL_OPENIMAGEIO_LIBRARY "${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO${LIBEXT};${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO_Util${LIBEXT};${LIBDIR}/png/lib/${LIBPREFIX}png16${LIBEXT};${LIBDIR}/jpg/lib/${LIBPREFIX}jpeg${LIBEXT};${LIBDIR}/tiff/lib/${LIBPREFIX}tiff${LIBEXT};${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf-2_2${LIBEXT}") + set(OSL_OPENIMAGEIO_LIBRARY "${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO${LIBEXT};${LIBDIR}/openimageio/lib/${LIBPREFIX}OpenImageIO_Util${LIBEXT};${LIBDIR}/png/lib/${LIBPREFIX}png16${LIBEXT};${LIBDIR}/jpg/lib/${LIBPREFIX}jpeg${LIBEXT};${LIBDIR}/tiff/lib/${LIBPREFIX}tiff${LIBEXT};${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT}") + SET(OSL_PLATFORM_FLAGS) endif() -set(OSL_ILMBASE_CUSTOM_LIBRARIES "${LIBDIR}/ilmbase/lib/Imath-2_2.lib^^${LIBDIR}/ilmbase/lib/Half.lib^^${LIBDIR}/ilmbase/lib/IlmThread-2_2.lib^^${LIBDIR}/ilmbase/lib/Iex-2_2.lib") -set(OSL_LLVM_LIBRARY "${LIBDIR}/llvm/lib/LLVMAnalysis${LIBEXT};${LIBDIR}/llvm/lib/LLVMAsmParser${LIBEXT};${LIBDIR}/llvm/lib/LLVMAsmPrinter${LIBEXT};${LIBDIR}/llvm/lib/LLVMBitReader${LIBEXT};${LIBDIR}/llvm/lib/LLVMBitWriter${LIBEXT};${LIBDIR}/llvm/lib/LLVMCodeGen${LIBEXT};${LIBDIR}/llvm/lib/LLVMCore${LIBEXT};${LIBDIR}/llvm/lib/LLVMDebugInfo${LIBEXT};${LIBDIR}/llvm/lib/LLVMExecutionEngine${LIBEXT};${LIBDIR}/llvm/lib/LLVMInstCombine${LIBEXT};${LIBDIR}/llvm/lib/LLVMInstrumentation${LIBEXT};${LIBDIR}/llvm/lib/LLVMInterpreter${LIBEXT};${LIBDIR}/llvm/lib/LLVMJIT${LIBEXT};${LIBDIR}/llvm/lib/LLVMLinker${LIBEXT};${LIBDIR}/llvm/lib/LLVMMC${LIBEXT};${LIBDIR}/llvm/lib/LLVMMCDisassembler${LIBEXT};${LIBDIR}/llvm/lib/LLVMMCJIT${LIBEXT};${LIBDIR}/llvm/lib/LLVMMCParser${LIBEXT};${LIBDIR}/llvm/lib/LLVMObject${LIBEXT};${LIBDIR}/llvm/lib/LLVMRuntimeDyld${LIBEXT};${LIBDIR}/llvm/lib/LLVMScalarOpts${LIBEXT};${LIBDIR}/llvm/lib/LLVMSelectionDAG${LIBEXT};${LIBDIR}/llvm/lib/LLVMSupport${LIBEXT};${LIBDIR}/llvm/lib/LLVMTableGen${LIBEXT};${LIBDIR}/llvm/lib/LLVMTarget${LIBEXT};${LIBDIR}/llvm/lib/LLVMTransformUtils${LIBEXT};${LIBDIR}/llvm/lib/LLVMVectorize${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86AsmParser${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86AsmPrinter${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86CodeGen${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86Desc${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86Disassembler${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86Info${LIBEXT};${LIBDIR}/llvm/lib/LLVMX86Utils${LIBEXT};${LIBDIR}/llvm/lib/LLVMipa${LIBEXT};${LIBDIR}/llvm/lib/LLVMipo${LIBEXT}") +set(OSL_ILMBASE_CUSTOM_LIBRARIES "${LIBDIR}/ilmbase/lib/Imath${ILMBASE_VERSION_POSTFIX}.lib^^${LIBDIR}/ilmbase/lib/Half{ILMBASE_VERSION_POSTFIX}.lib^^${LIBDIR}/ilmbase/lib/IlmThread${ILMBASE_VERSION_POSTFIX}.lib^^${LIBDIR}/ilmbase/lib/Iex${ILMBASE_VERSION_POSTFIX}.lib") +set(OSL_LLVM_LIBRARY "${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMAnalysis${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMAsmParser${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMAsmPrinter${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMBitReader${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMBitWriter${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMCodeGen${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMCore${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMDebugInfo${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMExecutionEngine${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMInstCombine${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMInstrumentation${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMInterpreter${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMJIT${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMLinker${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMMC${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMMCDisassembler${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMMCJIT${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMMCParser${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMObject${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMRuntimeDyld${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMScalarOpts${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMSelectionDAG${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMSupport${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMTableGen${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMTarget${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMTransformUtils${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMVectorize${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86AsmParser${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86AsmPrinter${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86CodeGen${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86Desc${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86Disassembler${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86Info${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMX86Utils${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMipa${LIBEXT};${LIBDIR}/llvm/lib/${LIBPREFIX}LLVMipo${LIBEXT}") set(OSL_EXTRA_ARGS -DBoost_COMPILER:STRING=${BOOST_COMPILER_STRING} @@ -50,11 +52,12 @@ set(OSL_EXTRA_ARGS -DOPENEXR_HOME=${LIBDIR}/openexr/ -DILMBASE_HOME=${LIBDIR}/ilmbase/ -DILMBASE_INCLUDE_DIR=${LIBDIR}/ilmbase/include/ - -DOPENEXR_IMATH_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath-2_2${LIBEXT} - -DOPENEXR_ILMTHREAD_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread-2_2${LIBEXT} - -DOPENEXR_IEX_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex-2_2${LIBEXT} + -DOPENEXR_HALF_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Half${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_IMATH_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Imath${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_ILMTHREAD_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}IlmThread${ILMBASE_VERSION_POSTFIX}${LIBEXT} + -DOPENEXR_IEX_LIBRARY=${LIBDIR}/ilmbase/lib/${LIBPREFIX}Iex${ILMBASE_VERSION_POSTFIX}${LIBEXT} -DOPENEXR_INCLUDE_DIR=${LIBDIR}/openexr/include/ - -DOPENEXR_ILMIMF_LIBRARY=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf-2_2${LIBEXT} + -DOPENEXR_ILMIMF_LIBRARY=${LIBDIR}/openexr/lib/${LIBPREFIX}IlmImf${OPENEXR_VERSION_POSTFIX}${LIBEXT} -DOSL_BUILD_TESTS=OFF -DZLIB_LIBRARY=${LIBDIR}/zlib/lib/${ZLIB_LIBRARY} -DZLIB_INCLUDE_DIR=${LIBDIR}/zlib/include/ @@ -64,23 +67,29 @@ set(OSL_EXTRA_ARGS ${OSL_FLEX_BISON} -DCMAKE_CXX_STANDARD_LIBRARIES=${OSL_CMAKE_CXX_STANDARD_LIBRARIES} -DBUILDSTATIC=ON - -DLINKSTATIC=ON + ${OSL_PLATFORM_FLAGS} -DOSL_BUILD_PLUGINS=Off -DSTOP_ON_WARNING=OFF - -DOSL_BUILD_CPP11=ON -DUSE_LLVM_BITCODE=OFF + -DUSE_PARTIO=OFF ${OSL_SIMD_FLAGS} + -DPARTIO_LIBRARIES= ) +if(WIN32) +set(OSL_EXTRA_ARGS + ${OSL_EXTRA_FLAGS} + -DPUGIXML_HOME=${LIBDIR}/pugixml +) +endif() + ExternalProject_Add(external_osl URL ${OSL_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} LIST_SEPARATOR ^^ URL_HASH MD5=${OSL_HASH} PREFIX ${BUILD_DIR}/osl - PATCH_COMMAND - ${PATCH_CMD} -p 3 -d ${BUILD_DIR}/osl/src/external_osl < ${PATCH_DIR}/osl.diff && - ${PATCH_CMD} -p 0 -d ${BUILD_DIR}/osl/src/external_osl < ${PATCH_DIR}/osl_simd_oiio.diff + PATCH_COMMAND ${PATCH_CMD} -p 1 -d ${BUILD_DIR}/osl/src/external_osl < ${PATCH_DIR}/osl.diff CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/osl -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} ${DEFAULT_CMAKE_FLAGS} ${OSL_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/osl ) @@ -95,4 +104,22 @@ add_dependencies( external_zlib external_flexbison external_openimageio + external_pugixml ) + +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_osl after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/osl/ ${HARVEST_TARGET}/osl + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_osl after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslcomp.lib ${HARVEST_TARGET}/osl/lib/oslcomp_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslexec.lib ${HARVEST_TARGET}/osl/lib/oslexec_d.lib + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/osl/lib/oslquery.lib ${HARVEST_TARGET}/osl/lib/oslquery_d.lib + DEPENDEES install + ) + endif() +endif() diff --git a/build_files/build_environment/cmake/pthreads.cmake b/build_files/build_environment/cmake/pthreads.cmake index c93f0866aa9f..66246c5ee903 100644 --- a/build_files/build_environment/cmake/pthreads.cmake +++ b/build_files/build_environment/cmake/pthreads.cmake @@ -43,4 +43,13 @@ if(WIN32) ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/pthreads/src/external_pthreads/semaphore.h ${LIBDIR}/pthreads/inc/semaphore.h INSTALL_DIR ${LIBDIR}/pthreads ) + + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_pthreads after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/pthreads/inc/ ${HARVEST_TARGET}/pthreads/include/ + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/pthreads/lib/ ${HARVEST_TARGET}/pthreads/lib + DEPENDEES install + ) + endif() + endif() diff --git a/build_files/build_environment/cmake/pugixml.cmake b/build_files/build_environment/cmake/pugixml.cmake new file mode 100644 index 000000000000..fe5a77efa33d --- /dev/null +++ b/build_files/build_environment/cmake/pugixml.cmake @@ -0,0 +1,43 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(PUGIXML_EXTRA_ARGS +) + +ExternalProject_Add(external_pugixml + URL ${PUGIXML_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${PUGIXML_HASH} + PREFIX ${BUILD_DIR}/pugixml + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/pugixml ${DEFAULT_CMAKE_FLAGS} ${PUGIXML_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/pugixml +) +if(WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_pugixml after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/pugixml/lib/pugixml.lib ${HARVEST_TARGET}/osl/lib/pugixml.lib + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_pugixml after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/pugixml/lib/pugixml.lib ${HARVEST_TARGET}/osl/lib/pugixml_d.lib + DEPENDEES install + ) + endif() +endif() \ No newline at end of file diff --git a/build_files/build_environment/cmake/python.cmake b/build_files/build_environment/cmake/python.cmake index 693ab1896bab..22b4052189ee 100644 --- a/build_files/build_environment/cmake/python.cmake +++ b/build_files/build_environment/cmake/python.cmake @@ -22,6 +22,12 @@ if(BUILD_MODE STREQUAL Debug) endif() if(WIN32) + if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + set(SSL_POSTFIX -x64) + else() + set(SSL_POSTFIX) + endif() + set(PYTHON_BINARY ${BUILD_DIR}/python/src/external_python/run/python${PYTHON_POSTFIX}.exe) macro(cmake_to_dos_path MsysPath ResultingPath) @@ -46,13 +52,12 @@ if(WIN32) PREFIX ${BUILD_DIR}/python PATCH_COMMAND echo mklink /D "${PYTHON_EXTERNALS_FOLDER_DOS}" "${DOWNLOADS_EXTERNALS_FOLDER_DOS}" && - mklink /D "${PYTHON_EXTERNALS_FOLDER_DOS}" "${DOWNLOADS_EXTERNALS_FOLDER_DOS}" && - ${PATCH_CMD} --verbose -p 0 -d ${BUILD_DIR}/python/src/external_python < ${PATCH_DIR}/python.diff && - ${PATCH_CMD} --verbose -p 0 -d ${BUILD_DIR}/python/src/external_python/pc < ${PATCH_DIR}/pyshell.diff + mklink /D "${PYTHON_EXTERNALS_FOLDER_DOS}" "${DOWNLOADS_EXTERNALS_FOLDER_DOS}" CONFIGURE_COMMAND "" - BUILD_COMMAND cd ${BUILD_DIR}/python/src/external_python/pcbuild/ && set IncludeTkinter=false && call build.bat -e -p ${PYTHON_ARCH} -c ${BUILD_MODE} -k ${PYTHON_COMPILER_STRING} + BUILD_COMMAND cd ${BUILD_DIR}/python/src/external_python/pcbuild/ && set IncludeTkinter=false && call build.bat -e -p ${PYTHON_ARCH} -c ${BUILD_MODE} INSTALL_COMMAND COMMAND ${CMAKE_COMMAND} -E copy ${PYTHON_OUTPUTDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.dll ${LIBDIR}/python/lib/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.dll && + ${CMAKE_COMMAND} -E copy ${PYTHON_OUTPUTDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.pdb ${LIBDIR}/python/lib/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.pdb && ${CMAKE_COMMAND} -E copy ${PYTHON_OUTPUTDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.lib ${LIBDIR}/python/lib/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.lib && ${CMAKE_COMMAND} -E copy ${PYTHON_OUTPUTDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.exp ${LIBDIR}/python/lib/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.exp && ${CMAKE_COMMAND} -E copy_directory ${BUILD_DIR}/python/src/external_python/include ${LIBDIR}/python/include/Python${PYTHON_SHORT_VERSION} && @@ -62,15 +67,39 @@ if(WIN32) message("POutput = ${PYTHON_OUTPUTDIR}") else() if(APPLE) - # we need to manually add homebrew headers to get ssl module building - set(PYTHON_CFLAGS "-I/usr/local/opt/openssl/include -I${OSX_SYSROOT}/usr/include ${PLATFORM_CFLAGS}") - set(PYTHON_LDFLAGS "-L/usr/local/opt/openssl/lib ${PLATFORM_LDFLAGS}") - set(PYTHON_CONFIGURE_ENV ${CONFIGURE_ENV} && export CFLAGS=${PYTHON_CFLAGS} && export LDFLAGS=${PYTHON_LDFLAGS}) + # we need to add homebrew pkgconfig directories to get ssl, xz + + set(BREW_PKG_CONFIG "/usr/local/opt/openssl/lib/pkgconfig:/usr/local/opt/xz/lib/pkgconfig") + # disable functions that can be in 10.13 sdk but aren't available on 10.9 target + set(PYTHON_FUNC_CONFIGS + export ac_cv_func_futimens=no && + export ac_cv_func_utimensat=no && + export ac_cv_func_basename_r=no && + export ac_cv_func_clock_getres=no && + export ac_cv_func_clock_gettime=no && + export ac_cv_func_clock_settime=no && + export ac_cv_func_dirname_r=no && + export ac_cv_func_getentropy=no && + export ac_cv_func_mkostemp=no && + export ac_cv_func_mkostemps=no && + export ac_cv_func_timingsafe_bcmp=no) + + set(PYTHON_CONFIGURE_ENV ${CONFIGURE_ENV} && export PKG_CONFIG_PATH=${BREW_PKG_CONFIG} && ${PYTHON_FUNC_CONFIGS}) set(PYTHON_BINARY ${BUILD_DIR}/python/src/external_python/python.exe) - set(PYTHON_PATCH ${PATCH_CMD} --verbose -p 0 -d ${BUILD_DIR}/python/src/external_python < ${PATCH_DIR}/python_apple.diff) + set(PYTHON_PATCH echo .) + set(PYTHON_CONFIGURE_EXTRA_ENV echo .) + set(PYTHON_CONFIGURE_EXTRA_ARGS) else() + set(PYTHON_CONFIGURE_EXTRA_ARGS "--with-openssl=${LIBDIR}/ssl") set(PYTHON_CONFIGURE_ENV ${CONFIGURE_ENV}) + set(PYTHON_CFLAGS "-I${LIBDIR}/sqlite/include -I${LIBDIR}/bzip2/include -I${LIBDIR}/lzma/include -I${LIBDIR}/zlib/include") + set(PYTHON_LDFLAGS "-L${LIBDIR}/sqlite/lib -L${LIBDIR}/bzip2/lib -L${LIBDIR}/lzma/lib -L${LIBDIR}/zlib/lib") + set(PYTHON_CONFIGURE_EXTRA_ENV + export CFLAGS=${PYTHON_CFLAGS} && + export CPPFLAGS=${PYTHON_CFLAGS} && + export LDFLAGS=${PYTHON_LDFLAGS}) set(PYTHON_BINARY ${BUILD_DIR}/python/src/external_python/python) + set(PYTHON_PATCH ${PATCH_CMD} --verbose -p1 -d ${BUILD_DIR}/python/src/external_python < ${PATCH_DIR}/python_linux.diff) endif() ExternalProject_Add(external_python @@ -79,7 +108,7 @@ else() URL_HASH MD5=${PYTHON_HASH} PREFIX ${BUILD_DIR}/python PATCH_COMMAND ${PYTHON_PATCH} - CONFIGURE_COMMAND ${PYTHON_CONFIGURE_ENV} && cd ${BUILD_DIR}/python/src/external_python/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/python + CONFIGURE_COMMAND ${PYTHON_CONFIGURE_ENV} && ${PYTHON_CONFIGURE_EXTRA_ENV} && cd ${BUILD_DIR}/python/src/external_python/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/python ${PYTHON_CONFIGURE_EXTRA_ARGS} BUILD_COMMAND ${PYTHON_CONFIGURE_ENV} && cd ${BUILD_DIR}/python/src/external_python/ && make -j${MAKE_THREADS} INSTALL_COMMAND ${PYTHON_CONFIGURE_ENV} && cd ${BUILD_DIR}/python/src/external_python/ && make install INSTALL_DIR ${LIBDIR}/python) @@ -92,39 +121,44 @@ if(MSVC) OUTPUT ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.tar.gz OUTPUT ${BUILD_DIR}/python/src/external_python/redist/bin/python${PYTHON_POSTFIX}.exe COMMAND ${CMAKE_COMMAND} -E copy_directory ${BUILD_DIR}/python/src/external_python/lib ${BUILD_DIR}/python/src/external_python/redist/lib - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/python${PYTHON_POSTFIX}.exe" ${BUILD_DIR}/python/src/external_python/redist/bin/python${PYTHON_POSTFIX}.exe + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_asyncio${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_asyncio${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_bz2${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_bz2${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_hashlib${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_hashlib${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_lzma${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_lzma${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_sqlite3${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_sqlite3${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_ssl${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_ssl${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/pyexpat${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/pyexpat${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/select${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/select${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/unicodedata${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/unicodedata${PYTHON_POSTFIX}.pyd - COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/winsound${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/winsound${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_contextvars${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_contextvars${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_ctypes${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_ctypes${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_ctypes_test${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_ctypes_test${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_decimal${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_decimal${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_distutils_findvs${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_distutils_findvs${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_elementtree${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_elementtree${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_hashlib${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_hashlib${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_lzma${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_lzma${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_msi${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_msi${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_multiprocessing${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_multiprocessing${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_overlapped${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_overlapped${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_queue${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_queue${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_socket${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_socket${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_sqlite3${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_sqlite3${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_ssl${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_ssl${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_testbuffer${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_testbuffer${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_testcapi${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_testcapi${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_testimportmultiple${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_testimportmultiple${PYTHON_POSTFIX}.pyd COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/_testmultiphase${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/_testmultiphase${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/pyexpat${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/pyexpat${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/python${PYTHON_POSTFIX}.exe" ${BUILD_DIR}/python/src/external_python/redist/bin/python${PYTHON_POSTFIX}.exe + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/select${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/select${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/unicodedata${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/unicodedata${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/winsound${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/winsound${PYTHON_POSTFIX}.pyd + #xxlimited is an example extention module, we don't need to ship it and debug doesn't build it + #leaving it commented out, so I won't get confused again with the next update. + #COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/xxlimited${PYTHON_POSTFIX}.pyd" ${BUILD_DIR}/python/src/external_python/redist/lib/xxlimited${PYTHON_POSTFIX}.pyd + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/libssl-1_1${SSL_POSTFIX}.dll" ${BUILD_DIR}/python/src/external_python/redist/lib/libssl-1_1${SSL_POSTFIX}.dll + COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/libcrypto-1_1${SSL_POSTFIX}.dll" ${BUILD_DIR}/python/src/external_python/redist/lib/libcrypto-1_1${SSL_POSTFIX}.dll COMMAND ${CMAKE_COMMAND} -E chdir "${BUILD_DIR}/python/src/external_python/redist" ${CMAKE_COMMAND} -E tar "cfvz" "${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.tar.gz" "." + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/python/ ${HARVEST_TARGET}/python/ + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.tar.gz ${HARVEST_TARGET}/Release/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.tar.gz ) add_custom_target(Package_Python ALL DEPENDS external_python ${LIBDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.tar.gz ${BUILD_DIR}/python/src/external_python/redist/bin/python${PYTHON_POSTFIX}.exe) - if(MSVC12) - set(PYTHON_DISTUTIL_PATCH ${PATCH_CMD} --verbose -p 0 -d ${BUILD_DIR}/python/src/external_python/run/lib/distutils < ${PATCH_DIR}/python_runtime_vc2013.diff) - else() - set(PYTHON_DISTUTIL_PATCH echo "No patch needed") - endif() - add_custom_command(OUTPUT ${BUILD_DIR}/python/src/external_python/run/python${PYTHON_POSTFIX}.exe COMMAND ${CMAKE_COMMAND} -E copy_directory ${BUILD_DIR}/python/src/external_python/redist ${BUILD_DIR}/python/src/external_python/run COMMAND ${CMAKE_COMMAND} -E copy_directory ${BUILD_DIR}/python/src/external_python/include ${BUILD_DIR}/python/src/external_python/run/include @@ -134,7 +168,18 @@ if(MSVC) COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.lib" ${BUILD_DIR}/python/src/external_python/run/libs/python${PYTHON_SHORT_VERSION_NO_DOTS}${PYTHON_POSTFIX}.lib #other things like numpy still want it though. COMMAND ${CMAKE_COMMAND} -E copy "${PYTHON_OUTPUTDIR}/python${PYTHON_POSTFIX}.exe" ${BUILD_DIR}/python/src/external_python/run/python${PYTHON_POSTFIX}.exe COMMAND ${BUILD_DIR}/python/src/external_python/run/python${PYTHON_POSTFIX}.exe -m ensurepip --upgrade - COMMAND ${PYTHON_DISTUTIL_PATCH} ) add_custom_target(Make_Python_Environment ALL DEPENDS ${BUILD_DIR}/python/src/external_python/run/python${PYTHON_POSTFIX}.exe Package_Python) endif() + +if(UNIX AND NOT APPLE) + add_dependencies( + external_python + external_bzip2 + external_ffi + external_lzma + external_ssl + external_sqlite + external_zlib + ) +endif() diff --git a/build_files/build_environment/cmake/python.map b/build_files/build_environment/cmake/python.map new file mode 100644 index 000000000000..1c11c33011d8 --- /dev/null +++ b/build_files/build_environment/cmake/python.map @@ -0,0 +1,9 @@ +{ +global: + Py*; + _Py*; + _py*; +local: + *; +}; + diff --git a/build_files/build_environment/cmake/schroedinger.cmake b/build_files/build_environment/cmake/schroedinger.cmake deleted file mode 100644 index 80bf84b06d7b..000000000000 --- a/build_files/build_environment/cmake/schroedinger.cmake +++ /dev/null @@ -1,48 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# ***** END GPL LICENSE BLOCK ***** - -if(WIN32) - set(SCHROEDINGER_EXTRA_FLAGS "CFLAGS=-g -I./ -I${LIBDIR}/orc/include/orc-0.4" "LDFLAGS=-Wl,--as-needed -static-libgcc -L${LIBDIR}/orc/lib" ORC_CFLAGS=-I${LIBDIR}/orc/include/orc-0.4 ORC_LDFLAGS=-L${LIBDIR}/orc/lib ORC_LIBS=${LIBDIR}/orc/lib/liborc-0.4.a ORCC=${LIBDIR}/orc/bin/orcc.exe) -else() - set(SCHROEDINGER_CFLAGS "${PLATFORM_CFLAGS} -I./ -I${LIBDIR}/orc/include/orc-0.4") - set(SCHROEDINGER_LDFLAGS "${PLATFORM_LDFLAGS} -L${LIBDIR}/orc/lib") - set(SCHROEDINGER_EXTRA_FLAGS CFLAGS=${SCHROEDINGER_CFLAGS} LDFLAGS=${SCHROEDINGER_LDFLAGS} ORC_CFLAGS=-I${LIBDIR}/orc/include/orc-0.4 ORC_LDFLAGS=-L${LIBDIR}/orc/lib ORCC=${LIBDIR}/orc/bin/orcc) # ORC_LIBS=${LIBDIR}/orc/lib/liborc-0.4.a -endif() - -ExternalProject_Add(external_schroedinger - URL ${SCHROEDINGER_URI} - DOWNLOAD_DIR ${DOWNLOAD_DIR} - URL_HASH SHA256=${SCHROEDINGER_HASH} - PREFIX ${BUILD_DIR}/schroedinger - PATCH_COMMAND ${PATCH_CMD} --verbose -p 0 -N -d ${BUILD_DIR}/schroedinger/src/external_schroedinger < ${PATCH_DIR}/schroedinger.diff - CONFIGURE_COMMAND ${CONFIGURE_ENV} && - cd ${BUILD_DIR}/schroedinger/src/external_schroedinger/ && - ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/schroedinger --disable-shared --enable-static ${SCHROEDINGER_EXTRA_FLAGS} - BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/schroedinger/src/external_schroedinger/ && make -j${MAKE_THREADS} - INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/schroedinger/src/external_schroedinger/ && make install - INSTALL_DIR ${LIBDIR}/schroedinger -) - -add_dependencies( - external_schroedinger - external_orc -) - -if(MSVC) - set_target_properties(external_schroedinger PROPERTIES FOLDER Mingw) -endif() diff --git a/build_files/build_environment/cmake/sdl.cmake b/build_files/build_environment/cmake/sdl.cmake index 0fbfa078eb1b..8383c5a5a79f 100644 --- a/build_files/build_environment/cmake/sdl.cmake +++ b/build_files/build_environment/cmake/sdl.cmake @@ -37,3 +37,12 @@ ExternalProject_Add(external_sdl CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/sdl ${DEFAULT_CMAKE_FLAGS} ${SDL_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/sdl ) + +if(BUILD_MODE STREQUAL Release AND WIN32) + ExternalProject_Add_Step(external_sdl after_install + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/include/sdl2 ${HARVEST_TARGET}/sdl/include + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/lib ${HARVEST_TARGET}/sdl/lib + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/sdl/bin ${HARVEST_TARGET}/sdl/lib + DEPENDEES install + ) +endif() diff --git a/build_files/build_environment/cmake/setup_mingw32.cmake b/build_files/build_environment/cmake/setup_mingw32.cmake index f0d99356da04..afb44e8e88d4 100644 --- a/build_files/build_environment/cmake/setup_mingw32.cmake +++ b/build_files/build_environment/cmake/setup_mingw32.cmake @@ -35,9 +35,9 @@ message("mingw_LIBDIR = ${mingw_LIBDIR}") message("Checking for mingw32") # download mingw32 -if(NOT EXISTS "${DOWNLOAD_DIR}/i686-w64-mingw32-gcc-4.8.0-win32_rubenvb.7z") +if(NOT EXISTS "${DOWNLOAD_DIR}/i686-4.9.4-release-win32-sjlj-rt_v5-rev0.7z") message("Downloading mingw32") - file(DOWNLOAD "https://nchc.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win32/Personal%20Builds/rubenvb/gcc-4.8-release/i686-w64-mingw32-gcc-4.8.0-win32_rubenvb.7z" "${DOWNLOAD_DIR}/i686-w64-mingw32-gcc-4.8.0-win32_rubenvb.7z") + file(DOWNLOAD "https://astuteinternet.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/4.9.4/threads-win32/sjlj/i686-4.9.4-release-win32-sjlj-rt_v5-rev0.7z" "${DOWNLOAD_DIR}/i686-4.9.4-release-win32-sjlj-rt_v5-rev0.7z") endif() # make mingw root directory @@ -49,10 +49,10 @@ if(NOT EXISTS "${DOWNLOAD_DIR}/mingw") endif() # extract mingw32 -if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/mingw32env.cmd") AND (EXISTS "${DOWNLOAD_DIR}/i686-w64-mingw32-gcc-4.8.0-win32_rubenvb.7z")) +if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/ming32sh.cmd") AND (EXISTS "${DOWNLOAD_DIR}/i686-4.9.4-release-win32-sjlj-rt_v5-rev0.7z")) message("Extracting mingw32") execute_process( - COMMAND ${CMAKE_COMMAND} -E tar jxf ${DOWNLOAD_DIR}/i686-w64-mingw32-gcc-4.8.0-win32_rubenvb.7z + COMMAND ${CMAKE_COMMAND} -E tar jxf ${DOWNLOAD_DIR}/i686-4.9.4-release-win32-sjlj-rt_v5-rev0.7z WORKING_DIRECTORY ${DOWNLOAD_DIR}/mingw ) endif() @@ -78,24 +78,24 @@ if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/pkg-config.exe") AND (EXISTS " endif() message("Checking for nasm") -if(NOT EXISTS "${DOWNLOAD_DIR}/nasm-2.12.01-win32.zip") +if(NOT EXISTS "${DOWNLOAD_DIR}/nasm-2.13.02-win32.zip") message("Downloading nasm") - file(DOWNLOAD "http://www.nasm.us/pub/nasm/releasebuilds/2.12.01/win32/nasm-2.12.01-win32.zip" "${DOWNLOAD_DIR}/nasm-2.12.01-win32.zip") + file(DOWNLOAD "http://www.nasm.us/pub/nasm/releasebuilds/2.13.02/win32/nasm-2.13.02-win32.zip" "${DOWNLOAD_DIR}/nasm-2.13.02-win32.zip") endif() # extract nasm -if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/nasm.exe") AND (EXISTS "${DOWNLOAD_DIR}/nasm-2.12.01-win32.zip")) +if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/nasm.exe") AND (EXISTS "${DOWNLOAD_DIR}/nasm-2.13.02-win32.zip")) message("Extracting nasm") execute_process( - COMMAND ${CMAKE_COMMAND} -E tar jxf "${DOWNLOAD_DIR}/nasm-2.12.01-win32.zip" + COMMAND ${CMAKE_COMMAND} -E tar jxf "${DOWNLOAD_DIR}/nasm-2.13.02-win32.zip" WORKING_DIRECTORY ${DOWNLOAD_DIR}/ ) execute_process( - COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/nasm-2.12.01/nasm.exe" "${DOWNLOAD_DIR}/mingw/mingw32/bin/nasm.exe" + COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/nasm-2.13.02/nasm.exe" "${DOWNLOAD_DIR}/mingw/mingw32/bin/nasm.exe" ) endif() - +SET(NASM_PATH ${DOWNLOAD_DIR}/mingw/mingw32/bin/nasm.exe) message("Checking for mingwGet") if(NOT EXISTS "${DOWNLOAD_DIR}/mingw-get-0.6.2-mingw32-beta-20131004-1-bin.zip") message("Downloading mingw-get") @@ -119,6 +119,15 @@ if((EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/mingw-get.exe") AND (NOT EXISTS "$ ) endif() +if((EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/mingw-get.exe") AND (NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/msys/1.0/bin/mktemp.exe")) + message("Installing mktemp") + execute_process( + COMMAND ${DOWNLOAD_DIR}/mingw/mingw32/bin/mingw-get install msys msys-mktemp + WORKING_DIRECTORY ${DOWNLOAD_DIR}/mingw/mingw32/bin/ + ) +endif() + + message("Checking for CoreUtils") # download old core_utils for pr.exe (ffmpeg needs it to build) if(NOT EXISTS "${DOWNLOAD_DIR}/coreutils-5.97-MSYS-1.0.11-snapshot.tar.bz2") @@ -216,4 +225,3 @@ if(NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw32/bin/i686-w64-mingw32-ranlib.exe") COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/mingw/mingw32/bin/ranlib.exe" "${DOWNLOAD_DIR}/mingw/mingw32/bin/i686-w64-mingw32-ranlib.exe" ) endif() - diff --git a/build_files/build_environment/cmake/setup_mingw64.cmake b/build_files/build_environment/cmake/setup_mingw64.cmake index 14f75d410b43..3ed020d373bd 100644 --- a/build_files/build_environment/cmake/setup_mingw64.cmake +++ b/build_files/build_environment/cmake/setup_mingw64.cmake @@ -35,9 +35,9 @@ message("mingw_LIBDIR = ${mingw_LIBDIR}") message("Checking for mingw64") # download ming64 -if(NOT EXISTS "${DOWNLOAD_DIR}/x86_64-w64-mingw32-gcc-4.8.0-win64_rubenvb.7z") +if(NOT EXISTS "${DOWNLOAD_DIR}/x86_64-4.9.4-release-win32-seh-rt_v5-rev0.7z") message("Downloading mingw64") - file(DOWNLOAD "https://nchc.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win64/Personal%20Builds/rubenvb/gcc-4.8-release/x86_64-w64-mingw32-gcc-4.8.0-win64_rubenvb.7z" "${DOWNLOAD_DIR}/x86_64-w64-mingw32-gcc-4.8.0-win64_rubenvb.7z") + file(DOWNLOAD "https://nchc.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/4.9.4/threads-win32/seh/x86_64-4.9.4-release-win32-seh-rt_v5-rev0.7z" "${DOWNLOAD_DIR}/x86_64-4.9.4-release-win32-seh-rt_v5-rev0.7z") endif() # make mingw root directory @@ -49,10 +49,10 @@ if(NOT EXISTS "${DOWNLOAD_DIR}/mingw") endif() # extract mingw64 -if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/mingw64env.cmd") AND (EXISTS "${DOWNLOAD_DIR}/x86_64-w64-mingw32-gcc-4.8.0-win64_rubenvb.7z")) +if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/ming64sh.cmd") AND (EXISTS "${DOWNLOAD_DIR}/x86_64-4.9.4-release-win32-seh-rt_v5-rev0.7z")) message("Extracting mingw64") execute_process( - COMMAND ${CMAKE_COMMAND} -E tar jxf ${DOWNLOAD_DIR}/x86_64-w64-mingw32-gcc-4.8.0-win64_rubenvb.7z + COMMAND ${CMAKE_COMMAND} -E tar jxf ${DOWNLOAD_DIR}/x86_64-4.9.4-release-win32-seh-rt_v5-rev0.7z WORKING_DIRECTORY ${DOWNLOAD_DIR}/mingw ) endif() @@ -78,23 +78,24 @@ if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/pkg-config.exe") AND (EXISTS " endif() message("Checking for nasm") -if(NOT EXISTS "${DOWNLOAD_DIR}/nasm-2.12.01-win64.zip") +if(NOT EXISTS "${DOWNLOAD_DIR}/nasm-2.13.02-win64.zip") message("Downloading nasm") - file(DOWNLOAD "http://www.nasm.us/pub/nasm/releasebuilds/2.12.01/win64/nasm-2.12.01-win64.zip" "${DOWNLOAD_DIR}/nasm-2.12.01-win64.zip") + file(DOWNLOAD "http://www.nasm.us/pub/nasm/releasebuilds/2.13.02/win64/nasm-2.13.02-win64.zip" "${DOWNLOAD_DIR}/nasm-2.13.02-win64.zip") endif() # extract nasm -if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/nasm.exe") AND (EXISTS "${DOWNLOAD_DIR}/nasm-2.12.01-win64.zip")) +if((NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/nasm.exe") AND (EXISTS "${DOWNLOAD_DIR}/nasm-2.13.02-win64.zip")) message("Extracting nasm") execute_process( - COMMAND ${CMAKE_COMMAND} -E tar jxf "${DOWNLOAD_DIR}/nasm-2.12.01-win64.zip" + COMMAND ${CMAKE_COMMAND} -E tar jxf "${DOWNLOAD_DIR}/nasm-2.13.02-win64.zip" WORKING_DIRECTORY ${DOWNLOAD_DIR}/ ) execute_process( - COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/nasm-2.12.01/nasm.exe" "${DOWNLOAD_DIR}/mingw/mingw64/bin/nasm.exe" + COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/nasm-2.13.02/nasm.exe" "${DOWNLOAD_DIR}/mingw/mingw64/bin/nasm.exe" ) endif() +SET(NASM_PATH ${DOWNLOAD_DIR}/mingw/mingw64/bin/nasm.exe) message("Checking for mingwGet") if(NOT EXISTS "${DOWNLOAD_DIR}/mingw-get-0.6.2-mingw32-beta-20131004-1-bin.zip") @@ -119,6 +120,14 @@ if((EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/mingw-get.exe") AND (NOT EXISTS "$ ) endif() +if((EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/mingw-get.exe") AND (NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/msys/1.0/bin/mktemp.exe")) + message("Installing mktemp") + execute_process( + COMMAND ${DOWNLOAD_DIR}/mingw/mingw64/bin/mingw-get install msys msys-mktemp + WORKING_DIRECTORY ${DOWNLOAD_DIR}/mingw/mingw64/bin/ + ) +endif() + message("Checking for CoreUtils") # download old core_utils for pr.exe (ffmpeg needs it to build) if(NOT EXISTS "${DOWNLOAD_DIR}/coreutils-5.97-MSYS-1.0.11-snapshot.tar.bz2") @@ -216,4 +225,3 @@ if(NOT EXISTS "${DOWNLOAD_DIR}/mingw/mingw64/bin/x86_64-w64-mingw32-ranlib.exe") COMMAND ${CMAKE_COMMAND} -E copy "${DOWNLOAD_DIR}/mingw/mingw64/bin/ranlib.exe" "${DOWNLOAD_DIR}/mingw/mingw64/bin/x86_64-w64-mingw32-ranlib.exe" ) endif() - diff --git a/build_files/build_environment/cmake/sqlite.cmake b/build_files/build_environment/cmake/sqlite.cmake new file mode 100644 index 000000000000..e5aa124a4148 --- /dev/null +++ b/build_files/build_environment/cmake/sqlite.cmake @@ -0,0 +1,57 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(SQLITE_CONFIGURE_ENV echo .) +set(SQLITE_CONFIGURATION_ARGS) + +if(UNIX AND NOT APPLE) + set(SQLITE_LDFLAGS -Wl,--as-needed) + set(SQLITE_CFLAGS + "-DSQLITE_SECURE_DELETE -DSQLITE_ENABLE_COLUMN_METADATA \ + -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS \ + -DSQLITE_ENABLE_RTREE=1 -DSQLITE_SOUNDEX=1 \ + -DSQLITE_ENABLE_UNLOCK_NOTIFY \ + -DSQLITE_OMIT_LOOKASIDE=1 -DSQLITE_ENABLE_DBSTAT_VTAB \ + -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT=1 \ + -DSQLITE_ENABLE_LOAD_EXTENSION \ + -DSQLITE_ENABLE_JSON1 \ + -DSQLITE_LIKE_DOESNT_MATCH_BLOBS \ + -DSQLITE_THREADSAFE=1 \ + -DSQLITE_ENABLE_FTS3_TOKENIZER=1 \ + -DSQLITE_MAX_SCHEMA_RETRY=25 \ + -DSQLITE_ENABLE_PREUPDATE_HOOK \ + -DSQLITE_ENABLE_SESSION \ + -DSQLITE_ENABLE_STMTVTAB \ + -DSQLITE_MAX_VARIABLE_NUMBER=250000 \ + -fPIC") + set(SQLITE_CONFIGURE_ENV ${SQLITE_CONFIGURE_ENV} && export LDFLAGS=${SQLITE_LDFLAGS} && export CFLAGS=${SQLITE_CFLAGS}) + set(SQLITE_CONFIGURATION_ARGS ${SQLITE_CONFIGURATION_ARGS} --enable-threadsafe --enable-load-extension --enable-json1 --enable-fts4 --enable-fts5 + --enable-shared=no) +endif() + +ExternalProject_Add(external_sqlite + URL ${SQLITE_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH SHA1=${SQLITE_HASH} + PREFIX ${BUILD_DIR}/sqlite + PATCH_COMMAND ${SQLITE_PATCH_CMD} + CONFIGURE_COMMAND ${SQLITE_CONFIGURE_ENV} && cd ${BUILD_DIR}/sqlite/src/external_sqlite/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/sqlite ${SQLITE_CONFIGURATION_ARGS} + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/sqlite/src/external_sqlite/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/sqlite/src/external_sqlite/ && make install + INSTALL_DIR ${LIBDIR}/sqlite +) diff --git a/build_files/build_environment/cmake/ssl.cmake b/build_files/build_environment/cmake/ssl.cmake new file mode 100644 index 000000000000..dd1b9957cc25 --- /dev/null +++ b/build_files/build_environment/cmake/ssl.cmake @@ -0,0 +1,44 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(SSL_CONFIGURE_COMMAND ./Configure) +set(SSL_PATCH_CMD echo .) + +if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + set(SSL_EXTRA_ARGS enable-ec_nistp_64_gcc_128) + set(SSL_OS_COMPILER "blender-x86_64") +else() + set(SSL_OS_COMPILER "blender-x86") +endif() + +ExternalProject_Add(external_ssl + URL ${SSL_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH SHA256=${SSL_HASH} + PREFIX ${BUILD_DIR}/ssl + PATCH_COMMAND ${SSL_PATCH_CMD} + CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ssl/src/external_ssl/ && ${SSL_CONFIGURE_COMMAND} --prefix=${LIBDIR}/ssl + --openssldir=${LIBDIR}/ssl + no-shared + no-idea no-mdc2 no-rc5 no-zlib no-ssl3 enable-unit-test no-ssl3-method enable-rfc3779 enable-cms + --config=${CMAKE_CURRENT_SOURCE_DIR}/cmake/ssl.conf + ${SSL_OS_COMPILER} + BUILD_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ssl/src/external_ssl/ && make -j${MAKE_THREADS} + INSTALL_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/ssl/src/external_ssl/ && make install + INSTALL_DIR ${LIBDIR}/ssl +) diff --git a/build_files/build_environment/cmake/ssl.conf b/build_files/build_environment/cmake/ssl.conf new file mode 100644 index 000000000000..a9534e56291d --- /dev/null +++ b/build_files/build_environment/cmake/ssl.conf @@ -0,0 +1,10 @@ +%targets = ( + "blender-x86" => { + inherit_from => [ "linux-x86" ], + cflags => add("-fPIC"), + }, + "blender-x86_64" => { + inherit_from => [ "linux-x86_64" ], + cflags => add("-fPIC"), + }, +); diff --git a/build_files/build_environment/cmake/tbb.cmake b/build_files/build_environment/cmake/tbb.cmake index fa5c9029ed06..4e0357da8bbd 100644 --- a/build_files/build_environment/cmake/tbb.cmake +++ b/build_files/build_environment/cmake/tbb.cmake @@ -23,14 +23,6 @@ set(TBB_EXTRA_ARGS -DTBB_BUILD_STATIC=On ) -if(TBB_VERSION MATCHES 2018) - set(TBB_VS_VERSION vs2013) -elseif(TBB_VERSION MATCHES 2017) - set(TBB_VS_VERSION vs2012) -else() - set(TBB_VS_VERSION vs2010) -endif() - # CMake script for TBB from https://github.com/wjakob/tbb/blob/master/CMakeLists.txt ExternalProject_Add(external_tbb URL ${TBB_URI} @@ -38,7 +30,23 @@ ExternalProject_Add(external_tbb URL_HASH MD5=${TBB_HASH} PREFIX ${BUILD_DIR}/tbb PATCH_COMMAND COMMAND ${CMAKE_COMMAND} -E copy ${PATCH_DIR}/cmakelists_tbb.txt ${BUILD_DIR}/tbb/src/external_tbb/CMakeLists.txt && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/tbb/src/external_tbb/build/${TBB_VS_VERSION}/version_string.ver ${BUILD_DIR}/tbb/src/external_tbb/src/tbb/version_string.ver + ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/tbb/src/external_tbb/build/vs2013/version_string.ver ${BUILD_DIR}/tbb/src/external_tbb/src/tbb/version_string.ver CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/tbb ${DEFAULT_CMAKE_FLAGS} ${TBB_EXTRA_ARGS} INSTALL_DIR ${LIBDIR}/tbb ) + +if (WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_tbb after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/tbb/lib/tbb_static.lib ${HARVEST_TARGET}/tbb/lib/tbb.lib + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/tbb/include/ ${HARVEST_TARGET}/tbb/include/ + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_tbb after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/tbb/lib/tbb_static.lib ${HARVEST_TARGET}/tbb/lib/tbb_debug.lib + DEPENDEES install + ) + endif() +endif() diff --git a/build_files/build_environment/cmake/tinyxml.cmake b/build_files/build_environment/cmake/tinyxml.cmake new file mode 100644 index 000000000000..9c7d0397c78d --- /dev/null +++ b/build_files/build_environment/cmake/tinyxml.cmake @@ -0,0 +1,31 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(TINYXML_EXTRA_ARGS +) + +ExternalProject_Add(external_tinyxml + URL ${TINYXML_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${TINYXML_HASH} + PREFIX ${BUILD_DIR}/tinyxml + #patch taken from ocio + PATCH_COMMAND ${PATCH_CMD} -p 1 -N -d ${BUILD_DIR}/tinyxml/src/external_tinyxml < ${PATCH_DIR}/tinyxml.diff + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/tinyxml ${DEFAULT_CMAKE_FLAGS} ${TINYXML_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/tinyxml +) diff --git a/build_files/build_environment/cmake/versions.cmake b/build_files/build_environment/cmake/versions.cmake index 361787fa9567..7ede80a2be9c 100644 --- a/build_files/build_environment/cmake/versions.cmake +++ b/build_files/build_environment/cmake/versions.cmake @@ -16,46 +16,63 @@ # # ***** END GPL LICENSE BLOCK ***** -set(ZLIB_VERSION 1.2.8) -set(ZLIB_URI https://netcologne.dl.sourceforge.net/project/libpng/zlib/${ZLIB_VERSION}/zlib-${ZLIB_VERSION}.tar.gz) -set(ZLIB_HASH 44d667c142d7cda120332623eab69f40) +set(ZLIB_VERSION 1.2.11) +set(ZLIB_URI https://zlib.net/zlib-${ZLIB_VERSION}.tar.gz) +set(ZLIB_HASH 1c9f62f0778697a09d36121ead88e08e) -set(OPENAL_VERSION 1.17.2) +set(OPENAL_VERSION 1.18.2) set(OPENAL_URI http://kcat.strangesoft.net/openal-releases/openal-soft-${OPENAL_VERSION}.tar.bz2) -set(OPENAL_HASH 1764e0d8fec499589b47ebc724e0913d) +set(OPENAL_HASH d4eeb0889812e2fdeaa1843523d76190) -set(PNG_VERSION 1.6.21) -set(PNG_URI http://prdownloads.sourceforge.net/libpng/libpng-${PNG_VERSION}.tar.gz) -set(PNG_HASH aca36ec8e0a3b406a5912243bc243717) +set(PNG_VERSION 1.6.35) +set(PNG_URI http://prdownloads.sourceforge.net/libpng/libpng-${PNG_VERSION}.tar.xz) +set(PNG_HASH 678b7e696a62a193ed3503b04bf449d6) -set(JPEG_VERSION 1.4.2) +set(JPEG_VERSION 1.5.3) set(JPEG_URI https://github.com/libjpeg-turbo/libjpeg-turbo/archive/${JPEG_VERSION}.tar.gz) -set(JPEG_HASH f9804884c1c41eb7f4febb9353a2cb27) +set(JPEG_HASH 5b7549d440b86c98a517355c102d155e) -set(BOOST_VERSION 1.60.0) -set(BOOST_VERSION_NODOTS 1_60_0) -set(BOOST_URI http://sourceforge.net/projects/boost/files/boost/${BOOST_VERSION}/boost_${BOOST_VERSION_NODOTS}.tar.bz2/download) -set(BOOST_MD5 65a840e1a0b13a558ff19eeb2c4f0cbe) +set(BOOST_VERSION 1.68.0) +set(BOOST_VERSION_NODOTS 1_68_0) +set(BOOST_URI https://dl.bintray.com/boostorg/release/${BOOST_VERSION}/source/boost_${BOOST_VERSION_NODOTS}.tar.gz) +set(BOOST_HASH 5d8b4503582fffa9eefdb9045359c239) -set(BLOSC_VERSION 1.7.1) -set(BLOSC_URI https://github.com/Blosc/c-blosc/archive/v${BLOSC_VERSION}.zip) -set(BLOSC_HASH ff5cc729a5a25934ef714217218eed26) +set(BLOSC_VERSION 1.14.4) +set(BLOSC_URI https://github.com/Blosc/c-blosc/archive/v${BLOSC_VERSION}.tar.gz) +set(BLOSC_HASH e80dfc71e4cba03b8d01ed0876547ffe) set(PTHREADS_VERSION 2-9-1) set(PTHREADS_URI ftp://sourceware.org/pub/pthreads-win32/pthreads-w32-${PTHREADS_VERSION}-release.tar.gz) set(PTHREADS_SHA512 9c06e85310766834370c3dceb83faafd397da18a32411ca7645c8eb6b9495fea54ca2872f4a3e8d83cb5fdc5dea7f3f0464be5bb9af3222a6534574a184bd551) -set(ILMBASE_VERSION 2.2.0) -set(ILMBASE_URI http://download.savannah.nongnu.org/releases/openexr/ilmbase-${ILMBASE_VERSION}.tar.gz) -set(ILMBASE_HASH b540db502c5fa42078249f43d18a4652) +set(ILMBASE_VERSION 2.3.0) +if (WIN32) + if(BUILD_MODE STREQUAL Release) + set(ILMBASE_VERSION_POSTFIX _s) + set(OPENEXR_VERSION_POSTFIX _s) + else() + set(ILMBASE_VERSION_POSTFIX _s_d) + set(OPENEXR_VERSION_POSTFIX _s_d) + endif() +else() + set(ILMBASE_VERSION_POSTFIX) +endif() +set(ILMBASE_URI https://github.com/openexr/openexr/releases/download/v${ILMBASE_VERSION}/ilmbase-${ILMBASE_VERSION}.tar.gz) +set(ILMBASE_HASH 354bf86de3b930ab87ac63619d60c860) -set(OPENEXR_VERSION 2.2.0) -set(OPENEXR_URI http://download.savannah.nongnu.org/releases/openexr/openexr-2.2.0.tar.gz) -set(OPENEXR_HASH b64e931c82aa3790329c21418373db4e) +set(OPENEXR_VERSION 2.3.0) +if (WIN32) #release 2.3.0 tarball has broken cmake support + set(OPENEXR_URI https://github.com/openexr/openexr/archive/0ac2ea34c8f3134148a5df4052e40f155b76f6fb.tar.gz) + set(OPENEXR_HASH ed159435d508240712fbaaa21d94bafb) +else() + set(OPENEXR_VERSION_POSTFIX) + set(OPENEXR_URI https://github.com/openexr/openexr/releases/download/v${OPENEXR_VERSION}/openexr-${OPENEXR_VERSION}.tar.gz) + set(OPENEXR_HASH a157e8a46596bc185f2472a5a4682174) +endif() -set(FREETYPE_VERSION 263) -set(FREETYPE_URI http://download.savannah.gnu.org/releases/freetype/ft${FREETYPE_VERSION}.zip) -set(FREETYPE_HASH 0db2a43301572e5c2b4a0864f237aeeb) +set(FREETYPE_VERSION 2.9.1) +set(FREETYPE_URI http://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPE_VERSION}.tar.gz) +set(FREETYPE_HASH 3adb0e35d3c100c456357345ccfa8056) set(GLEW_VERSION 1.13.0) set(GLEW_URI http://prdownloads.sourceforge.net/glew/glew/${GLEW_VERSION}/glew-${GLEW_VERSION}.tgz) @@ -69,9 +86,9 @@ set(HDF5_VERSION 1.8.17) set(HDF5_URI https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.8/hdf5-${HDF5_VERSION}/src/hdf5-${HDF5_VERSION}.tar.gz) set(HDF5_HASH 7d572f8f3b798a628b8245af0391a0ca) -set(ALEMBIC_VERSION 1.7.1) -set(ALEMBIC_URI https://github.com/alembic/alembic/archive/${ALEMBIC_VERSION}.zip) -set(ALEMBIC_MD5 cf7705055501d5ea0cb8256866496f79) +set(ALEMBIC_VERSION 1.7.8) +set(ALEMBIC_URI https://github.com/alembic/alembic/archive/${ALEMBIC_VERSION}.tar.gz) +set(ALEMBIC_MD5 d095c2feb5e183b824904db7b63c1d30) ## hash is for 3.1.2 set(GLFW_GIT_UID 30306e54705c3adae9fe082c816a3be71963485c) @@ -88,141 +105,122 @@ set(CUEW_GIT_UID 1744972026de9cf27c8a7dc39cf39cd83d5f922f) set(CUEW_URI https://github.com/CudaWrangler/cuew/archive/${CUEW_GIT_UID}.zip) set(CUEW_HASH 86760d62978ebfd96cd93f5aa1abaf4a) -set(OPENSUBDIV_VERSION v3_1_1) -set(OPENSUBDIV_Hash 25a9a6a94136b0eb85ce69e9c8cb6ab3) -set(OPENSUBDIV_URI https://github.com/PixarAnimationStudios/OpenSubdiv/archive/${OPENSUBDIV_VERSION}.zip) +set(OPENSUBDIV_VERSION v3_3_3) +set(OPENSUBDIV_Hash 29c79dc01ef616aab02670bed5544ddd) +set(OPENSUBDIV_URI https://github.com/PixarAnimationStudios/OpenSubdiv/archive/${OPENSUBDIV_VERSION}.tar.gz) -set(SDL_VERSION 2.0.4) +set(SDL_VERSION 2.0.8) set(SDL_URI https://www.libsdl.org/release/SDL2-${SDL_VERSION}.tar.gz) -set(SDL_HASH 44fc4a023349933e7f5d7a582f7b886e) +set(SDL_HASH 3800d705cef742c6a634f202c37f263f) -set(OPENCOLLADA_VERSION v1.6.51) +set(OPENCOLLADA_VERSION v1.6.63) set(OPENCOLLADA_URI https://github.com/KhronosGroup/OpenCOLLADA/archive/${OPENCOLLADA_VERSION}.tar.gz) -set(OPENCOLLADA_HASH 23db5087faed4bc4cc1dfe456c0d4701) +set(OPENCOLLADA_HASH e937c3897b86fc0da53cde97257f5156) -set(OPENCOLORIO_URI https://github.com/imageworks/OpenColorIO/archive/6de971097c7f552300f669ed69ca0b6cf5a70843.zip) -set(OPENCOLORIO_HASH c9de0fd98f26ce6f2e08d617ca68b8e4) +set(OPENCOLORIO_VERSION 1.1.0) +set(OPENCOLORIO_URI https://github.com/imageworks/OpenColorIO/archive/v${OPENCOLORIO_VERSION}.tar.gz) +set(OPENCOLORIO_HASH 802d8f5b1d1fe316ec5f76511aa611b8) -set(LLVM_VERSION 3.4.2) -set(LLVM_URI http://releases.llvm.org/${LLVM_VERSION}/llvm-${LLVM_VERSION}.src.tar.gz) -set(LLVM_HASH a20669f75967440de949ac3b1bad439c) +set(LLVM_VERSION 6.0.1) +set(LLVM_URI http://releases.llvm.org/${LLVM_VERSION}/llvm-${LLVM_VERSION}.src.tar.xz) +set(LLVM_HASH c88c98709300ce2c285391f387fecce0) -set(CLANG_URI http://releases.llvm.org/${LLVM_VERSION}/cfe-${LLVM_VERSION}.src.tar.gz) -set(CLANG_HASH 87945973b7c73038871c5f849a818588) +set(CLANG_URI http://releases.llvm.org/${LLVM_VERSION}/cfe-${LLVM_VERSION}.src.tar.xz) +set(CLANG_HASH 4e419bd4e3b55aa06d872320f754bd85) -set(OPENIMAGEIO_VERSION 1.7.15) -set(OPENIMAGEIO_URI https://github.com/OpenImageIO/oiio/archive/Release-${OPENIMAGEIO_VERSION}.zip) -set(OPENIMAGEIO_HASH_178 e156e3669af0e1373142ab5e8f13de66) -set(OPENIMAGEIO_HASH_179 4121cb0e0433bda6a7ef32c8628a149f) -set(OPENIMAGEIO_HASH_1713 42a662775b834161ba88c6abdb299360) -set(OPENIMAGEIO_HASH_1715 e2ece0f62c013d64c478f82265988b0b) -set(OPENIMAGEIO_HASH ${OPENIMAGEIO_HASH_1715}) +set(OPENMP_URI http://releases.llvm.org/${LLVM_VERSION}/openmp-${LLVM_VERSION}.src.tar.xz) +set(OPENMP_HASH 4826402ae3633c36c51ba4d0e5527d30) +set(OPENIMAGEIO_VERSION 1.8.13) +set(OPENIMAGEIO_URI https://github.com/OpenImageIO/oiio/archive/Release-${OPENIMAGEIO_VERSION}.tar.gz) +set(OPENIMAGEIO_HASH f5526c3c9878029ee900d84856683f93) -set(TIFF_VERSION 4.0.6) +set(TIFF_VERSION 4.0.9) set(TIFF_URI http://download.osgeo.org/libtiff/tiff-${TIFF_VERSION}.tar.gz) -set(TIFF_HASH d1d2e940dea0b5ad435f21f03d96dd72) +set(TIFF_HASH 54bad211279cc93eb4fca31ba9bfdc79) -set(FLEXBISON_VERSION 2.5.5) -set(FLEXBISON_URI http://prdownloads.sourceforge.net/winflexbison//win_flex_bison-2.5.5.zip) -set(FLEXBISON_HASH d87a3938194520d904013abef3df10ce) +set(OSL_VERSION 1.9.9) +set(OSL_URI https://github.com/imageworks/OpenShadingLanguage/archive/Release-${OSL_VERSION}.tar.gz) +set(OSL_HASH 44ad511e424965a10fce051a053b0605) -set(OSL_VERSION 1.7.5) -set(OSL_URI https://github.com/imageworks/OpenShadingLanguage/archive/Release-${OSL_VERSION}.zip) -set(OSL_HASH 6924dd5d453159e7b6eb106a08c358cf) - -set(PYTHON_VERSION 3.6.2) -set(PYTHON_SHORT_VERSION 3.6) -set(PYTHON_SHORT_VERSION_NO_DOTS 36) +set(PYTHON_VERSION 3.7.0) +set(PYTHON_SHORT_VERSION 3.7) +set(PYTHON_SHORT_VERSION_NO_DOTS 37) set(PYTHON_URI https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tar.xz) -set(PYTHON_HASH 2c68846471994897278364fc18730dd9) +set(PYTHON_HASH eb8c2a6b1447d50813c02714af4681f3) -if(UNIX AND NOT APPLE) - # Needed to be compatible with GCC 7, other platforms can upgrade later - set(TBB_VERSION 2017_U7) - set(TBB_URI https://github.com/01org/tbb/archive/${TBB_VERSION}.tar.gz) - set(TBB_HASH 364f2a4b80e978f38a69cbf7c466b898) -else() - set(TBB_VERSION 44_20160128) - set(TBB_URI https://www.threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb${TBB_VERSION}oss_src_0.tgz) - set(TBB_HASH 9d8a4cdf43496f1b3f7c473a5248e5cc) -endif() +set(TBB_VERSION 2018_U5) +set(TBB_URI https://github.com/01org/tbb/archive/${TBB_VERSION}.tar.gz) +set(TBB_HASH ff3ae09f8c23892fbc3008c39f78288f) -set(OPENVDB_VERSION 3.1.0) +set(OPENVDB_VERSION 5.1.0) set(OPENVDB_URI https://github.com/dreamworksanimation/openvdb/archive/v${OPENVDB_VERSION}.tar.gz) -set(OPENVDB_HASH 30a7e9571a03ab7bcf1a39fb62aa436f) +set(OPENVDB_HASH 5310101f874dcfd2165f9cee68c22624) -set(IDNA_VERSION 2.6) -set(CHARDET_VERSION 3.0.2) -set(URLLIB3_VERSION 1.22) -set(CERTIFI_VERSION 2017.7.27.1) -set(REQUESTS_VERSION 2.18.4) +set(IDNA_VERSION 2.7) +set(CHARDET_VERSION 3.0.4) +set(URLLIB3_VERSION 1.23) +set(CERTIFI_VERSION 2018.8.13) +set(REQUESTS_VERSION 2.19.1) -set(NUMPY_VERSION v1.13.1) -set(NUMPY_SHORT_VERSION 1.13) -set(NUMPY_URI https://pypi.python.org/packages/c0/3a/40967d9f5675fbb097ffec170f59c2ba19fc96373e73ad47c2cae9a30aed/numpy-1.13.1.zip) -set(NUMPY_HASH 2c3c0f4edf720c3a7b525dacc825b9ae) +set(NUMPY_VERSION v1.15.0) +set(NUMPY_SHORT_VERSION 1.15) +set(NUMPY_URI https://files.pythonhosted.org/packages/3a/20/c81632328b1a4e1db65f45c0a1350a9c5341fd4bbb8ea66cdd98da56fe2e/numpy-1.15.0.zip) +set(NUMPY_HASH 20e13185089011116a98e11c9bf8aa07) -set(LAME_VERSION 3.99.5) -set(LAME_URI http://downloads.sourceforge.net/project/lame/lame/3.99/lame-${LAME_VERSION}.tar.gz) -set(LAME_HASH 84835b313d4a8b68f5349816d33e07ce) +set(LAME_VERSION 3.100) +set(LAME_URI http://downloads.sourceforge.net/project/lame/lame/3.100/lame-${LAME_VERSION}.tar.gz) +set(LAME_HASH 83e260acbe4389b54fe08e0bdbf7cddb) -set(OGG_VERSION 1.3.2) +set(OGG_VERSION 1.3.3) set(OGG_URI http://downloads.xiph.org/releases/ogg/libogg-${OGG_VERSION}.tar.gz) -set(OGG_HASH e19ee34711d7af328cb26287f4137e70630e7261b17cbe3cd41011d73a654692) +set(OGG_HASH c2e8a485110b97550f453226ec644ebac6cb29d1caef2902c007edab4308d985) -set(VORBIS_VERSION 1.3.5) +set(VORBIS_VERSION 1.3.6) set(VORBIS_URI http://downloads.xiph.org/releases/vorbis/libvorbis-${VORBIS_VERSION}.tar.gz) -set(VORBIS_HASH 6efbcecdd3e5dfbf090341b485da9d176eb250d893e3eb378c428a2db38301ce) +set(VORBIS_HASH 6ed40e0241089a42c48604dc00e362beee00036af2d8b3f46338031c9e0351cb) set(THEORA_VERSION 1.1.1) set(THEORA_URI http://downloads.xiph.org/releases/theora/libtheora-${THEORA_VERSION}.tar.bz2) set(THEORA_HASH b6ae1ee2fa3d42ac489287d3ec34c5885730b1296f0801ae577a35193d3affbc) -set(FLAC_VERSION 1.3.1) +set(FLAC_VERSION 1.3.2) set(FLAC_URI http://downloads.xiph.org/releases/flac/flac-${FLAC_VERSION}.tar.xz) -set(FLAC_HASH 4773c0099dba767d963fd92143263be338c48702172e8754b9bc5103efe1c56c) +set(FLAC_HASH 91cfc3ed61dc40f47f050a109b08610667d73477af6ef36dcad31c31a4a8d53f) -set(VPX_VERSION 1.5.0) -set(VPX_URI http://storage.googleapis.com/downloads.webmproject.org/releases/webm/libvpx-${VPX_VERSION}.tar.bz2) -set(VPX_HASH 306d67908625675f8e188d37a81fbfafdf5068b09d9aa52702b6fbe601c76797) +set(VPX_VERSION 1.7.0) +set(VPX_URI https://github.com/webmproject/libvpx/archive/v${VPX_VERSION}/libvpx-v${VPX_VERSION}.tar.gz) +set(VPX_HASH 1fec931eb5c94279ad219a5b6e0202358e94a93a90cfb1603578c326abfc1238) -set(ORC_VERSION 0.4.25) -set(ORC_URI https://gstreamer.freedesktop.org/src/orc/orc-${ORC_VERSION}.tar.xz) -set(ORC_HASH c1b1d54a58f26d483f0b3881538984789fe5d5460ab8fab74a1cacbd3d1c53d1) +set(X264_URI http://download.videolan.org/pub/videolan/x264/snapshots/x264-snapshot-20180811-2245-stable.tar.bz2) +set(X264_HASH ae8a868a0e236a348b35d79f3ee80294b169d1195408b689f9851383661ed7aa) -set(SCHROEDINGER_VERSION 1.0.11) -set(SCHROEDINGER_URI https://download.videolan.org/contrib/schroedinger/schroedinger-${SCHROEDINGER_VERSION}.tar.gz) -set(SCHROEDINGER_HASH 1e572a0735b92aca5746c4528f9bebd35aa0ccf8619b22fa2756137a8cc9f912) - -set(X264_URI http://download.videolan.org/pub/videolan/x264/snapshots/x264-snapshot-20160401-2245-stable.tar.bz2) -set(X264_HASH 1e9a7b835e80313aade53a9b6ff353e099de3856bf5f30a4d8dfc91281f786f5) - -set(XVIDCORE_VERSION 1.3.4) +set(XVIDCORE_VERSION 1.3.5) set(XVIDCORE_URI http://downloads.xvid.org/downloads/xvidcore-${XVIDCORE_VERSION}.tar.gz) -set(XVIDCORE_HASH 4e9fd62728885855bc5007fe1be58df42e5e274497591fec37249e1052ae316f) +set(XVIDCORE_HASH 165ba6a2a447a8375f7b06db5a3c91810181f2898166e7c8137401d7fc894cf0) #this has to be in sync with the version in blenders /extern folder -set(OPENJPEG_VERSION 1.5.2) -set(OPENJPEG_SHORT_VERSION 1.5) -set(OPENJPEG_URI https://github.com/uclouvain/openjpeg/archive/version.${OPENJPEG_VERSION}.tar.gz) -set(OPENJPEG_HASH 3734e95edd0bef6e056815591755efd822228dc3cd866894e00a2c929026b16d) +set(OPENJPEG_VERSION 2.3.0) +set(OPENJPEG_SHORT_VERSION 2.3) +# Use slightly newer commit after release which includes a cmake fix +set(OPENJPEG_URI https://github.com/uclouvain/openjpeg/archive/66297f07a43.zip) +set(OPENJPEG_HASH 8242b18d908c7c42174e4231a741cfa7ce7c26b6ed5c9644feb9df7b3054310b) -set(FAAD_VERSION 2-2.7) -set(FAAD_URI http://downloads.sourceforge.net/faac/faad${FAAD_VERSION}.tar.bz2) -set(FAAD_HASH 4c332fa23febc0e4648064685a3d4332) +set(FAAD_VERSION 2-2.8.8) +set(FAAD_URI http://downloads.sourceforge.net/faac/faad${FAAD_VERSION}.tar.gz) +set(FAAD_HASH 28f6116efdbe9378269f8a6221767d1f) -set(FFMPEG_VERSION 3.2.1) +set(FFMPEG_VERSION 4.0.2) set(FFMPEG_URI http://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.bz2) -set(FFMPEG_HASH cede174178e61f882844f5870c35ce72) +set(FFMPEG_HASH 5576e8a22f80b6a336db39808f427cfb) -set(FFTW_VERSION 3.3.4) +set(FFTW_VERSION 3.3.8) set(FFTW_URI http://www.fftw.org/fftw-${FFTW_VERSION}.tar.gz) -set(FFTW_HASH 2edab8c06b24feeb3b82bbb3ebf3e7b3) +set(FFTW_HASH 8aac833c943d8e90d51b697b27d4384d) -set(ICONV_VERSION 1.14) +set(ICONV_VERSION 1.15) set(ICONV_URI http://ftp.gnu.org/pub/gnu/libiconv/libiconv-${ICONV_VERSION}.tar.gz) -set(ICONV_HASH e34509b1623cec449dfeb73d7ce9c6c6) +set(ICONV_HASH ace8b5f2db42f7b3b3057585e80d9808) set(LAPACK_VERSION 3.6.0) set(LAPACK_URI http://www.netlib.org/lapack/lapack-${LAPACK_VERSION}.tgz) @@ -240,9 +238,9 @@ set(HIDAPI_UID 89a6c75dc6f45ecabd4ddfbd2bf5ba6ad8ba38b5) set(HIDAPI_URI https://github.com/TheOnlyJoey/hidapi/archive/${HIDAPI_UID}.zip) set(HIDAPI_HASH b6e22f6b514f8bcf594989f20ffc46fb) -set(WEBP_VERSION 0.5.1) +set(WEBP_VERSION 0.6.1) set(WEBP_URI https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-${WEBP_VERSION}.tar.gz) -set(WEBP_HASH 3d7db92ebba5b4f679413d25c6040881) +set(WEBP_HASH b49ce9c3e3e9acae4d91bca44bb85a72) set(SPNAV_VERSION 0.2.3) set(SPNAV_URI http://downloads.sourceforge.net/project/spacenav/spacenav%20library%20%28SDK%29/libspnav%20${SPNAV_VERSION}/libspnav-${SPNAV_VERSION}.tar.gz) @@ -255,3 +253,48 @@ set(JEMALLOC_HASH 507f7b6b882d868730d644510491d18f) set(XML2_VERSION 2.9.4) set(XML2_URI ftp://xmlsoft.org/libxml2/libxml2-${XML2_VERSION}.tar.gz) set(XML2_HASH ae249165c173b1ff386ee8ad676815f5) + +set(TINYXML_VERSION 2_6_2) +set(TINYXML_VERSION_DOTS 2.6.2) +set(TINYXML_URI https://nchc.dl.sourceforge.net/project/tinyxml/tinyxml/${TINYXML_VERSION_DOTS}/tinyxml_${TINYXML_VERSION}.tar.gz) +set(TINYXML_HASH c1b864c96804a10526540c664ade67f0) + +set(YAMLCPP_VERSION 0.6.2) +set(YAMLCPP_URI https://codeload.github.com/jbeder/yaml-cpp/tar.gz/yaml-cpp-${YAMLCPP_VERSION}) +set(YAMLCPP_HASH 5b943e9af0060d0811148b037449ef82) + +set(LCMS_VERSION 2.9) +set(LCMS_URI https://nchc.dl.sourceforge.net/project/lcms/lcms/${LCMS_VERSION}/lcms2-${LCMS_VERSION}.tar.gz) +set(LCMS_HASH 8de1b7724f578d2995c8fdfa35c3ad0e) + +set(PUGIXML_VERSION 1.9) +set(PUGIXML_URI https://github.com/zeux/pugixml/archive/v1.9.tar.gz) +set(PUGIXML_HASH 9346ca1dce2c48f1748c12fdac41a714) + +set(FLEXBISON_VERSION 2.5.5) +set(FLEXBISON_URI http://prdownloads.sourceforge.net/winflexbison//win_flex_bison-2.5.5.zip) +set(FLEXBISON_HASH d87a3938194520d904013abef3df10ce) + +# Libraries to keep Python modules static on Linux. + +# NOTE: bzip.org domain does no longer belong to BZip 2 project, so we download +# sources from Debian packaging. +set(BZIP2_VERSION 1.0.6) +set(BZIP2_URI http://http.debian.net/debian/pool/main/b/bzip2/bzip2_${BZIP2_VERSION}.orig.tar.bz2) +set(BZIP2_HASH d70a9ccd8bdf47e302d96c69fecd54925f45d9c7b966bb4ef5f56b770960afa7) + +set(FFI_VERSION 3.2.1) +set(FFI_URI ftp://sourceware.org/pub/libffi/libffi-${FFI_VERSION}.tar.gz) +set(FFI_HASH d06ebb8e1d9a22d19e38d63fdb83954253f39bedc5d46232a05645685722ca37) + +set(LZMA_VERSION 5.2.4) +set(LZMA_URI https://tukaani.org/xz/xz-${LZMA_VERSION}.tar.bz2) +set(LZMA_HASH 3313fd2a95f43d88e44264e6b015e7d03053e681860b0d5d3f9baca79c57b7bf) + +set(SSL_VERSION 1.1.0i) +set(SSL_URI https://www.openssl.org/source/openssl-${SSL_VERSION}.tar.gz) +set(SSL_HASH ebbfc844a8c8cc0ea5dc10b86c9ce97f401837f3fa08c17b2cdadc118253cf99) + +set(SQLITE_VERSION 3.24.0) +set(SQLITE_URI https://www.sqlite.org/2018/sqlite-src-3240000.zip) +set(SQLITE_HASH fb558c49ee21a837713c4f1e7e413309aabdd9c7) diff --git a/build_files/build_environment/cmake/vpx.cmake b/build_files/build_environment/cmake/vpx.cmake index 9d155be1c6cd..8989262135ba 100644 --- a/build_files/build_environment/cmake/vpx.cmake +++ b/build_files/build_environment/cmake/vpx.cmake @@ -18,9 +18,9 @@ if(WIN32) if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") - set(VPX_EXTRA_FLAGS --target=x86_64-win64-gcc) + set(VPX_EXTRA_FLAGS --target=x86_64-win64-gcc --disable-multithread) else() - set(VPX_EXTRA_FLAGS --target=x86-win32-gcc) + set(VPX_EXTRA_FLAGS --target=x86-win32-gcc --disable-multithread) endif() else() if(APPLE) diff --git a/build_files/build_environment/cmake/webp.cmake b/build_files/build_environment/cmake/webp.cmake index 0504988a088d..92cd41b96ffe 100644 --- a/build_files/build_environment/cmake/webp.cmake +++ b/build_files/build_environment/cmake/webp.cmake @@ -37,14 +37,5 @@ ExternalProject_Add(external_webp URL_HASH MD5=${WEBP_HASH} PREFIX ${BUILD_DIR}/webp CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/webp -Wno-dev ${DEFAULT_CMAKE_FLAGS} ${WEBP_EXTRA_ARGS} - INSTALL_COMMAND COMMAND ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp-build/${WEBP_BUILD_DIR}${LIBPREFIX}webp${LIBEXT} ${LIBDIR}/webp/lib/${LIBPREFIX}webp${LIBEXT} && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/decode.h ${LIBDIR}/webp/include/webp/decode.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/encode.h ${LIBDIR}/webp/include/webp/encode.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/demux.h ${LIBDIR}/webp/include/webp/demux.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/extras.h ${LIBDIR}/webp/include/webp/extras.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/format_constants.h ${LIBDIR}/webp/include/webp/format_constants.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/mux.h ${LIBDIR}/webp/include/webp/mux.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/mux_types.h ${LIBDIR}/webp/include/webp/mux_types.h && - ${CMAKE_COMMAND} -E copy ${BUILD_DIR}/webp/src/external_webp/src/webp/types.h ${LIBDIR}/webp/include/webp/types.h INSTALL_DIR ${LIBDIR}/webp ) diff --git a/build_files/build_environment/cmake/x264.cmake b/build_files/build_environment/cmake/x264.cmake index f42015e43952..7d7b0758aaf7 100644 --- a/build_files/build_environment/cmake/x264.cmake +++ b/build_files/build_environment/cmake/x264.cmake @@ -18,13 +18,18 @@ if(WIN32) set(X264_EXTRA_ARGS --enable-win32thread --cross-prefix=${MINGW_HOST}- --host=${MINGW_HOST}) + set(X264_PATCH_CMD ${PATCH_CMD} --verbose -p 1 -N -d ${BUILD_DIR}/x264/src/external_x264 < ${PATCH_DIR}/x264.diff) +else() + set(X264_PATCH_CMD echo .) endif() + ExternalProject_Add(external_x264 URL ${X264_URI} DOWNLOAD_DIR ${DOWNLOAD_DIR} URL_HASH SHA256=${X264_HASH} PREFIX ${BUILD_DIR}/x264 + PATCH_COMMAND ${X264_PATCH_CMD} CONFIGURE_COMMAND ${CONFIGURE_ENV} && cd ${BUILD_DIR}/x264/src/external_x264/ && ${CONFIGURE_COMMAND} --prefix=${LIBDIR}/x264 --enable-static --enable-pic diff --git a/build_files/build_environment/cmake/yamlcpp.cmake b/build_files/build_environment/cmake/yamlcpp.cmake new file mode 100644 index 000000000000..617158ff40a7 --- /dev/null +++ b/build_files/build_environment/cmake/yamlcpp.cmake @@ -0,0 +1,34 @@ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +set(YAMLCPP_EXTRA_ARGS + -DBUILD_GMOCK=OFF + -DYAML_CPP_BUILD_TESTS=OFF + -DYAML_CPP_BUILD_TOOLS=OFF + -DYAML_CPP_BUILD_CONTRIB=OFF + -DMSVC_SHARED_RT=OFF +) + +ExternalProject_Add(external_yamlcpp + URL ${YAMLCPP_URI} + DOWNLOAD_DIR ${DOWNLOAD_DIR} + URL_HASH MD5=${YAMLCPP_HASH} + PREFIX ${BUILD_DIR}/yamlcpp + CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${LIBDIR}/yamlcpp ${DEFAULT_CMAKE_FLAGS} ${YAMLCPP_EXTRA_ARGS} + INSTALL_DIR ${LIBDIR}/yamlcpp +) diff --git a/build_files/build_environment/cmake/zlib.cmake b/build_files/build_environment/cmake/zlib.cmake index 3307cb1f167d..7bf1c45e359f 100644 --- a/build_files/build_environment/cmake/zlib.cmake +++ b/build_files/build_environment/cmake/zlib.cmake @@ -25,9 +25,31 @@ ExternalProject_Add(external_zlib INSTALL_DIR ${LIBDIR}/zlib ) -if(BUILD_MODE STREQUAL Debug) - ExternalProject_Add_Step(external_zlib after_install - COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/zlibstaticd${LIBEXT} ${LIBDIR}/zlib/lib/${ZLIB_LIBRARY} +if (WIN32) + if(BUILD_MODE STREQUAL Release) + ExternalProject_Add_Step(external_zlib after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/zlibstatic${LIBEXT} ${HARVEST_TARGET}/zlib/lib/libz_st${LIBEXT} + COMMAND ${CMAKE_COMMAND} -E copy_directory ${LIBDIR}/zlib/include/ ${HARVEST_TARGET}/zlib/include/ + DEPENDEES install + ) + endif() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_zlib after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/zlibstaticd${LIBEXT} ${HARVEST_TARGET}/zlib/lib/libz_st_d${LIBEXT} DEPENDEES install - ) + ) + endif() +else() + if(BUILD_MODE STREQUAL Debug) + ExternalProject_Add_Step(external_zlib after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/zlibstaticd${LIBEXT} ${LIBDIR}/zlib/lib/${ZLIB_LIBRARY} + DEPENDEES install + ) + endif() + if (UNIX AND NOT APPLE) + ExternalProject_Add_Step(external_zlib after_install + COMMAND ${CMAKE_COMMAND} -E copy ${LIBDIR}/zlib/lib/libz.a ${LIBDIR}/zlib/lib/libz_pic.a + DEPENDEES install + ) + endif() endif() diff --git a/build_files/build_environment/cmake/zlib_mingw.cmake b/build_files/build_environment/cmake/zlib_mingw.cmake index 13345f29ffae..56578857a47a 100644 --- a/build_files/build_environment/cmake/zlib_mingw.cmake +++ b/build_files/build_environment/cmake/zlib_mingw.cmake @@ -37,4 +37,3 @@ endif() if(MSVC) set_target_properties(external_zlib_mingw PROPERTIES FOLDER Mingw) endif() - diff --git a/build_files/build_environment/install_deps.sh b/build_files/build_environment/install_deps.sh index 6cd725494b3f..8d277ac787e5 100755 --- a/build_files/build_environment/install_deps.sh +++ b/build_files/build_environment/install_deps.sh @@ -290,7 +290,7 @@ SUDO="sudo" NO_BUILD=false NO_CONFIRM=false -USE_CXX11=false +USE_CXX11=true PYTHON_VERSION="3.6.2" PYTHON_VERSION_MIN="3.6" @@ -501,9 +501,6 @@ while true; do --no-confirm) NO_CONFIRM=true; shift; continue ;; - --use-cxx11) - USE_CXX11=true; shift; continue - ;; --with-all) WITH_ALL=true; shift; continue ;; @@ -802,20 +799,10 @@ OPENCOLLADA_REPO_BRANCH="master" FFMPEG_SOURCE=( "http://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.bz2" ) +# C++11 is required now CXXFLAGS_BACK=$CXXFLAGS -if [ "$USE_CXX11" = true ]; then - WARNING "You are trying to use c++11, this *should* go smoothely with any very recent distribution -However, if you are experiencing linking errors (also when building Blender itself), please try the following: - * Re-run this script with '--build-all --force-all' options. - * Ensure your gcc version is at the very least 4.8, if possible you should really rather use gcc-5.1 or above. - -Please note that until the transition to C++11-built libraries if completed in your distribution, situation will -remain fuzzy and incompatibilities may happen..." - PRINT "" - PRINT "" - CXXFLAGS="$CXXFLAGS -std=c++11" - export CXXFLAGS -fi +CXXFLAGS="$CXXFLAGS -std=c++11" +export CXXFLAGS #### Show Dependencies #### @@ -1690,9 +1677,7 @@ compile_OIIO() { # fi cmake_d="$cmake_d -D USE_OCIO=OFF" - if [ "$USE_CXX11" = true ]; then - cmake_d="$cmake_d -D OIIO_BUILD_CPP11=ON" - fi + cmake_d="$cmake_d -D OIIO_BUILD_CPP11=ON" if file /bin/cp | grep -q '32-bit'; then cflags="-fPIC -m32 -march=i686" @@ -1905,9 +1890,7 @@ compile_OSL() { cmake_d="$cmake_d -D OSL_BUILD_PLUGINS=OFF" cmake_d="$cmake_d -D OSL_BUILD_TESTS=OFF" cmake_d="$cmake_d -D USE_SIMD=sse2" - if [ "$USE_CXX11" = true ]; then - cmake_d="$cmake_d -D OSL_BUILD_CPP11=1" - fi + cmake_d="$cmake_d -D OSL_BUILD_CPP11=1" #~ cmake_d="$cmake_d -D ILMBASE_VERSION=$ILMBASE_VERSION" @@ -2293,12 +2276,6 @@ compile_ALEMBIC() { cmake_d="-D CMAKE_INSTALL_PREFIX=$_inst" - # Without Boost or TR1, Alembic requires C++11. - if [ "$USE_CXX11" != true ]; then - cmake_d="$cmake_d -D ALEMBIC_LIB_USES_BOOST=ON" - cmake_d="$cmake_d -D ALEMBIC_LIB_USES_TR1=OFF" - fi - if [ -d $INST/boost ]; then if [ -d $INST/boost ]; then cmake_d="$cmake_d -D BOOST_ROOT=$INST/boost" @@ -4235,12 +4212,6 @@ print_info() { _buildargs="$_buildargs -U *OPENCOLORIO* -U *OPENEXR* -U *OPENIMAGEIO* -U *LLVM* -U *CYCLES*" _buildargs="$_buildargs -U *OPENSUBDIV* -U *OPENVDB* -U *COLLADA* -U *FFMPEG* -U *ALEMBIC*" - if [ "$USE_CXX11" = true ]; then - _1="-D WITH_CXX11=ON" - PRINT " $_1" - _buildargs="$_buildargs $_1" - fi - _1="-D WITH_CODEC_SNDFILE=ON" PRINT " $_1" _buildargs="$_buildargs $_1" diff --git a/build_files/build_environment/patches/alembic.diff b/build_files/build_environment/patches/alembic.diff deleted file mode 100644 index f869858efb20..000000000000 --- a/build_files/build_environment/patches/alembic.diff +++ /dev/null @@ -1,35 +0,0 @@ -diff --git a/CMakeLists.txt b/CMakeLists.txt -index 3e09c57..26565ae 100644 ---- a/CMakeLists.txt -+++ b/CMakeLists.txt -@@ -116,7 +116,7 @@ IF (NOT ${ALEMBIC_LIB_USES_TR1} AND NOT ${ALEMBIC_LIB_USES_BOOST}) - INCLUDE(CheckCXXCompilerFlag) - CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) - CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) -- IF (COMPILER_SUPPORTS_CXX1X) -+ IF (COMPILER_SUPPORTS_CXX11) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - ELSEIF (COMPILER_SUPPORTS_CXX0X) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") ---- a/lib/Alembic/AbcCoreOgawa/StreamManager.cpp -+++ b/lib/Alembic/AbcCoreOgawa/StreamManager.cpp -@@ -47,7 +47,18 @@ - #define COMPARE_EXCHANGE( V, COMP, EXCH ) V.compare_exchange_weak( COMP, EXCH, std::memory_order_seq_cst, std::memory_order_seq_cst ) - // Windows - #elif defined( _MSC_VER ) --#define COMPARE_EXCHANGE( V, COMP, EXCH ) InterlockedCompareExhange64( &V, EXCH, COMP ) == COMP -+#define COMPARE_EXCHANGE( V, COMP, EXCH ) InterlockedCompareExchange64( &V, EXCH, COMP ) == COMP -+int ffsll(long long value) -+{ -+ if (!value) -+ return 0; -+ -+ for (int bit = 0; bit < 63; bit++) -+ { -+ if (value & (1 << bit)) -+ return bit + 1; -+ } -+} - // gcc 4.8 and above not using C++11 - #elif defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 - #define COMPARE_EXCHANGE( V, COMP, EXCH ) __atomic_compare_exchange_n( &V, &COMP, EXCH, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) diff --git a/build_files/build_environment/patches/blosc.diff b/build_files/build_environment/patches/blosc.diff index 3bd6ef281446..2c473d3b6323 100644 --- a/build_files/build_environment/patches/blosc.diff +++ b/build_files/build_environment/patches/blosc.diff @@ -10,24 +10,22 @@ diff -Naur src/blosc/CMakeLists.txt external_blosc/blosc/CMakeLists.txt endif(NOT Threads_FOUND) else(WIN32) find_package(Threads REQUIRED) -diff -Naur src/blosc/blosc.c external_blosc/blosc/blosc.c ---- src/blosc/blosc.c 2016-02-03 10:26:28 -0700 -+++ external_blosc/blosc/blosc.c 2017-03-03 09:01:50 -0700 -@@ -49,12 +49,12 @@ +diff -Naur external_blosc.orig/blosc/blosc.c external_blosc/blosc/blosc.c +--- external_blosc.orig/blosc/blosc.c 2018-07-30 04:56:38 -0600 ++++ external_blosc/blosc/blosc.c 2018-08-11 15:27:26 -0600 +@@ -56,14 +56,7 @@ #include #endif /* _WIN32 */ - --#if defined(_WIN32) && !defined(__GNUC__) + +-/* Include the win32/pthread.h library for all the Windows builds. See #224. */ +-#if defined(_WIN32) - #include "win32/pthread.h" - #include "win32/pthread.c" -#else -+//#if defined(_WIN32) && !defined(__GNUC__) -+// #include "win32/pthread.h" -+ //#include "win32/pthread.c" -+//#else - #include +- #include -#endif -+//#endif - - /* If C11 is supported, use it's built-in aligned allocation. */ - #if __STDC_VERSION__ >= 201112L +- ++#include + + /* Some useful units */ + #define KB 1024 diff --git a/build_files/build_environment/patches/boost.diff b/build_files/build_environment/patches/boost.diff deleted file mode 100644 index 41b40d7a9150..000000000000 --- a/build_files/build_environment/patches/boost.diff +++ /dev/null @@ -1,37 +0,0 @@ ---- a/boost/config/compiler/visualc.hpp 2015-12-08 11:55:19 -0700 -+++ b/boost/config/compiler/visualc.hpp 2018-03-17 10:29:52 -0600 -@@ -287,12 +287,3 @@ - # define BOOST_COMPILER "Microsoft Visual C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) - #endif - --// --// last known and checked version is 19.00.23026 (VC++ 2015 RTM): --#if (_MSC_VER > 1900) --# if defined(BOOST_ASSERT_CONFIG) --# error "Unknown compiler version - please run the configure tests and report the results" --# else --# pragma message("Unknown compiler version - please run the configure tests and report the results") --# endif --#endif ---- a/boost/type_traits/has_nothrow_assign.hpp 2015-12-13 05:49:42 -0700 -+++ b/boost/type_traits/has_nothrow_assign.hpp 2018-05-27 11:11:02 -0600 -@@ -24,7 +24,7 @@ - #include - #endif - #endif --#if defined(__GNUC__) || defined(__SUNPRO_CC) -+#if defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__clang__) - #include - #include - #include ---- a/boost/type_traits/has_nothrow_constructor.hpp 2015-12-13 05:49:42 -0700 -+++ b/boost/type_traits/has_nothrow_constructor.hpp 2018-05-27 11:11:02 -0600 -@@ -17,7 +17,7 @@ - #if defined(BOOST_MSVC) || defined(BOOST_INTEL) - #include - #endif --#if defined(__GNUC__ ) || defined(__SUNPRO_CC) -+#if defined(__GNUC__ ) || defined(__SUNPRO_CC) || defined(__clang__) - #include - #endif - diff --git a/build_files/build_environment/patches/clang.diff b/build_files/build_environment/patches/clang.diff deleted file mode 100644 index 724e92f81634..000000000000 --- a/build_files/build_environment/patches/clang.diff +++ /dev/null @@ -1,127 +0,0 @@ ---- cfe/trunk/lib/Serialization/ASTWriter.cpp -+++ cfe/trunk/lib/Serialization/ASTWriter.cpp -@@ -56,14 +56,14 @@ - using namespace clang::serialization; - - template --static StringRef bytes(const std::vector &v) { -+static StringRef data(const std::vector &v) { - if (v.empty()) return StringRef(); - return StringRef(reinterpret_cast(&v[0]), - sizeof(T) * v.size()); - } - - template --static StringRef bytes(const SmallVectorImpl &v) { -+static StringRef data(const SmallVectorImpl &v) { - return StringRef(reinterpret_cast(v.data()), - sizeof(T) * v.size()); - } -@@ -1385,7 +1385,7 @@ - Record.push_back(INPUT_FILE_OFFSETS); - Record.push_back(InputFileOffsets.size()); - Record.push_back(UserFilesNum); -- Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets)); -+ Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets)); - } - - //===----------------------------------------------------------------------===// -@@ -1771,7 +1771,7 @@ - Record.push_back(SOURCE_LOCATION_OFFSETS); - Record.push_back(SLocEntryOffsets.size()); - Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy -- Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, bytes(SLocEntryOffsets)); -+ Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); - - // Write the source location entry preloads array, telling the AST - // reader which source locations entries it should load eagerly. -@@ -2087,7 +2087,7 @@ - Record.push_back(MacroOffsets.size()); - Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS); - Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, -- bytes(MacroOffsets)); -+ data(MacroOffsets)); - } - - void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { -@@ -2185,7 +2185,7 @@ - Record.push_back(PPD_ENTITIES_OFFSETS); - Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); - Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, -- bytes(PreprocessedEntityOffsets)); -+ data(PreprocessedEntityOffsets)); - } - } - -@@ -2548,7 +2548,7 @@ - Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); - Record.push_back(CXXBaseSpecifiersOffsets.size()); - Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, -- bytes(CXXBaseSpecifiersOffsets)); -+ data(CXXBaseSpecifiersOffsets)); - } - - //===----------------------------------------------------------------------===// -@@ -2623,7 +2623,7 @@ - Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); - - ++NumLexicalDeclContexts; -- Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, bytes(Decls)); -+ Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); - return Offset; - } - -@@ -2642,7 +2642,7 @@ - Record.push_back(TYPE_OFFSET); - Record.push_back(TypeOffsets.size()); - Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); -- Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets)); -+ Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); - - // Write the declaration offsets array - Abbrev = new BitCodeAbbrev(); -@@ -2655,7 +2655,7 @@ - Record.push_back(DECL_OFFSET); - Record.push_back(DeclOffsets.size()); - Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); -- Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets)); -+ Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); - } - - void ASTWriter::WriteFileDeclIDsMap() { -@@ -2680,7 +2680,7 @@ - unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); - Record.push_back(FILE_SORTED_DECLS); - Record.push_back(FileSortedIDs.size()); -- Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileSortedIDs)); -+ Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); - } - - void ASTWriter::WriteComments() { -@@ -2893,7 +2893,7 @@ - Record.push_back(SelectorOffsets.size()); - Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); - Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, -- bytes(SelectorOffsets)); -+ data(SelectorOffsets)); - } - } - -@@ -3253,7 +3253,7 @@ - Record.push_back(IdentifierOffsets.size()); - Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); - Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, -- bytes(IdentifierOffsets)); -+ data(IdentifierOffsets)); - } - - //===----------------------------------------------------------------------===// -@@ -4046,7 +4046,7 @@ - Record.clear(); - Record.push_back(TU_UPDATE_LEXICAL); - Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, -- bytes(NewGlobalDecls)); -+ data(NewGlobalDecls)); - - // And a visible updates block for the translation unit. - Abv = new llvm::BitCodeAbbrev(); diff --git a/build_files/build_environment/patches/cmake/modules/FindIlmBase.cmake b/build_files/build_environment/patches/cmake/modules/FindIlmBase.cmake index de4c0aba48c8..10075d714844 100644 --- a/build_files/build_environment/patches/cmake/modules/FindIlmBase.cmake +++ b/build_files/build_environment/patches/cmake/modules/FindIlmBase.cmake @@ -75,7 +75,7 @@ macro(PREFIX_FIND_LIB prefix libname libpath_var liblist_var cachelist_var) # Handle new library names for OpenEXR 2.1 build via cmake string(REPLACE "." "_" _ILMBASE_VERSION ${ILMBASE_VERSION}) string(SUBSTRING ${_ILMBASE_VERSION} 0 3 _ILMBASE_VERSION ) - + find_library(${tmp_prefix}_LIBRARY_RELEASE NAMES ${libname} ${libname}-${_ILMBASE_VERSION} HINTS ${${libpath_var}} @@ -177,7 +177,7 @@ if(ILMBASE_INCLUDE_DIR) "\\1" XYZ ${ILMBASE_BUILD_SPECIFICATION}) set("ILMBASE_VERSION" ${XYZ} CACHE STRING "Version of ILMBase lib") else() - # Old versions (before 2.0?) do not have any version string, just assuming 2.0 should be fine though. + # Old versions (before 2.0?) do not have any version string, just assuming 2.0 should be fine though. message(WARNING "Could not determine ILMBase library version, assuming 2.0.") set("ILMBASE_VERSION" "2.0" CACHE STRING "Version of ILMBase lib") endif() diff --git a/build_files/build_environment/patches/cmake/modules/FindOpenEXR.cmake b/build_files/build_environment/patches/cmake/modules/FindOpenEXR.cmake index 1eb4ea3f5e7b..96a2ca94babc 100644 --- a/build_files/build_environment/patches/cmake/modules/FindOpenEXR.cmake +++ b/build_files/build_environment/patches/cmake/modules/FindOpenEXR.cmake @@ -175,7 +175,7 @@ if(OPENEXR_INCLUDE_DIR) "\\1" XYZ ${OPENEXR_BUILD_SPECIFICATION}) set("OPENEXR_VERSION" ${XYZ} CACHE STRING "Version of OpenEXR lib") else() - # Old versions (before 2.0?) do not have any version string, just assuming 2.0 should be fine though. + # Old versions (before 2.0?) do not have any version string, just assuming 2.0 should be fine though. message(WARNING "Could not determine ILMBase library version, assuming 2.0.") set("OPENEXR_VERSION" "2.0" CACHE STRING "Version of OpenEXR lib") endif() diff --git a/build_files/build_environment/patches/cmake/modules/SelectLibraryConfigurations.cmake b/build_files/build_environment/patches/cmake/modules/SelectLibraryConfigurations.cmake index 47234ced74a4..ba8c4fce285f 100644 --- a/build_files/build_environment/patches/cmake/modules/SelectLibraryConfigurations.cmake +++ b/build_files/build_environment/patches/cmake/modules/SelectLibraryConfigurations.cmake @@ -6,7 +6,7 @@ # basename_LIBRARY_RELEASE is defined, basename_LIBRARY, basename_LIBRARY_DEBUG, # and basename_LIBRARY_RELEASE will be set to the release value. If only # basename_LIBRARY_DEBUG is defined, then basename_LIBRARY, -# basename_LIBRARY_DEBUG and basename_LIBRARY_RELEASE will take the debug value. +# basename_LIBRARY_DEBUG and basename_LIBRARY_RELEASE will take the debug value. # # If the generator supports configuration types, then basename_LIBRARY and # basename_LIBRARIES will be set with debug and optimized flags specifying the @@ -53,10 +53,10 @@ macro( select_library_configurations basename ) # if the generator supports configuration types or CMAKE_BUILD_TYPE # is set, then set optimized and debug options. if( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) - set( ${basename}_LIBRARY + set( ${basename}_LIBRARY optimized ${${basename}_LIBRARY_RELEASE} debug ${${basename}_LIBRARY_DEBUG} ) - set( ${basename}_LIBRARIES + set( ${basename}_LIBRARIES optimized ${${basename}_LIBRARY_RELEASE} debug ${${basename}_LIBRARY_DEBUG} ) else( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) @@ -67,16 +67,15 @@ macro( select_library_configurations basename ) endif( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE ) endif( ${basename}_LIBRARY_DEBUG AND ${basename}_LIBRARY_RELEASE ) - set( ${basename}_LIBRARY ${${basename}_LIBRARY} CACHE FILEPATH + set( ${basename}_LIBRARY ${${basename}_LIBRARY} CACHE FILEPATH "The ${basename} library" ) if( ${basename}_LIBRARY ) set( ${basename}_FOUND TRUE ) endif( ${basename}_LIBRARY ) - mark_as_advanced( ${basename}_LIBRARY + mark_as_advanced( ${basename}_LIBRARY ${basename}_LIBRARY_RELEASE ${basename}_LIBRARY_DEBUG ) endmacro( select_library_configurations ) - diff --git a/build_files/build_environment/patches/cmakelists_lcms.txt b/build_files/build_environment/patches/cmakelists_lcms.txt new file mode 100644 index 000000000000..cd7b45621eca --- /dev/null +++ b/build_files/build_environment/patches/cmakelists_lcms.txt @@ -0,0 +1,51 @@ +project(lcms2) + +cmake_minimum_required(VERSION 2.8) + +include_directories(include) + +set(HEADERS + include/lcms2.h + include/lcms2_plugin.h +) +set(SOURCES + src/cmscam02.c + src/cmscgats.c + src/cmscnvrt.c + src/cmserr.c + src/cmsgamma.c + src/cmsgmt.c + src/cmsintrp.c + src/cmsio0.c + src/cmsio1.c + src/cmslut.c + src/cmsmd5.c + src/cmsmtrx.c + src/cmsnamed.c + src/cmsopt.c + src/cmspack.c + src/cmspcs.c + src/cmsplugin.c + src/cmsps2.c + src/cmssamp.c + src/cmssm.c + src/cmstypes.c + src/cmsvirt.c + src/cmswtpnt.c + src/cmsxform.c + src/lcms2_internal.h +) + +add_library(${PROJECT_NAME} STATIC ${HEADERS} ${SOURCES}) + +set_target_properties(${PROJECT_NAME} PROPERTIES + LIBRARY_OUTPUT_NAME "${PROJECT_NAME}" + PUBLIC_HEADER "${HEADERS}" +) + +install(TARGETS ${PROJECT_NAME} + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib + PUBLIC_HEADER DESTINATION include +) diff --git a/build_files/build_environment/patches/cmakelists_openvdb.txt b/build_files/build_environment/patches/cmakelists_openvdb.txt deleted file mode 100644 index 43161b8acff8..000000000000 --- a/build_files/build_environment/patches/cmakelists_openvdb.txt +++ /dev/null @@ -1,398 +0,0 @@ -# -------------------------------------------------------------------------------- - -cmake_minimum_required(VERSION 2.8) - -# -------------------------------------------------------------------------------- - -project(OpenVDB) - -# -------------------------------------------------------------------------------- - -set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") - -# -------------------------------------------------------------------------------- - -set(CMAKE_BUILD_TYPE_INIT "Release") - -# -------------------------------------------------------------------------------- -# Options - -option(WITH_BLOSC "Enable Blosc support for compression" OFF) -option(WITH_LOGC4PLUS "Enable logging" OFF) -option(WITH_OPENVDB_2_ABI "Enable building the library to be compability with the OpenVDB 2 ABI" OFF) -option(WITH_PRINTER "Enable building the OpenVDB print executable" OFF) -option(WITH_PYTHON "Enable building the OpenVDB python API" OFF) -option(WITH_RENDERER "Enable building the OpenVDB render executable" OFF) -option(WITH_UNITTEST "Enable building the unit tests" OFF) -option(WITH_VIEWER "Enable building the OpenVDB viewer executable" OFF) - -# -------------------------------------------------------------------------------- -# Find packages -#set(BOOST_LIBRARIES boost_iostreams boost_system boost_thread) - -find_package(IlmBase) -find_package(OpenEXR) -find_package(TBB) -find_package(Boost) - -if(WITH_BLOSC) - find_package(Blosc) - - if(NOT BLOSC_FOUND) - set(WITH_BLOSC OFF) - endif() -endif() - -# todo -if(WITH_VIEWER) - set(GLFW_INCLUDE_DIRS ${GLFW_INCLUDE_PATH}) - set(GLFW_LIBRARY_DIRS ${GLFW_LIBRARY_PATH}) -endif() - -if(WITH_LOGC4PLUS) - find_package(LogC4Plus) - - if(NOT LOGC4PLUS_FOUND) - set(WITH_LOGC4PLUS OFF) - endif() -endif() - -# todo -if(WITH_PYTHON) - set(PYTHON_INCLUDE_DIRS ${PYTHON_INCLUDE_PATH}) - set(PYTHON_LIBRARY_DIRS ${PYTHON_LIBRARY_PATH}) -endif() - -if(WITH_UNITTEST) - find_package(CppUnit) - - if(NOT CPPUNIT_FOUND) - set(WITH_UNITTEST OFF) - endif() -endif() - -# -------------------------------------------------------------------------------- - -message (STATUS "BOOST_ROOT ${BOOST_ROOT}") -message (STATUS "Boost found ${Boost_FOUND} ") -message (STATUS "Boost version ${Boost_VERSION}") -message (STATUS "Boost include dirs ${Boost_INCLUDE_DIRS}") -message (STATUS "Boost library dirs ${Boost_LIBRARY_DIRS}") -message (STATUS "Boost libraries ${Boost_LIBRARIES}") - -message (STATUS "ILMBase found ${ILMBASE_FOUND} ") -message (STATUS "ILMBase include dir ${ILMBASE_INCLUDE_DIR}") -message (STATUS "ILMBase libraries ${ILMBASE_LIBRARIES}") - -message (STATUS "TBB found ${TBB_FOUND} ") -message (STATUS "TBB include dir ${TBB_INCLUDE_DIR}") -message (STATUS "TBB libraries ${TBB_LIBRARIES}") - -if(MSVC) - set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj" ) - set ( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj" ) -endif() - -set(OPENVDB_LIBRARIES ${BLOSC_LIBRARIES} ${BOOST_LIBRARIES} ${OPENEXR_LIBRARIES} ${ILMBASE_LIBRARIES} ${TBB_LIBRARIES} ${ZLIB_LIBRARY} ) - -include_directories(. ${CMAKE_CURRENT_SOURCE_DIR}/../ ${Boost_INCLUDE_DIRS} ${ILMBASE_INCLUDE_DIR} ${OPENEXR_INCLUDE_DIR} ${TBB_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR}) -link_directories(${Boost_LIBRARY_DIRS} ${OPENEXR_LIBRARY_DIRS} ${TBB_INCLUDE_DIRS}) -add_definitions(-DNOMINMAX -D__TBB_NO_IMPLICIT_LINKAGE -DOPENVDB_STATICLIB -DOPENVDB_OPENEXR_STATICLIB) - -if(WITH_BLOSC) - add_definitions(-DOPENVDB_USE_BLOSC) - include_directories(${BLOSC_INCLUDE_DIRS}) - link_directories(${BLOSC_LIBRARY_DIRS}) -endif() - -if(WITH_LOGC4PLUS) - add_definitions(-DOPENVDB_USE_LOG4CPLUS) - include_directories(${LOG4CPLUS_INCLUDE_DIRS}) - link_directories(${LOG4CPLUS_LIBRARY_DIRS}) -endif() - -if(WITH_OPENVDB_2_ABI) - add_definitions(-DOPENVDB_2_ABI_COMPATIBLE) -endif() - -# todo -if(WITH_OPENVDB_USE_GLFW_3) - add_definitions(-DOPENVDB_USE_GLFW_3) -endif() - -if(WITH_UNITTEST) - include_directories(${CPPUNIT_INCLUDE_DIRS}) - link_directories(${CPPUNIT_LIBRARY_DIRS}) -endif() - -# -------------------------------------------------------------------------------- - -set(SRC_FILES - openvdb/openvdb.cc - openvdb/io/Compression.cc - openvdb/io/File.cc - openvdb/io/Queue.cc - openvdb/io/Stream.cc - openvdb/io/TempFile.cc - openvdb/io/GridDescriptor.cc - openvdb/io/Archive.cc - openvdb/metadata/MetaMap.cc - openvdb/metadata/Metadata.cc - openvdb/math/Maps.cc - openvdb/math/Transform.cc - openvdb/math/QuantizedUnitVec.cc - openvdb/math/Proximity.cc - openvdb/Grid.cc - openvdb/util/Formats.cc - openvdb/util/Util.cc -) - -set(HEADER_FILES - openvdb/openvdb.h - openvdb/version.h - openvdb/PlatformConfig.h - openvdb/Metadata.h - openvdb/Exceptions.h - openvdb/Grid.h - openvdb/Types.h - openvdb/Platform.h - openvdb/tree/ValueAccessor.h - openvdb/tree/NodeUnion.h - openvdb/tree/Tree.h - openvdb/tree/Iterator.h - openvdb/tree/LeafNodeBool.h - openvdb/tree/TreeIterator.h - openvdb/tree/LeafNode.h - openvdb/tree/NodeManager.h - openvdb/tree/LeafManager.h - openvdb/tree/InternalNode.h - openvdb/tree/RootNode.h - openvdb/tools/PointScatter.h - openvdb/tools/VolumeAdvect.h - openvdb/tools/LevelSetTracker.h - openvdb/tools/Composite.h - openvdb/tools/Morphology.h - openvdb/tools/ValueTransformer.h - openvdb/tools/ChangeBackground.h - openvdb/tools/GridTransformer.h - openvdb/tools/Prune.h - openvdb/tools/LevelSetUtil.h - openvdb/tools/VolumeToSpheres.h - openvdb/tools/LevelSetAdvect.h - openvdb/tools/Statistics.h - openvdb/tools/LevelSetMeasure.h - openvdb/tools/VectorTransformer.h - openvdb/tools/RayIntersector.h - openvdb/tools/PointPartitioner.h - openvdb/tools/Interpolation.h - openvdb/tools/VelocityFields.h - openvdb/tools/PointIndexGrid.h - openvdb/tools/LevelSetRebuild.h - openvdb/tools/Clip.h - openvdb/tools/SignedFloodFill.h - openvdb/tools/MeshToVolume.h - openvdb/tools/Dense.h - openvdb/tools/Filter.h - openvdb/tools/RayTracer.h - openvdb/tools/Diagnostics.h - openvdb/tools/VolumeToMesh.h - openvdb/tools/PoissonSolver.h - openvdb/tools/LevelSetFracture.h - openvdb/tools/GridOperators.h - openvdb/tools/DenseSparseTools.h - openvdb/tools/ParticlesToLevelSet.h - openvdb/tools/LevelSetSphere.h - openvdb/tools/LevelSetMorph.h - openvdb/tools/LevelSetFilter.h - openvdb/tools/PointAdvect.h - openvdb/io/Queue.h - openvdb/io/TempFile.h - openvdb/io/Stream.h - openvdb/io/GridDescriptor.h - openvdb/io/Archive.h - openvdb/io/io.h - openvdb/io/Compression.h - openvdb/io/File.h - openvdb/metadata/StringMetadata.h - openvdb/metadata/MetaMap.h - openvdb/metadata/Metadata.h - openvdb/math/DDA.h - openvdb/math/Vec2.h - openvdb/math/FiniteDifference.h - openvdb/math/Stencils.h - openvdb/math/BBox.h - openvdb/math/Mat3.h - openvdb/math/Mat.h - openvdb/math/Proximity.h - openvdb/math/Ray.h - openvdb/math/ConjGradient.h - openvdb/math/Quat.h - openvdb/math/Vec3.h - openvdb/math/Vec4.h - openvdb/math/QuantizedUnitVec.h - openvdb/math/Coord.h - openvdb/math/Operators.h - openvdb/math/Stats.h - openvdb/math/Math.h - openvdb/math/Tuple.h - openvdb/math/LegacyFrustum.h - openvdb/math/Mat4.h - openvdb/math/Maps.h - openvdb/math/Transform.h - openvdb/util/PagedArray.h - openvdb/util/CpuTimer.h - openvdb/util/Formats.h - openvdb/util/NullInterrupter.h - openvdb/util/Util.h - openvdb/util/Name.h - openvdb/util/MapsUtil.h - openvdb/util/NodeMasks.h - openvdb/util/logging.h -) - -add_library(openvdb STATIC ${SRC_FILES} ${HEADER_FILES}) - -# -------------------------------------------------------------------------------- - -target_link_libraries(openvdb ${OPENVDB_LIBRARIES}) - -set(OPENVDB_VERSION_MAJOR 3) -set(OPENVDB_VERSION_MINOR 1) -set(OPENVDB_VERSION_PATCH 0) -set(OPENVDB_VERSION_STRING ${OPENVDB_VERSION_MAJOR}.${OPENVDB_VERSION_MINOR}.${OPENVDB_VERSION_PATCH}) - -set_target_properties(openvdb PROPERTIES VERSION ${OPENVDB_VERSION_STRING} SOVERSION ${OPENVDB_VERSION_MAJOR}) - -install(TARGETS openvdb DESTINATION lib) - -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION include COMPONENT Development FILES_MATCHING PATTERN "*.h" - PATTERN ".git" EXCLUDE PATTERN "build" EXCLUDE PATTERN "cmake" EXCLUDE) - -# -------------------------------------------------------------------------------- - -if(WITH_PRINTER) - set(PRINT_SRC - openvdb/cmd/openvdb_print/main.cc - ) - - add_executable(vdb_print ${PRINT_SRC}) - target_link_libraries(vdb_print openvdb) - install(TARGETS vdb_print RUNTIME DESTINATION bin) -endif() - -if(WITH_RENDER) - set(RENDER_SRC - openvdb/cmd/openvdb_render/main.cc - ) - - add_executable(vdb_render ${RENDER_SRC}) - target_link_libraries(vdb_render openvdb) - install(TARGETS vdb_render RUNTIME DESTINATION bin) -endif() - -# todo -if(WITH_VIEWER) - set(VIEWER_SRC - openvdb/viewer/Camera.cc - openvdb/viewer/ClipBox.cc - openvdb/viewer/Font.cc - openvdb/viewer/RenderModules.cc - openvdb/viewer/Viewer.cc - - openvdb/viewer/Camera.h - openvdb/viewer/ClipBox.h - openvdb/viewer/Font.h - openvdb/viewer/RenderModules.h - openvdb/viewer/Viewer.h - openvdb/cmd/openvdb_viewer/main.cc - ) - - include_directories(${GLFW_INCLUDE_DIRS}) - link_directories(${GLFW_LIBRARY_DIRS}) - - add_executable(vdb_viewer ${VIEWER_SRC}) - target_link_libraries(vdb_viewer openvdb) - install(TARGETS vdb_viewer RUNTIME DESTINATION bin) -endif() - -# todo -if(WITH_PYTHON) -# add_library(pyopenvdb SHARED ) -endif() - -set(UNITTEST_SRC - openvdb/unittest/main.cc - openvdb/unittest/TestBBox.cc - openvdb/unittest/TestConjGradient.cc - openvdb/unittest/TestCoord.cc - openvdb/unittest/TestCpt.cc - openvdb/unittest/TestCurl.cc - openvdb/unittest/TestDense.cc - openvdb/unittest/TestDenseSparseTools.cc - openvdb/unittest/TestDiagnostics.cc - openvdb/unittest/TestDivergence.cc - openvdb/unittest/TestDoubleMetadata.cc - openvdb/unittest/TestExceptions.cc - openvdb/unittest/TestFile.cc - openvdb/unittest/TestFloatMetadata.cc - openvdb/unittest/TestGradient.cc - openvdb/unittest/TestGrid.cc - openvdb/unittest/TestGridBbox.cc - openvdb/unittest/TestGridDescriptor.cc - openvdb/unittest/TestGridIO.cc - openvdb/unittest/TestGridTransformer.cc - openvdb/unittest/TestInit.cc - openvdb/unittest/TestInt32Metadata.cc - openvdb/unittest/TestInt64Metadata.cc - openvdb/unittest/TestInternalOrigin.cc - openvdb/unittest/TestLaplacian.cc - openvdb/unittest/TestLeaf.cc - openvdb/unittest/TestLeafBool.cc - openvdb/unittest/TestLeafIO.cc - openvdb/unittest/TestLeafOrigin.cc - openvdb/unittest/TestLevelSetRayIntersector.cc - openvdb/unittest/TestLevelSetUtil.cc - openvdb/unittest/TestLinearInterp.cc - openvdb/unittest/TestMaps.cc - openvdb/unittest/TestMat4Metadata.cc - openvdb/unittest/TestMath.cc - openvdb/unittest/TestMeanCurvature.cc - openvdb/unittest/TestMeshToVolume.cc - openvdb/unittest/TestMetadata.cc - openvdb/unittest/TestMetadataIO.cc - openvdb/unittest/TestMetaMap.cc - openvdb/unittest/TestName.cc - openvdb/unittest/TestNodeIterator.cc - openvdb/unittest/TestNodeMask.cc - openvdb/unittest/TestParticlesToLevelSet.cc - openvdb/unittest/TestPointIndexGrid.cc - openvdb/unittest/TestPointPartitioner.cc - openvdb/unittest/TestPoissonSolver.cc - openvdb/unittest/TestPrePostAPI.cc - openvdb/unittest/TestQuadraticInterp.cc - openvdb/unittest/TestQuantizedUnitVec.cc - openvdb/unittest/TestQuat.cc - openvdb/unittest/TestRay.cc - openvdb/unittest/TestStats.cc - openvdb/unittest/TestStream.cc - openvdb/unittest/TestStringMetadata.cc - openvdb/unittest/TestTools.cc - openvdb/unittest/TestTransform.cc - openvdb/unittest/TestTree.cc - openvdb/unittest/TestTreeCombine.cc - openvdb/unittest/TestTreeGetSetValues.cc - openvdb/unittest/TestTreeIterators.cc - openvdb/unittest/TestTreeVisitor.cc - openvdb/unittest/TestUtil.cc - openvdb/unittest/TestValueAccessor.cc - openvdb/unittest/TestVec2Metadata.cc - openvdb/unittest/TestVec3Metadata.cc - openvdb/unittest/TestVolumeRayIntersector.cc - openvdb/unittest/TestVolumeToMesh.cc -) - -# todo -if(WITH_UNITTEST) - add_executable(test ${UNITTEST_SRC} ${HEADER_FILES}) - target_link_libraries(test openvdb ${CPPUNIT_LIBRARIES}) -endif() diff --git a/build_files/build_environment/patches/distutildebugflags.diff b/build_files/build_environment/patches/distutildebugflags.diff deleted file mode 100644 index 3d6b688bc532..000000000000 --- a/build_files/build_environment/patches/distutildebugflags.diff +++ /dev/null @@ -1,11 +0,0 @@ ---- _msvccompiler.py.orig 2017-01-17 00:57:48 -0700 -+++ _msvccompiler.py 2017-05-20 09:47:26 -0600 -@@ -237,7 +237,7 @@ - ldflags.extend(('/nodefaultlib:libucrt.lib', 'ucrt.lib')) - - ldflags_debug = [ -- '/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL' -+ '/nologo', '/INCREMENTAL:NO', '/LTCG' - ] - - self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1'] diff --git a/build_files/build_environment/patches/ffmpeg.diff b/build_files/build_environment/patches/ffmpeg.diff index 75fc6490031e..960728ae980f 100644 --- a/build_files/build_environment/patches/ffmpeg.diff +++ b/build_files/build_environment/patches/ffmpeg.diff @@ -1,32 +1,11 @@ ---- libavutil/common.h 2016-02-14 19:29:42 -0700 -+++ libavutil/common.h 2016-03-30 09:50:29 -0600 -@@ -99,6 +99,11 @@ - #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0) - #define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0])) - -+//msvc helper -+#ifdef _MSC_VER -+#define inline __inline -+#endif -+ - /* misc math functions */ - - #ifdef HAVE_AV_CONFIG_H ---- configure 2016-11-26 03:12:05.000000000 +0100 -+++ configure 2017-04-05 03:24:35.000000000 +0200 -@@ -1899,7 +1899,6 @@ - access - aligned_malloc - arc4random -- clock_gettime - closesocket - CommandLineToArgvW - CoTaskMemFree -@@ -5494,7 +5493,6 @@ - - check_func access - check_func_headers stdlib.h arc4random --check_func_headers time.h clock_gettime || { check_func_headers time.h clock_gettime -lrt && add_extralibs -lrt && LIBRT="-lrt"; } - check_func fcntl - check_func fork - check_func gethrtime +--- a/configure 2018-08-27 13:46:41.071106150 +0200 ++++ b/configure 2018-08-27 13:46:28.162765762 +0200 +@@ -6013,7 +6013,7 @@ + require_pkg_config libopencv opencv opencv/cxcore.h cvCreateImageHeader; } + enabled libopenh264 && require_pkg_config libopenh264 openh264 wels/codec_api.h WelsGetCodecVersion + enabled libopenjpeg && { check_pkg_config libopenjpeg "libopenjp2 >= 2.1.0" openjpeg.h opj_version || +- { require_pkg_config libopenjpeg "libopenjp2 >= 2.1.0" openjpeg.h opj_version -DOPJ_STATIC && add_cppflags -DOPJ_STATIC; } } ++ { require_pkg_config libopenjpeg "libopenjp2 >= 2.1.0" openjpeg.h opj_version "-DOPJ_STATIC $pthreads_extralibs $libm_extralibs" && add_cppflags "-DOPJ_STATIC $pthreads_extralibs $libm_extralibs"; } } + enabled libopenmpt && require_pkg_config libopenmpt "libopenmpt >= 0.2.6557" libopenmpt/libopenmpt.h openmpt_module_create -lstdc++ && append libopenmpt_extralibs "-lstdc++" + enabled libopus && { + enabled libopus_decoder && { diff --git a/build_files/build_environment/patches/freetype.diff b/build_files/build_environment/patches/freetype.diff new file mode 100644 index 000000000000..cf9522347951 --- /dev/null +++ b/build_files/build_environment/patches/freetype.diff @@ -0,0 +1,18 @@ +diff -NaurBb b/CMakeLists.txt a/CMakeLists.txt +--- b/CMakeLists.txt 2018-05-01 12:45:46 -0600 ++++ a/CMakeLists.txt 2018-08-08 13:03:22 -0600 +@@ -229,9 +229,12 @@ + endif () + string(REPLACE "/undef " "#undef " + FTCONFIG_H "${FTCONFIG_H}") +- file(WRITE "${PROJECT_BINARY_DIR}/include/freetype/config/ftconfig.h" +- "${FTCONFIG_H}") ++else() ++ file(READ "${PROJECT_SOURCE_DIR}/include/freetype/config/ftconfig.h" ++ FTCONFIG_H) + endif () ++file(WRITE "${PROJECT_BINARY_DIR}/include/freetype/config/ftconfig.h" ++ "${FTCONFIG_H}") + + + # Create the options file diff --git a/build_files/build_environment/patches/libfaad.diff b/build_files/build_environment/patches/libfaad.diff deleted file mode 100644 index 37605b29cd9e..000000000000 --- a/build_files/build_environment/patches/libfaad.diff +++ /dev/null @@ -1,10 +0,0 @@ ---- frontend/main.c 2008-09-22 11:55:09 -0600 -+++ frontend/main.c 2016-04-06 15:20:36 -0600 -@@ -31,7 +31,6 @@ - #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include --#define off_t __int64 - #else - #include - #endif diff --git a/build_files/build_environment/patches/llvm-alloca-fix.diff b/build_files/build_environment/patches/llvm-alloca-fix.diff deleted file mode 100644 index 5394a472167c..000000000000 --- a/build_files/build_environment/patches/llvm-alloca-fix.diff +++ /dev/null @@ -1,111 +0,0 @@ -Index: lib/Target/X86/X86ISelLowering.cpp -=================================================================== ---- lib/Target/X86/X86ISelLowering.cpp 2014-04-11 23:04:44.000000000 +0200 -+++ lib/Target/X86/X86ISelLowering.cpp (working copy) -@@ -15493,12 +15493,36 @@ - // non-trivial part is impdef of ESP. - - if (Subtarget->isTargetWin64()) { -+ const char *StackProbeSymbol = -+ Subtarget->isTargetCygMing() ? "___chkstk" : "__chkstk"; -+ -+ MachineInstrBuilder MIB; -+ -+ if (getTargetMachine().getCodeModel() == CodeModel::Large) { -+ // For large code model we need to do indirect call to __chkstk. -+ -+ // R11 will be used to contain the address of __chkstk. -+ // R11 is a volotiale register and assumed to be destoyed by the callee, -+ // so there is no need to save and restore it. -+ BuildMI(*BB, MI, DL, TII->get(X86::MOV64ri), X86::R11) -+ .addExternalSymbol(StackProbeSymbol); -+ // Create a call to __chkstk function which address contained in R11. -+ MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64r)) -+ .addReg(X86::R11, RegState::Kill); -+ -+ } else { -+ -+ // For non-large code model we can do direct call to __chkstk. -+ -+ MIB = BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) -+ .addExternalSymbol(StackProbeSymbol); -+ } -+ - if (Subtarget->isTargetCygMing()) { - // ___chkstk(Mingw64): - // Clobbers R10, R11, RAX and EFLAGS. - // Updates RSP. -- BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) -- .addExternalSymbol("___chkstk") -+ MIB - .addReg(X86::RAX, RegState::Implicit) - .addReg(X86::RSP, RegState::Implicit) - .addReg(X86::RAX, RegState::Define | RegState::Implicit) -@@ -15507,8 +15531,7 @@ - } else { - // __chkstk(MSVCRT): does not update stack pointer. - // Clobbers R10, R11 and EFLAGS. -- BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) -- .addExternalSymbol("__chkstk") -+ MIB - .addReg(X86::RAX, RegState::Implicit) - .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); - // RAX has the offset to be subtracted from RSP. -Index: lib/Target/X86/X86FrameLowering.cpp -=================================================================== ---- lib/Target/X86/X86FrameLowering.cpp 2013-10-24 01:37:01.000000000 +0200 -+++ lib/Target/X86/X86FrameLowering.cpp (working copy) -@@ -635,25 +635,49 @@ - .addReg(X86::EAX, RegState::Kill) - .setMIFlag(MachineInstr::FrameSetup); - } -+ -+ MachineInstrBuilder MIB; - - if (Is64Bit) { -+ - // Handle the 64-bit Windows ABI case where we need to call __chkstk. - // Function prologue is responsible for adjusting the stack pointer. - BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX) - .addImm(NumBytes) - .setMIFlag(MachineInstr::FrameSetup); -+ -+ if (TM.getCodeModel() == CodeModel::Large) { -+ // For large code model we need to do indirect call to __chkstk. -+ -+ -+ // R11 will be used to contain the address of __chkstk. -+ // R11 is a volotiale register and assumed to be destoyed by the callee, -+ // so there is no need to save and restore it. -+ BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11) -+ .addExternalSymbol(StackProbeSymbol); -+ // Create a call to __chkstk function which address contained in R11. -+ MIB = BuildMI(MBB, MBBI, DL, TII.get(X86::CALL64r)) -+ .addReg(X86::R11, RegState::Kill); -+ } else { -+ -+ // For non-large code model we can do direct call to __chkstk. -+ -+ MIB = BuildMI(MBB, MBBI, DL, TII.get(X86::W64ALLOCA)) -+ .addExternalSymbol(StackProbeSymbol); -+ } - } else { - // Allocate NumBytes-4 bytes on stack in case of isEAXAlive. - // We'll also use 4 already allocated bytes for EAX. - BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) - .addImm(isEAXAlive ? NumBytes - 4 : NumBytes) - .setMIFlag(MachineInstr::FrameSetup); -+ -+ MIB = BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32)) -+ .addExternalSymbol(StackProbeSymbol); - } - -- BuildMI(MBB, MBBI, DL, -- TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32)) -- .addExternalSymbol(StackProbeSymbol) -- .addReg(StackPtr, RegState::Define | RegState::Implicit) -+ -+ MIB.addReg(StackPtr, RegState::Define | RegState::Implicit) - .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit) - .setMIFlag(MachineInstr::FrameSetup); - diff --git a/build_files/build_environment/patches/numpy.diff b/build_files/build_environment/patches/numpy.diff deleted file mode 100644 index c4c572228389..000000000000 --- a/build_files/build_environment/patches/numpy.diff +++ /dev/null @@ -1,23 +0,0 @@ -diff -Naur numpy-1.11.1/numpy/distutils/ccompiler.py numpy-1.11.1/numpy/distutils/ccompiler.py ---- numpy-1.11.1/numpy/distutils/ccompiler.py 2016-06-25 08:38:34 -0600 -+++ numpy-1.11.1/numpy/distutils/ccompiler.py 2016-08-04 12:33:43 -0600 -@@ -29,6 +29,7 @@ - - # Using customized CCompiler.spawn. - def CCompiler_spawn(self, cmd, display=None): -+ cmd = quote_args(cmd) - """ - Execute a command in a sub-process. - -diff -Naur numpy-1.11.1/numpy/distutils/misc_util.py numpy-1.11.1/numpy/distutils/misc_util.py ---- numpy-1.11.1/numpy/distutils/misc_util.py 2016-06-25 08:38:34 -0600 -+++ numpy-1.11.1/numpy/distutils/misc_util.py 2016-08-04 12:34:56 -0600 -@@ -116,7 +116,7 @@ - args = list(args) - for i in range(len(args)): - a = args[i] -- if ' ' in a and a[0] not in '"\'': -+ if ' ' in a and a[0] not in '"\'' and a[len(a)-1] not in '"\'': - args[i] = '"%s"' % (a) - return args - diff --git a/build_files/build_environment/patches/opencollada.diff b/build_files/build_environment/patches/opencollada.diff index 0c91b4151fe2..48a5008f356a 100644 --- a/build_files/build_environment/patches/opencollada.diff +++ b/build_files/build_environment/patches/opencollada.diff @@ -1,8 +1,8 @@ diff --git a/CMakeLists.txt b/CMakeLists.txt -index 3fc9be5..5112ce6 100644 +index 95abbe2..4f14f30 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt -@@ -254,11 +254,11 @@ +@@ -254,11 +254,11 @@ if(USE_STATIC_MSVC_RUNTIME) endif() #adding PCRE @@ -16,10 +16,10 @@ index 3fc9be5..5112ce6 100644 message("WARNING: Native PCRE not found, taking PCRE from ./Externals") add_definitions(-DPCRE_STATIC) add_subdirectory(${EXTERNAL_LIBRARIES}/pcre) -diff --git a/DAEValidator/library/include/no_warning_begin.orig b/DAEValidator/library/include/no_warning_begin -index 3fc9be5..5112ce6 100644 ---- a/DAEValidator/library/include/no_warning_begin.orig 2017-05-31 16:56:39 -0600 -+++ b/DAEValidator/library/include/no_warning_begin 2017-06-07 10:18:45 -0600 +diff --git a/DAEValidator/library/include/no_warning_begin b/DAEValidator/library/include/no_warning_begin +index 7a69c32..defb315 100644 +--- a/DAEValidator/library/include/no_warning_begin ++++ b/DAEValidator/library/include/no_warning_begin @@ -2,6 +2,9 @@ #if defined(_WIN32) # pragma warning(push) @@ -30,3 +30,16 @@ index 3fc9be5..5112ce6 100644 # if defined(_MSC_VER) && defined(_DEBUG) # pragma warning(disable:4548) # endif +diff --git a/GeneratedSaxParser/src/GeneratedSaxParserUtils.cpp b/GeneratedSaxParser/src/GeneratedSaxParserUtils.cpp +index 1f9a3ee..d151e9a 100644 +--- a/GeneratedSaxParser/src/GeneratedSaxParserUtils.cpp ++++ b/GeneratedSaxParser/src/GeneratedSaxParserUtils.cpp +@@ -1553,7 +1553,7 @@ namespace GeneratedSaxParser + #if defined(COLLADABU_OS_WIN) && !defined(__MINGW32__) + return _isnan( value ) ? true : false; + #else +-#ifdef isnan ++#if defined(isnan) || defined(__APPLE__) + return isnan( value ); + #else + return std::isnan(value); diff --git a/build_files/build_environment/patches/opencolorio.diff b/build_files/build_environment/patches/opencolorio.diff index 4e947d890976..65901f969ca2 100644 --- a/build_files/build_environment/patches/opencolorio.diff +++ b/build_files/build_environment/patches/opencolorio.diff @@ -1,21 +1,13 @@ -diff -ru ./CMakeLists.txt ./CMakeLists.txt ---- ./CMakeLists.txt 2014-09-11 21:08:18.000000000 +0200 -+++ ./CMakeLists.txt 2016-05-15 17:17:01.000000000 +0200 -@@ -186,7 +186,7 @@ - PATCH_COMMAND patch -f -p1 < ${CMAKE_SOURCE_DIR}/ext/tinyxml_${TINYXML_VERSION}.patch - BINARY_DIR ext/build/tinyxml - INSTALL_DIR ext/dist -- CMAKE_ARGS ${TINYXML_CMAKE_ARGS} -+ CMAKE_ARGS ${TINYXML_CMAKE_ARGS} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES} -DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} -DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT} -DCMAKE_C_FLAGS_DEBUG=${CMAKE_C_FLAGS_DEBUG} -DCMAKE_C_FLAGS_RELEASE=${CMAKE_C_FLAGS_RELEASE} -DCMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_CXX_FLAGS_RELEASE=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - ) - if(WIN32) - set(TINYXML_STATIC_LIBRARIES ${PROJECT_BINARY_DIR}/ext/dist/lib/tinyxml.lib) -@@ -254,7 +254,7 @@ - BINARY_DIR ext/build/yaml-cpp - PATCH_COMMAND patch -p1 < ${CMAKE_SOURCE_DIR}/ext/yaml-cpp-${YAML_CPP_VERSION}.patch - INSTALL_DIR ext/dist -- CMAKE_ARGS ${YAML_CPP_CMAKE_ARGS} -+ CMAKE_ARGS ${YAML_CPP_CMAKE_ARGS} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES} -DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} -DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT} -DCMAKE_C_FLAGS_DEBUG=${CMAKE_C_FLAGS_DEBUG} -DCMAKE_C_FLAGS_RELEASE=${CMAKE_C_FLAGS_RELEASE} -DCMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_CXX_FLAGS_RELEASE=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - ) - set(YAML_CPP_INCLUDE_DIRS ${PROJECT_BINARY_DIR}/ext/dist/include) - set(YAML_CPP_LIBRARY_DIRS ${PROJECT_BINARY_DIR}/ext/dist/lib) +diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt +index 1eb691b..cff9bd8 100644 +--- a/src/core/CMakeLists.txt ++++ b/src/core/CMakeLists.txt +@@ -23,8 +23,6 @@ if(WIN32) + if("${CMAKE_BUILD_TYPE}" STREQUAL "Release") + set(EXTERNAL_COMPILE_FLAGS "${EXTERNAL_COMPILE_FLAGS} /WX") + endif() +-else() +- set(EXTERNAL_COMPILE_FLAGS "${EXTERNAL_COMPILE_FLAGS} -Werror") + endif() + + # SHARED diff --git a/build_files/build_environment/patches/opencolorio_win.diff b/build_files/build_environment/patches/opencolorio_win.diff new file mode 100644 index 000000000000..eb65411b61a5 --- /dev/null +++ b/build_files/build_environment/patches/opencolorio_win.diff @@ -0,0 +1,51 @@ +diff -Naur external_opencolorio/CMakeLists.txt external_opencolorio.patched/CMakeLists.txt +--- external_opencolorio/CMakeLists.txt 2018-01-04 18:38:27 -0700 ++++ external_opencolorio.patched/CMakeLists.txt 2018-08-15 11:46:53 -0600 +@@ -251,25 +251,30 @@ + if(USE_EXTERNAL_YAML) + # Set minimum yaml version for non-patched sources. + set(YAML_VERSION_MIN "0.3.0") +- include(FindPkgConfig) +- pkg_check_modules(PC_YAML_CPP REQUIRED QUIET yaml-cpp) +- find_path(YAML_CPP_INCLUDE_DIR yaml-cpp/yaml.h +- HINTS ${PC_YAML_CPP_INCLUDEDIR} ${PC_YAML_CPP_INCLUDE_DIRS} ) +- find_library(YAML_CPP_LIBRARY LIBRARY_NAMES yaml-cpp libyaml-cpp +- HINTS ${PC_YAML_CPP_LIBRARY_DIRS} ) +- set(YAML_CPP_LIBRARIES ${YAML_CPP_LIBRARY}) +- set(YAML_CPP_INCLUDE_DIRS ${YAML_CPP_INCLUDE_DIR}) +- set(YAML_CPP_VERSION ${PC_YAML_CPP_VERSION}) ++ if(NOT WIN32) ++ include(FindPkgConfig) ++ pkg_check_modules(PC_YAML_CPP REQUIRED QUIET yaml-cpp) ++ find_path(YAML_CPP_INCLUDE_DIR yaml-cpp/yaml.h ++ HINTS ${PC_YAML_CPP_INCLUDEDIR} ${PC_YAML_CPP_INCLUDE_DIRS} ) ++ find_library(YAML_CPP_LIBRARY LIBRARY_NAMES yaml-cpp libyaml-cpp ++ HINTS ${PC_YAML_CPP_LIBRARY_DIRS} ) ++ set(YAML_CPP_LIBRARIES ${YAML_CPP_LIBRARY}) ++ set(YAML_CPP_INCLUDE_DIRS ${YAML_CPP_INCLUDE_DIR}) ++ set(YAML_CPP_VERSION ${PC_YAML_CPP_VERSION}) + +- if(YAML_CPP_VERSION VERSION_LESS ${YAML_VERSION_MIN}) +- message(FATAL_ERROR "ERROR: yaml-cpp ${YAML_VERSION_MIN} or greater is required.") +- endif() +- +- find_package_handle_standard_args(yaml-cpp +- REQUIRED_VARS YAML_CPP_LIBRARIES YAML_CPP_INCLUDE_DIRS ) +- set(YAML_CPP_FOUND ${YAML-CPP_FOUND}) +- mark_as_advanced(YAML_CPP_INCLUDE_DIR YAML_CPP_LIBRARY YAML-CPP_FOUND) ++ if(YAML_CPP_VERSION VERSION_LESS ${YAML_VERSION_MIN}) ++ message(FATAL_ERROR "ERROR: yaml-cpp ${YAML_VERSION_MIN} or greater is required.") ++ endif() + ++ find_package_handle_standard_args(yaml-cpp ++ REQUIRED_VARS YAML_CPP_LIBRARIES YAML_CPP_INCLUDE_DIRS ) ++ set(YAML_CPP_FOUND ${YAML-CPP_FOUND}) ++ mark_as_advanced(YAML_CPP_INCLUDE_DIR YAML_CPP_LIBRARY YAML-CPP_FOUND) ++ else() ++ set(EXTERNAL_INCLUDE_DIRS ${EXTERNAL_INCLUDE_DIRS} ${INC_1}) ++ set(EXTERNAL_INCLUDE_DIRS ${EXTERNAL_INCLUDE_DIRS} ${INC_2}) ++ message("INCLUDE DIRS = i:${EXTERNAL_INCLUDE_DIRS} |1:${INC_1} |2:${INC_2}") ++ endif() + if(YAML_CPP_FOUND) + if(YAML_CPP_VERSION VERSION_GREATER "0.5.0") + # Need to also get the boost headers here, as yaml-cpp 0.5.0+ requires them. diff --git a/build_files/build_environment/patches/openexr.diff b/build_files/build_environment/patches/openexr.diff deleted file mode 100644 index ec18751fe74f..000000000000 --- a/build_files/build_environment/patches/openexr.diff +++ /dev/null @@ -1,33 +0,0 @@ ---- IlmImf/CMakeLists.txt 2014-08-10 06:23:56.000000000 +0200 -+++ IlmImf/CMakeLists.txt 2017-01-08 04:06:04.931723800 +0100 -@@ -8,8 +8,8 @@ - - TARGET_LINK_LIBRARIES ( b44ExpLogTable - Half -- Iex${ILMBASE_LIBSUFFIX} - IlmThread${ILMBASE_LIBSUFFIX} -+ Iex${ILMBASE_LIBSUFFIX} - ${PTHREAD_LIB} - ) - -@@ -25,8 +25,8 @@ - - TARGET_LINK_LIBRARIES ( dwaLookups - Half -- Iex${ILMBASE_LIBSUFFIX} - IlmThread${ILMBASE_LIBSUFFIX} -+ Iex${ILMBASE_LIBSUFFIX} - ${PTHREAD_LIB} - ) - -@@ -138,9 +138,9 @@ - - TARGET_LINK_LIBRARIES ( IlmImf - Half -- Iex${ILMBASE_LIBSUFFIX} - Imath${ILMBASE_LIBSUFFIX} - IlmThread${ILMBASE_LIBSUFFIX} -+ Iex${ILMBASE_LIBSUFFIX} - ${PTHREAD_LIB} ${ZLIB_LIBRARIES} - ) - diff --git a/build_files/build_environment/patches/openimageio_static_libs.diff b/build_files/build_environment/patches/openimageio_static_libs.diff new file mode 100644 index 000000000000..6a2e58bd1395 --- /dev/null +++ b/build_files/build_environment/patches/openimageio_static_libs.diff @@ -0,0 +1,22 @@ +diff -Naur external_openimageio.orig/src/cmake/compiler.cmake external_openimageio/src/cmake/compiler.cmake +--- external_openimageio.orig/src/cmake/compiler.cmake 2018-07-31 23:45:19 -0600 ++++ external_openimageio/src/cmake/compiler.cmake 2018-08-16 12:50:12 -0600 +@@ -152,6 +152,7 @@ + add_definitions (-D_CRT_NONSTDC_NO_WARNINGS) + add_definitions (-D_SCL_SECURE_NO_WARNINGS) + add_definitions (-DJAS_WIN_MSVC_BUILD) ++ add_definitions (-DOPJ_STATIC) + endif (MSVC) + + # Use ccache if found +--- external_openimageio.orig/CMakeLists.txt 2018-07-31 23:45:19 -0600 ++++ external_openimageio/CMakeLists.txt 2018-08-17 15:22:56 -0600 +@@ -169,7 +169,7 @@ + add_subdirectory (src/iinfo) + add_subdirectory (src/maketx) + add_subdirectory (src/oiiotool) +- add_subdirectory (src/testtex) ++# add_subdirectory (src/testtex) + add_subdirectory (src/iv) + endif () + diff --git a/build_files/build_environment/patches/openimageio_staticexr.diff b/build_files/build_environment/patches/openimageio_staticexr.diff deleted file mode 100644 index e1f0f4730571..000000000000 --- a/build_files/build_environment/patches/openimageio_staticexr.diff +++ /dev/null @@ -1,11 +0,0 @@ ---- CMakeLists.txt 2016-11-01 01:03:44 -0600 -+++ CMakeLists.txt 2016-12-01 09:20:12 -0700 -@@ -454,7 +454,7 @@ - add_definitions (-D_CRT_NONSTDC_NO_WARNINGS) - add_definitions (-D_SCL_SECURE_NO_WARNINGS) - add_definitions (-DJAS_WIN_MSVC_BUILD) -- add_definitions (-DOPENEXR_DLL) -+ add_definitions (-DOPJ_STATIC) - if (LINKSTATIC) - add_definitions (-DBoost_USE_STATIC_LIBS=1) - else () diff --git a/build_files/build_environment/patches/opensubdiv.diff b/build_files/build_environment/patches/opensubdiv.diff index 9e9cf7ad5541..3fc78bf3c189 100644 --- a/build_files/build_environment/patches/opensubdiv.diff +++ b/build_files/build_environment/patches/opensubdiv.diff @@ -1,16 +1,13 @@ - opensubdiv/osd/d3d11VertexBuffer.cpp | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/opensubdiv/osd/d3d11VertexBuffer.cpp b/opensubdiv/osd/d3d11VertexBuffer.cpp -index 603cbf4..07e7e0a 100644 ---- a/opensubdiv/osd/d3d11VertexBuffer.cpp -+++ b/opensubdiv/osd/d3d11VertexBuffer.cpp -@@ -81,7 +81,7 @@ D3D11VertexBuffer::UpdateData(const float *src, int startVertex, int numVertices +diff --git a/opensubdiv/far/topologyRefiner.cpp b/opensubdiv/far/topologyRefiner.cpp +index 3754b36e..7fe42bcc 100644 +--- a/opensubdiv/far/topologyRefiner.cpp ++++ b/opensubdiv/far/topologyRefiner.cpp +@@ -263,7 +263,7 @@ namespace internal { + bool IsEmpty() const { return *((int_type*)this) == 0; } - deviceContext->Unmap(_uploadBuffer, 0); + FeatureMask() { Clear(); } +- FeatureMask(Options const & options, Sdc::SchemeType sType) { InitializeFeatures(options, sType); } ++ FeatureMask(Options const & options, Sdc::SchemeType sType) { Clear(); InitializeFeatures(options, sType); } -- D3D11_BOX srcBox = { 0, 0, 0, size, 1, 1 }; -+ D3D11_BOX srcBox = { 0, 0, 0, (UINT) size, 1, 1 }; - deviceContext->CopySubresourceRegion(_buffer, 0, 0, 0, 0, - _uploadBuffer, 0, &srcBox); - } + // These are the two primary methods intended for use -- intialization via a set of Options + // and reduction of the subsequent feature set (which presumes prior initialization with the \ No newline at end of file diff --git a/build_files/build_environment/patches/openvdb.diff b/build_files/build_environment/patches/openvdb.diff index f3afa13ea171..391a7be46db1 100644 --- a/build_files/build_environment/patches/openvdb.diff +++ b/build_files/build_environment/patches/openvdb.diff @@ -1,11 +1,102 @@ -diff -Naur k:\BlenderDev\lib\win64_vc12_Harvest\openVDB\/include/openvdb/math/Coord.h .\openVDB/include/openvdb/math/Coord.h ---- k:\BlenderDev\lib\win64_vc12_Harvest\openVDB\/include/openvdb/math/Coord.h 2016-03-30 15:09:49 -0600 -+++ .\openVDB/include/openvdb/math/Coord.h 2016-04-01 06:53:47 -0600 -@@ -34,6 +34,7 @@ +diff -Naur openvdb.orig/openvdb/CMakeLists.txt openvdb/openvdb/CMakeLists.txt +--- openvdb.orig/openvdb/CMakeLists.txt 2018-04-10 12:22:17 -0600 ++++ openvdb/openvdb/CMakeLists.txt 2018-08-15 19:04:52 -0600 +@@ -82,6 +82,9 @@ + IF (WIN32 AND OPENVDB_DISABLE_BOOST_IMPLICIT_LINKING) + ADD_DEFINITIONS ( -DBOOST_ALL_NO_LIB ) + ENDIF () ++if(WIN32) ++ADD_DEFINITIONS ( -D__TBB_NO_IMPLICIT_LINKAGE ) ++endif() + + FIND_PACKAGE ( Blosc REQUIRED ) + FIND_PACKAGE ( TBB REQUIRED ) +@@ -195,6 +198,7 @@ + ${Ilmbase_HALF_LIBRARY} + ${ZLIB_LIBRARY} + ${BLOSC_blosc_LIBRARY} ++ ${EXTRA_LIBS} + ) + + IF (WIN32) +@@ -225,13 +228,16 @@ + ${VDB_PRINT_SOURCE_FILES} + ) + ++if(NOT WIN32) ++ set(EXTRA_LIBS m stdc++ dl) ++endif() ++ + TARGET_LINK_LIBRARIES ( vdb_print + openvdb_shared + ${CMAKE_THREAD_LIBS_INIT} + ${BLOSC_blosc_LIBRARY} +- m +- stdc++ +- ) ++ ${EXTRA_LIBS} ++) + + SET ( VDB_RENDER_SOURCE_FILES cmd/openvdb_render/main.cc ) + SET_SOURCE_FILES_PROPERTIES ( ${VDB_RENDER_SOURCE_FILES} +@@ -249,8 +255,7 @@ + ${Openexr_ILMIMF_LIBRARY} + ${Ilmbase_ILMTHREAD_LIBRARY} + ${Ilmbase_IEX_LIBRARY} +- m +- stdc++ ++ ${EXTRA_LIBS} + ) + + SET ( VDB_VIEW_SOURCE_FILES +@@ -270,7 +270,7 @@ + PROPERTIES + COMPILE_FLAGS "-DOPENVDB_USE_BLOSC ${OPENVDB_USE_GLFW_FLAG} -DGL_GLEXT_PROTOTYPES=1" + ) +-IF (NOT WIN32) ++IF (FALSE) + ADD_EXECUTABLE ( vdb_view + ${VDB_VIEW_SOURCE_FILES} + ) +@@ -283,9 +288,8 @@ + ${GLFW_LINK_LIBRARY} + ${GLFW_DEPENDENT_LIBRARIES} + ${GLEW_GLEW_LIBRARY} +- m +- stdc++ +- ) ++ ${EXTRA_LIBS} ++ ) + ENDIF () + + SET ( UNITTEST_SOURCE_FILES +@@ -392,8 +396,7 @@ + TARGET_LINK_LIBRARIES ( vdb_test + ${CPPUnit_cppunit_LIBRARY} + openvdb_shared +- m +- stdc++ ++ ${EXTRA_LIBS} + ) + + ADD_TEST ( vdb_unit_test vdb_test ) +@@ -422,7 +422,7 @@ + ENDIF () + + # Installation +-IF ( NOT WIN32 ) ++IF ( FALSE ) + INSTALL ( TARGETS + vdb_view + DESTINATION +diff -Naur openvdb.orig/openvdb/math/Coord.h openvdb/openvdb/math/Coord.h +--- openvdb.orig/openvdb/math/Coord.h 2018-04-10 12:22:17 -0600 ++++ openvdb/openvdb/math/Coord.h 2018-08-15 20:32:43 -0600 +@@ -35,6 +35,7 @@ + #include // for std::array + #include + #include ++#define NOMINMAX #include #include "Math.h" #include "Vec3.h" -+#define NOMINMAX - - namespace tbb { class split; } // forward declaration - diff --git a/build_files/build_environment/patches/openvdb_vc2013.diff b/build_files/build_environment/patches/openvdb_vc2013.diff deleted file mode 100644 index 7dc3e4762978..000000000000 --- a/build_files/build_environment/patches/openvdb_vc2013.diff +++ /dev/null @@ -1,35 +0,0 @@ ---- openvdb/tree/LeafNode.h 2015-10-01 15:55:33 -0600 -+++ openvdb/tree/LeafNode.h 2016-03-26 13:12:22 -0600 -@@ -70,13 +70,14 @@ - typedef boost::shared_ptr Ptr; - typedef util::NodeMask NodeMaskType; - -- static const Index -- LOG2DIM = Log2Dim, // needed by parent nodes -- TOTAL = Log2Dim, // needed by parent nodes -- DIM = 1 << TOTAL, // dimension along one coordinate direction -- NUM_VALUES = 1 << 3 * Log2Dim, -- NUM_VOXELS = NUM_VALUES, // total number of voxels represented by this node -- SIZE = NUM_VALUES, -+ static const Index -+ LOG2DIM = Log2Dim, // needed by parent nodes -+ TOTAL = Log2Dim, // needed by parent nodes -+ DIM = 1 << TOTAL, // dimension along one coordinate direction -+ NUM_VALUES = 1 << 3 * Log2Dim, -+ NUM_VOXELS = NUM_VALUES; // total number of voxels represented by this node -+ static const Index -+ SIZE = NUM_VALUES, - LEVEL = 0; // level 0 = leaf - - /// @brief ValueConverter::Type is the type of a LeafNode having the same ---- openvdb/PlatformConfig.h 2016-03-30 15:09:49 -0600 -+++ openvdb/PlatformConfig.h 2016-04-01 07:00:38 -0600 -@@ -47,7 +47,7 @@ - #if !defined(OPENVDB_OPENEXR_STATICLIB) && !defined(OPENEXR_DLL) - #define OPENEXR_DLL - #endif -- -+ #define NOMINMAX - #endif // _WIN32 - - #endif // OPENVDB_PLATFORMCONFIG_HAS_BEEN_INCLUDED diff --git a/build_files/build_environment/patches/osl.diff b/build_files/build_environment/patches/osl.diff index ccf34d996992..36cda06f3948 100644 --- a/build_files/build_environment/patches/osl.diff +++ b/build_files/build_environment/patches/osl.diff @@ -1,6 +1,6 @@ -diff -Naur osl/src/external_osl/src/cmake/flexbison.cmake osl_bak/src/external_osl/src/cmake/flexbison.cmake ---- osl/src/external_osl//src/cmake/flexbison.cmake 2016-01-29 11:15:22 -0700 -+++ osl_bak/src/external_osl/src/cmake/flexbison.cmake 2016-02-29 21:26:26 -0700 +diff -Naur OpenShadingLanguage-Release-1.9.9/src/cmake/flexbison.cmake external_osl/src/cmake/flexbison.cmake +--- OpenShadingLanguage-Release-1.9.9/src/cmake/flexbison.cmake 2018-05-01 16:39:02 -0600 ++++ external_osl/src/cmake/flexbison.cmake 2018-08-23 15:42:27 -0600 @@ -77,7 +77,7 @@ DEPENDS ${${compiler_headers}} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) @@ -10,29 +10,65 @@ diff -Naur osl/src/external_osl/src/cmake/flexbison.cmake osl_bak/src/external_o MAIN_DEPENDENCY ${flexsrc} DEPENDS ${${compiler_headers}} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) ---- osl/src/external_osl/src/include/OSL/oslconfig.h 2016-10-31 16:48:19 -0600 -+++ osl/src/external_osl/src/include/OSL/oslconfig.h 2018-05-27 11:18:08 -0600 -@@ -44,12 +44,18 @@ - // same if another packages is compiling against OSL and using these headers - // (OSL may be C++11 but the client package may be older, or vice versa -- - // use these two symbols to differentiate these cases, when important). --#if (__cplusplus >= 201402L) --# define OSL_CPLUSPLUS_VERSION 14 --#elif (__cplusplus >= 201103L) --# define OSL_CPLUSPLUS_VERSION 11 +diff -Naur OpenShadingLanguage-Release-1.9.9/src/cmake/flexbison.cmake.rej external_osl/src/cmake/flexbison.cmake.rej +--- OpenShadingLanguage-Release-1.9.9/src/cmake/flexbison.cmake.rej 1969-12-31 17:00:00 -0700 ++++ external_osl/src/cmake/flexbison.cmake.rej 2018-08-24 17:42:11 -0600 +@@ -0,0 +1,11 @@ ++--- src/cmake/flexbison.cmake 2018-05-01 16:39:02 -0600 +++++ src/cmake/flexbison.cmake 2018-08-24 10:24:03 -0600 ++@@ -77,7 +77,7 @@ ++ DEPENDS ${${compiler_headers}} ++ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) ++ ADD_CUSTOM_COMMAND ( OUTPUT ${flexoutputcxx} ++- COMMAND ${FLEX_EXECUTABLE} -o ${flexoutputcxx} "${CMAKE_CURRENT_SOURCE_DIR}/${flexsrc}" +++ COMMAND ${FLEX_EXECUTABLE} ${FLEX_EXTRA_OPTIONS} -o ${flexoutputcxx} "${CMAKE_CURRENT_SOURCE_DIR}/${flexsrc}" ++ MAIN_DEPENDENCY ${flexsrc} ++ DEPENDS ${${compiler_headers}} ++ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) +diff -Naur OpenShadingLanguage-Release-1.9.9/src/include/OSL/llvm_util.h external_osl/src/include/OSL/llvm_util.h +--- OpenShadingLanguage-Release-1.9.9/src/include/OSL/llvm_util.h 2018-05-01 16:39:02 -0600 ++++ external_osl/src/include/OSL/llvm_util.h 2018-08-25 14:05:00 -0600 +@@ -33,6 +33,8 @@ + + #include + ++#define OSL_HAS_BLENDER_CLEANUP_FIX + -+// Force C++03 for MSVC in blender since svn the libraries are build with that -+#if !defined(_MSC_VER) -+ #if (__cplusplus >= 201402L) -+ # define OSL_CPLUSPLUS_VERSION 14 -+ #elif (__cplusplus >= 201103L) -+ # define OSL_CPLUSPLUS_VERSION 11 -+ #else -+ # define OSL_CPLUSPLUS_VERSION 3 /* presume C++03 */ -+ #endif - #else --# define OSL_CPLUSPLUS_VERSION 3 /* presume C++03 */ -+ # define OSL_CPLUSPLUS_VERSION 3 /* presume C++03 */ + #ifdef LLVM_NAMESPACE + namespace llvm = LLVM_NAMESPACE; #endif +@@ -487,6 +489,7 @@ + std::string func_name (llvm::Function *f); + + static size_t total_jit_memory_held (); ++ static void Cleanup (); + + private: + class MemoryManager; +diff -Naur OpenShadingLanguage-Release-1.9.9/src/include/OSL/oslnoise.h external_osl/src/include/OSL/oslnoise.h +--- OpenShadingLanguage-Release-1.9.9/src/include/OSL/oslnoise.h 2018-05-01 16:39:02 -0600 ++++ external_osl/src/include/OSL/oslnoise.h 2018-08-24 17:42:11 -0600 +@@ -762,7 +762,7 @@ + // packed into a float4. We assume T is float and VECTYPE is float4, + // but it also works if T is Dual2 and VECTYPE is Dual2. + template +-OIIO_FORCEINLINE T bilerp (VECTYPE abcd, T u, T v) { ++OIIO_FORCEINLINE T bilerp (VECTYPE& abcd, T u, T v) { + VECTYPE xx = OIIO::lerp (abcd, OIIO::simd::shuffle<1,1,3,3>(abcd), u); + return OIIO::simd::extract<0>(OIIO::lerp (xx,OIIO::simd::shuffle<2>(xx), v)); + } +diff -Naur OpenShadingLanguage-Release-1.9.9/src/liboslexec/llvm_util.cpp external_osl/src/liboslexec/llvm_util.cpp +--- OpenShadingLanguage-Release-1.9.9/src/liboslexec/llvm_util.cpp 2018-05-01 16:39:02 -0600 ++++ external_osl/src/liboslexec/llvm_util.cpp 2018-08-25 14:04:27 -0600 +@@ -140,7 +140,10 @@ + }; + + +- ++void LLVM_Util::Cleanup () ++{ ++ jitmm_hold.clear(); ++} - // Symbol export defines + size_t + LLVM_Util::total_jit_memory_held () diff --git a/build_files/build_environment/patches/osl_simd_oiio.diff b/build_files/build_environment/patches/osl_simd_oiio.diff deleted file mode 100644 index 5062a5971670..000000000000 --- a/build_files/build_environment/patches/osl_simd_oiio.diff +++ /dev/null @@ -1,14 +0,0 @@ ---- CMakeLists.txt 2016-10-31 16:48:19 -0600 -+++ CMakeLists.txt 2017-04-10 10:38:48 -0600 -@@ -269,6 +269,11 @@ - add_definitions ("-DOIIO_STATIC_BUILD=1") - endif () - -+set (OIIO_NOSIMD OFF CACHE BOOL "Disable simd support in oiio") -+if (OIIO_NOSIMD) -+ add_definitions ("-DOIIO_NO_SSE=1") -+endif () -+ - if (OSL_NO_DEFAULT_TEXTURESYSTEM) - add_definitions ("-DOSL_NO_DEFAULT_TEXTURESYSTEM=1") - endif () diff --git a/build_files/build_environment/patches/pyshell.diff b/build_files/build_environment/patches/pyshell.diff deleted file mode 100644 index 7ccffe4c0402..000000000000 --- a/build_files/build_environment/patches/pyshell.diff +++ /dev/null @@ -1,12 +0,0 @@ ---- pyshellext.cpp.orig 2017-01-17 00:57:53 -0700 -+++ pyshellext.cpp 2017-05-20 15:21:51 -0600 -@@ -13,6 +13,9 @@ - #include - - #include "pyshellext_h.h" -+#if _MSC_VER < 1900 -+#include "pyshellext_i.c" -+#endif - - #define DDWM_UPDATEWINDOW (WM_USER+3) - diff --git a/build_files/build_environment/patches/python.diff b/build_files/build_environment/patches/python.diff deleted file mode 100644 index 9e7eccfafff4..000000000000 --- a/build_files/build_environment/patches/python.diff +++ /dev/null @@ -1,82 +0,0 @@ ---- Include/Python.h 2017-07-07 21:33:27 -0600 -+++ Include/Python.h 2017-09-19 10:36:10 -0600 -@@ -2,6 +2,10 @@ - #define Py_PYTHON_H - /* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */ - -+#if _MSC_VER < 1900 -+#define inline __inline -+#endif -+ - /* Include nearly all Python header files */ - - #include "patchlevel.h" ---- Include/pydtrace.h 2017-07-07 21:33:27 -0600 -+++ Include/pydtrace.h 2017-09-19 10:32:31 -0600 -@@ -2,6 +2,11 @@ - - #ifndef Py_DTRACE_H - #define Py_DTRACE_H -+ -+#if _MSC_VER < 1900 -+#define inline __inline -+#endif -+ - #ifdef __cplusplus - extern "C" { - #endif - ---- Modules/_blake2/impl/blake2.h 2017-07-07 21:33:27 -0600 -+++ Modules/_blake2/impl/blake2.h 2017-09-19 10:22:41 -0600 -@@ -19,6 +19,10 @@ - #include - #include - -+#if _MSC_VER < 1900 -+#define inline __inline -+#endif -+ - #ifdef BLAKE2_NO_INLINE - #define BLAKE2_LOCAL_INLINE(type) static type - #endif - ---- pcbuild/build.bat 2016-05-21 09:53:55 -0600 -+++ pcbuild/build.bat 2016-05-21 09:56:16 -0600 -@@ -59,6 +59,7 @@ - if "%~1"=="-h" goto Usage - if "%~1"=="-c" (set conf=%2) & shift & shift & goto CheckOpts - if "%~1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts -+if "%~1"=="-k" (set vs_toolset=%2) & shift & shift & goto CheckOpts - if "%~1"=="-r" (set target=Rebuild) & shift & goto CheckOpts - if "%~1"=="-t" (set target=%2) & shift & shift & goto CheckOpts - if "%~1"=="-d" (set conf=Debug) & shift & goto CheckOpts -@@ -120,7 +120,7 @@ - - :Kill - echo on --%MSBUILD% "%dir%\pythoncore.vcxproj" /t:KillPython %verbose%^ -+%MSBUILD% "%dir%\pythoncore.vcxproj" /t:KillPython %verbose% /p:PlatformToolset=%vs_toolset%^ - /p:Configuration=%conf% /p:Platform=%platf%^ - /p:KillPython=true - -@@ -130,7 +130,7 @@ - rem batch is, shall we say, "lackluster" - echo on - %MSBUILD% "%dir%pcbuild.proj" /t:%target% %parallel% %verbose%^ -- /p:Configuration=%conf% /p:Platform=%platf%^ -+ /p:Configuration=%conf% /p:Platform=%platf% /p:PlatformToolset=%vs_toolset%^ - /p:IncludeExternals=%IncludeExternals%^ - /p:IncludeSSL=%IncludeSSL% /p:IncludeTkinter=%IncludeTkinter%^ - /p:UseTestMarker=%UseTestMarker%^ - ---- pcbuild/sqlite3.vcxproj 2015-12-06 18:39:10 -0700 -+++ pcbuild/sqlite3.vcxproj 2016-11-02 09:25:56 -0600 -@@ -43,7 +43,7 @@ - - - -- DynamicLibrary -+ StaticLibrary - NotSet - - diff --git a/build_files/build_environment/patches/python_apple.diff b/build_files/build_environment/patches/python_apple.diff deleted file mode 100644 index 34a7906ed6ce..000000000000 --- a/build_files/build_environment/patches/python_apple.diff +++ /dev/null @@ -1,25 +0,0 @@ ---- pyconfig.h.in 2017-09-19 14:41:01.000000000 +0300 -+++ pyconfig.h.in 2017-09-19 14:43:18.000000000 +0300 -@@ -119,12 +119,6 @@ - /* Define to 1 if you have the `clock' function. */ - #undef HAVE_CLOCK - --/* Define to 1 if you have the `clock_getres' function. */ --#undef HAVE_CLOCK_GETRES -- --/* Define to 1 if you have the `clock_gettime' function. */ --#undef HAVE_CLOCK_GETTIME -- - /* Define to 1 if you have the `clock_settime' function. */ - #undef HAVE_CLOCK_SETTIME - -@@ -369,9 +363,6 @@ - /* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */ - #undef HAVE_GETC_UNLOCKED - --/* Define to 1 if you have the `getentropy' function. */ --#undef HAVE_GETENTROPY -- - /* Define to 1 if you have the `getgrouplist' function. */ - #undef HAVE_GETGROUPLIST - diff --git a/build_files/build_environment/patches/python_linux.diff b/build_files/build_environment/patches/python_linux.diff new file mode 100644 index 000000000000..24d625c7cebd --- /dev/null +++ b/build_files/build_environment/patches/python_linux.diff @@ -0,0 +1,38 @@ +diff --git a/setup.py.orig b/setup.py +index a97a755..07ce853 100644 +--- a/setup.py.orig ++++ b/setup.py +@@ -1422,13 +1422,13 @@ class PyBuildExt(build_ext): + version = line.split()[2] + break + if version >= version_req: +- if (self.compiler.find_library_file(lib_dirs, 'z')): ++ if (self.compiler.find_library_file(lib_dirs, 'z_pic')): + if host_platform == "darwin": + zlib_extra_link_args = ('-Wl,-search_paths_first',) + else: + zlib_extra_link_args = () + exts.append( Extension('zlib', ['zlibmodule.c'], +- libraries = ['z'], ++ libraries = ['z_pic'], + extra_link_args = zlib_extra_link_args)) + have_zlib = True + else: +@@ -1442,7 +1442,7 @@ class PyBuildExt(build_ext): + # crc32 if we have it. Otherwise binascii uses its own. + if have_zlib: + extra_compile_args = ['-DUSE_ZLIB_CRC32'] +- libraries = ['z'] ++ libraries = ['z_pic'] + extra_link_args = zlib_extra_link_args + else: + extra_compile_args = [] +@@ -1991,7 +1991,7 @@ class PyBuildExt(build_ext): + print('Header file {} does not exist'.format(ffi_h)) + ffi_lib = None + if ffi_inc is not None: +- for lib_name in ('ffi', 'ffi_pic'): ++ for lib_name in ('ffi_pic', ): + if (self.compiler.find_library_file(lib_dirs, lib_name)): + ffi_lib = lib_name + break diff --git a/build_files/build_environment/patches/python_runtime_vc2013.diff b/build_files/build_environment/patches/python_runtime_vc2013.diff deleted file mode 100644 index 186d2b36c071..000000000000 --- a/build_files/build_environment/patches/python_runtime_vc2013.diff +++ /dev/null @@ -1,29 +0,0 @@ ---- _msvccompiler.py.orig 2017-05-20 19:31:45 -0600 -+++ _msvccompiler.py 2017-06-10 10:05:38 -0600 -@@ -222,9 +222,9 @@ - # use /MT[d] to build statically, then switch from libucrt[d].lib to ucrt[d].lib - # later to dynamically link to ucrtbase but not vcruntime. - self.compile_options = [ -- '/nologo', '/Ox', '/W3', '/GL', '/DNDEBUG' -+ '/nologo', '/Ox', '/W3', '/GL', '/DNDEBUG' , '/MD' - ] -- self.compile_options.append('/MD' if self._vcruntime_redist else '/MT') -+ #self.compile_options.append('/MD' if self._vcruntime_redist else '/MT') - - self.compile_options_debug = [ - '/nologo', '/Od', '/MDd', '/Zi', '/W3', '/D_DEBUG' -@@ -233,11 +233,11 @@ - ldflags = [ - '/nologo', '/INCREMENTAL:NO', '/LTCG' - ] -- if not self._vcruntime_redist: -- ldflags.extend(('/nodefaultlib:libucrt.lib', 'ucrt.lib')) -+ #if not self._vcruntime_redist: -+ # ldflags.extend(('/nodefaultlib:libucrt.lib', 'ucrt.lib')) - - ldflags_debug = [ -- '/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL' -+ '/nologo', '/INCREMENTAL:NO', '/LTCG' - ] - - self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1'] diff --git a/build_files/build_environment/patches/schroedinger.diff b/build_files/build_environment/patches/schroedinger.diff deleted file mode 100644 index 6acb35f2a7b4..000000000000 --- a/build_files/build_environment/patches/schroedinger.diff +++ /dev/null @@ -1,54 +0,0 @@ ---- configure.orig 2012-01-22 19:06:43 -0700 -+++ configure 2016-04-06 20:00:50 -0600 -@@ -16492,10 +16492,10 @@ - HAVE_ORC=yes - fi - if test "x${HAVE_ORC}" != xyes ; then -- as_fn_error $? "orc-0.4 >= $ORC_VER is required" "$LINENO" 5 -+ $as_echo "orc-0.4 >= $ORC_VER is required" - fi - SCHRO_PKG_DEPS="$SCHRO_PKG_DEPS orc-0.4 >= $ORC_VER" --ORCC=`$PKG_CONFIG --variable=orcc orc-0.4` -+#ORCC=`$PKG_CONFIG --variable=orcc orc-0.4` - - if test "x$cross_compiling" != xyes; then - HAVE_ORCC_TRUE= ---- Makefile.in 2012-01-22 18:06:42 -0700 -+++ Makefile.in 2016-04-06 20:30:09 -0600 -@@ -291,7 +291,7 @@ - top_builddir = @top_builddir@ - top_srcdir = @top_srcdir@ - AUTOMAKE_OPTIONS = foreign --SUBDIRS = schroedinger doc tools testsuite -+SUBDIRS = schroedinger doc tools - DISTCHECK_CONFIGURE_FLAGS = --enable-gtk-doc - DIST_SUBDIRS = schroedinger doc tools testsuite - EXTRA_DIST = COPYING COPYING.GPL COPYING.LGPL COPYING.MIT COPYING.MPL \ - ---- schroedinger.pc.in 2011-03-21 17:08:39 -0600 -+++ schroedinger.pc.in 2016-04-08 13:30:42 -0600 -@@ -7,9 +7,9 @@ - - Name: schroedinger-@SCHRO_MAJORMINOR@ - Description: Dirac codec library --Requires.private: @SCHRO_PKG_DEPS@ -+Requires: @SCHRO_PKG_DEPS@ - Version: @VERSION@ --Libs: -L${libdir} -lschroedinger-@SCHRO_MAJORMINOR@ -+Libs: -L${libdir} -lschroedinger-@SCHRO_MAJORMINOR@ -lorc-0.4 - Libs.private: @PTHREAD_LIBS@ @LIBM@ - Cflags: -I${includedir} - ---- ./schroedinger/schrodecoder.c 2012-01-23 00:38:57.000000000 +0100 -+++ ./schroedinger/schrodecoder.c 2016-05-15 06:07:24.000000000 +0200 -@@ -70,8 +70,8 @@ - }; - - --int _schro_decode_prediction_only; --int _schro_telemetry; -+int _schro_decode_prediction_only = 0; -+int _schro_telemetry = 0; - - static void schro_decoder_x_decode_motion (SchroAsyncStage * stage); - static void schro_decoder_x_render_motion (SchroAsyncStage * stage); diff --git a/build_files/build_environment/patches/sdl.diff b/build_files/build_environment/patches/sdl.diff index b309d0230f30..d0a3bca863d7 100644 --- a/build_files/build_environment/patches/sdl.diff +++ b/build_files/build_environment/patches/sdl.diff @@ -1,33 +1,4 @@ diff -ru /Users/brecht/dev/lib/deps/Downloads/SDL2-2.0.4/src/video/SDL_video.c ./src/video/SDL_video.c ---- /Users/brecht/dev/lib/deps/Downloads/SDL2-2.0.4/src/video/SDL_video.c 2016-01-02 20:56:31.000000000 +0100 -+++ ./src/video/SDL_video.c 2016-05-15 02:58:27.000000000 +0200 -@@ -137,7 +137,7 @@ - - #define FULLSCREEN_MASK (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN) - --#ifdef __MACOSX__ -+#if SDL_VIDEO_DRIVER_COCOA - /* Support for Mac OS X fullscreen spaces */ - extern SDL_bool Cocoa_IsWindowInFullscreenSpace(SDL_Window * window); - extern SDL_bool Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state); -@@ -1141,7 +1141,7 @@ - if ( window->is_hiding && fullscreen ) - return 0; - --#ifdef __MACOSX__ -+#if SDL_VIDEO_DRIVER_COCOA - /* if the window is going away and no resolution change is necessary, - do nothing, or else we may trigger an ugly double-transition - */ -@@ -2365,7 +2365,7 @@ - return SDL_FALSE; - } - --#ifdef __MACOSX__ -+#if SDL_VIDEO_DRIVER_COCOA - if (Cocoa_IsWindowInFullscreenSpace(window)) { - return SDL_FALSE; - } --- CMakeLists.txt.old 2016-01-02 12:56:31 -0700 +++ CMakeLists.txt 2016-10-03 11:24:24 -0600 @@ -609,7 +609,7 @@ @@ -39,12 +10,3 @@ diff -ru /Users/brecht/dev/lib/deps/Downloads/SDL2-2.0.4/src/video/SDL_video.c . if(HAVE_LIBICONV) list(APPEND EXTRA_LIBS iconv) set(HAVE_ICONV 1) -@@ -1455,7 +1455,7 @@ - set(_INSTALL_LIBS "SDL2main") - - if(SDL_SHARED) -- add_library(SDL2 SHARED ${SOURCE_FILES}) -+ add_library(SDL2 SHARED ${SOURCE_FILES} ${VERSION_SOURCES}) - if(UNIX) - set_target_properties(SDL2 PROPERTIES - VERSION ${LT_VERSION} diff --git a/build_files/build_environment/patches/tinyxml.diff b/build_files/build_environment/patches/tinyxml.diff new file mode 100644 index 000000000000..9965f3e610e0 --- /dev/null +++ b/build_files/build_environment/patches/tinyxml.diff @@ -0,0 +1,34 @@ +diff -Naur tinyxml.orig/CMakeLists.txt tinyxml/CMakeLists.txt +--- tinyxml.orig/CMakeLists.txt 1969-12-31 16:00:00.000000000 -0800 ++++ tinyxml/CMakeLists.txt 2013-06-18 17:10:59.000000000 -0700 +@@ -0,0 +1,30 @@ ++project(tinyxml) ++ ++cmake_minimum_required(VERSION 2.8) ++ ++add_library(tinyxml ++ STATIC ++ tinystr.cpp ++ tinyxml.cpp ++ tinyxmlerror.cpp ++ tinyxmlparser.cpp) ++ ++set(TINYXML_COMPILE_FLAGS "-DTIXML_USE_STL") ++ ++if(UNIX) ++ set(TINYXML_COMPILE_FLAGS "${TINYXML_COMPILE_FLAGS} -fPIC -fvisibility=hidden") ++endif() ++ ++if(OCIO_INLINES_HIDDEN AND UNIX) ++ set(TINYXML_COMPILE_FLAGS "${TINYXML_COMPILE_FLAGS} -fvisibility-inlines-hidden") ++endif() ++ ++set_target_properties(tinyxml PROPERTIES ++ COMPILE_FLAGS "${TINYXML_COMPILE_FLAGS}") ++ ++install(TARGETS ++ tinyxml ++ DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) ++install(FILES ++ tinyxml.h tinystr.h ++ DESTINATION ${CMAKE_INSTALL_PREFIX}/include) diff --git a/build_files/build_environment/patches/x264.diff b/build_files/build_environment/patches/x264.diff new file mode 100644 index 000000000000..2f2e68083acb --- /dev/null +++ b/build_files/build_environment/patches/x264.diff @@ -0,0 +1,22 @@ +--- x264-snapshot-20180811-2245-stable\configure 2018-08-11 14:45:05 -0600 ++++ external_x264\configure 2018-08-11 23:51:35 -0600 +@@ -396,7 +396,7 @@ + # list of all preprocessor HAVE values we can define + CONFIG_HAVE="MALLOC_H ALTIVEC ALTIVEC_H MMX ARMV6 ARMV6T2 NEON BEOSTHREAD POSIXTHREAD WIN32THREAD THREAD LOG2F SWSCALE \ + LAVF FFMS GPAC AVS GPL VECTOREXT INTERLACED CPU_COUNT OPENCL THP LSMASH X86_INLINE_ASM AS_FUNC INTEL_DISPATCHER \ +- MSA MMAP WINRT VSX ARM_INLINE_ASM STRTOK_R BITDEPTH8 BITDEPTH10" ++ MSA MMAP WINRT VSX ARM_INLINE_ASM BITDEPTH8 BITDEPTH10" + + # parse options + +@@ -1071,10 +1071,6 @@ + define HAVE_LOG2F + fi + +-if cc_check 'string.h' '' 'strtok_r(0, 0, 0);' ; then +- define HAVE_STRTOK_R +-fi +- + if [ "$SYS" != "WINDOWS" ] && cpp_check "sys/mman.h unistd.h" "" "defined(MAP_PRIVATE)"; then + define HAVE_MMAP + fi diff --git a/build_files/buildbot/config/blender_linux.cmake b/build_files/buildbot/config/blender_linux.cmake index a405ae95fff1..1c400339dfe1 100644 --- a/build_files/buildbot/config/blender_linux.cmake +++ b/build_files/buildbot/config/blender_linux.cmake @@ -1,11 +1,21 @@ # ######## Global feature set settings ######## -include("${CMAKE_CURRENT_LIST_DIR}/../../cmake/config/blender_full.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/../../cmake/config/blender_release.cmake") # Detect which libc we'll be linking against. # Some of the paths will depend on this -if(EXISTS "/lib/x86_64-linux-gnu/libc-2.19.so") +if(EXISTS "/lib/x86_64-linux-gnu/libc-2.24.so") + message(STATUS "Building in GLibc-2.24 environment") + set(GLIBC "2.24") + set(MULTILIB "/x86_64-linux-gnu") + set(LIBDIR_NAME "linux_x86_64") +elseif(EXISTS "/lib/i386-linux-gnu//libc-2.24.so") + message(STATUS "Building in GLibc-2.24 environment") + set(GLIBC "2.24") + set(MULTILIB "/i386-linux-gnu") + set(LIBDIR_NAME "linux_i686") +elseif(EXISTS "/lib/x86_64-linux-gnu/libc-2.19.so") message(STATUS "Building in GLibc-2.19 environment") set(GLIBC "2.19") set(MULTILIB "/x86_64-linux-gnu") @@ -41,7 +51,10 @@ set(WITH_PYTHON_INSTALL_NUMPY ON CACHE BOOL "" FORCE) set(WITH_PYTHON_INSTALL_REQUESTS ON CACHE BOOL "" FORCE) # ######## Release environment specific settings ######## -# All the hardcoded libraru paths and such + +if (NOT ${GLIBC} STREQUAL "2.24") + +# All the hardcoded library paths and such # LLVM libraries set(LLVM_VERSION "3.4" CACHE STRING "" FORCE) @@ -74,7 +87,7 @@ set(SNDFILE_LIBRARY "/usr/lib${MULTILIB}/libsndfile.a;/usr/lib${MULTILI # OpenAL libraries set(OPENAL_ROOT_DIR "/opt/lib/openal" CACHE STRING "" FORCE) -set(OPENAL_INCLUDE_DIR "${OPENAL_ROOT_DIR}/include" CACHE STRING "" FORCE) +set(OPENAL_INCLUDE_DIR "${OPENAL_ROOT_DIR}/include/AL" CACHE STRING "" FORCE) set(OPENAL_LIBRARY ${OPENAL_ROOT_DIR}/lib/libopenal.a ${OPENAL_ROOT_DIR}/lib/libcommon.a @@ -148,5 +161,28 @@ set(BLOSC_LIBRARY CACHE BOOL "" FORCE ) +else() + +set(LIBDIR "/opt/blender-deps/${LIBDIR_NAME}" CACHE BOOL "" FORCE) + +# TODO(sergey): Remove once Python is oficially bumped to 3.7. +set(PYTHON_VERSION 3.7 CACHE BOOL "" FORCE) + +# Platform specific configuration, to ensure static linking against everything. + +set(Boost_USE_STATIC_LIBS ON CACHE BOOL "" FORCE) + +# TODO(sergey): Move up to the rest of WITH_SYSTEM and DYNLOAD configuration, +# once old chroot is officially retired. +set(WITH_SYSTEM_OPENJPEG ON CACHE BOOL "" FORCE) + +# We need to link OpenCOLLADA against PCRE library. Even though it is not installed +# on /usr, we do not really care -- all we care is PCRE_FOUND be TRUE and its +# library pointing to a valid one. +set(PCRE_INCLUDE_DIR "/usr/include" CACHE STRING "" FORCE) +set(PCRE_LIBRARY "${LIBDIR}/opencollada/lib/libpcre.a" CACHE STRING "" FORCE) + +endif() + # Additional linking libraries -set(CMAKE_EXE_LINKER_FLAGS "-lrt -static-libstdc++" CACHE STRING "" FORCE) +set(CMAKE_EXE_LINKER_FLAGS "-lrt -static-libstdc++ -no-pie" CACHE STRING "" FORCE) diff --git a/build_files/buildbot/slave_compile.py b/build_files/buildbot/slave_compile.py index ff19bcce758b..d5ec5630e39e 100644 --- a/build_files/buildbot/slave_compile.py +++ b/build_files/buildbot/slave_compile.py @@ -48,7 +48,7 @@ def parse_header_file(filename, define): # cmake # Some fine-tuning configuration - blender_dir = os.path.join('..', blender_dir) + blender_dir = os.path.abspath(blender_dir) build_dir = os.path.abspath(os.path.join('..', 'build', builder)) install_dir = os.path.abspath(os.path.join('..', 'install', builder)) targets = ['blender'] @@ -59,7 +59,7 @@ def parse_header_file(filename, define): bits = 64 # Config file to be used (relative to blender's sources root) - cmake_config_file = "build_files/cmake/config/blender_full.cmake" + cmake_config_file = "build_files/cmake/config/blender_release.cmake" cmake_player_config_file = None cmake_cuda_config_file = None @@ -78,7 +78,13 @@ def parse_header_file(filename, define): # cmake_extra_options.append('-DCUDA_NVCC_EXECUTABLE=/usr/local/cuda-hack/nvcc') elif builder.startswith('win'): - if builder.endswith('_vc2015'): + if builder.endswith('_vs2017'): + if builder.startswith('win64'): + cmake_options.extend(['-G', 'Visual Studio 15 2017 Win64']) + elif builder.startswith('win32'): + bits = 32 + cmake_options.extend(['-G', 'Visual Studio 15 2017']) + elif builder.endswith('_vc2015'): if builder.startswith('win64'): cmake_options.extend(['-G', 'Visual Studio 14 2015 Win64']) elif builder.startswith('win32'): @@ -96,7 +102,9 @@ def parse_header_file(filename, define): elif builder.startswith('linux'): tokens = builder.split("_") glibc = tokens[1] - if glibc == 'glibc219': + if glibc == 'glibc224': + deb_name = "stretch" + elif glibc == 'glibc219': deb_name = "jessie" elif glibc == 'glibc211': deb_name = "squeeze" @@ -109,8 +117,9 @@ def parse_header_file(filename, define): bits = 32 chroot_name = 'buildbot_' + deb_name + '_i686' targets = ['player', 'blender'] - cmake_extra_options.extend(["-DCMAKE_C_COMPILER=/usr/bin/gcc-7", - "-DCMAKE_CXX_COMPILER=/usr/bin/g++-7"]) + if deb_name != "stretch": + cmake_extra_options.extend(["-DCMAKE_C_COMPILER=/usr/bin/gcc-7", + "-DCMAKE_CXX_COMPILER=/usr/bin/g++-7"]) cmake_options.append("-C" + os.path.join(blender_dir, cmake_config_file)) @@ -153,10 +162,6 @@ def parse_header_file(filename, define): if target != 'blender': target_build_dir += '_' + target target_name = 'install' - # Make sure build directory exists and enter it - if not os.path.isdir(target_build_dir): - os.mkdir(target_build_dir) - os.chdir(target_build_dir) # Tweaking CMake options to respect the target target_cmake_options = cmake_options[:] if target == 'player': @@ -169,6 +174,19 @@ def parse_header_file(filename, define): # other targets don't compile cuda binaries. if 'cuda' in targets and target != 'cuda': target_cmake_options.append("-DWITH_CYCLES_CUDA_BINARIES=OFF") + # Do extra git fetch because not all platform/git/buildbot combinations + # update the origin remote, causing buildinfo to detect local changes. + os.chdir(blender_dir) + print("Fetching remotes") + command = ['git', 'fetch', '--all'] + print(command) + retcode = subprocess.call(target_chroot_prefix + command) + if retcode != 0: + sys.exit(retcode) + # Make sure build directory exists and enter it + if not os.path.isdir(target_build_dir): + os.mkdir(target_build_dir) + os.chdir(target_build_dir) # Configure the build print("CMake options:") print(target_cmake_options) @@ -183,11 +201,11 @@ def parse_header_file(filename, define): if 'win32' in builder or 'win64' in builder: command = ['cmake', '--build', '.', '--target', target_name, '--config', 'Release'] else: - command = target_chroot_prefix + ['make', '-s', '-j2', target_name] + command = ['make', '-s', '-j2', target_name] print("Executing command:") print(command) - retcode = subprocess.call(command) + retcode = subprocess.call(target_chroot_prefix + command) if retcode != 0: sys.exit(retcode) diff --git a/build_files/cmake/Modules/FindLLVM.cmake b/build_files/cmake/Modules/FindLLVM.cmake index f5f3db3fc71e..a40a71cb58eb 100644 --- a/build_files/cmake/Modules/FindLLVM.cmake +++ b/build_files/cmake/Modules/FindLLVM.cmake @@ -93,4 +93,3 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(LLVM DEFAULT_MSG MARK_AS_ADVANCED( LLVM_LIBRARY ) - diff --git a/build_files/cmake/Modules/FindOpenJPEG.cmake b/build_files/cmake/Modules/FindOpenJPEG.cmake index 85a4c131fb1d..a6c28be6782c 100644 --- a/build_files/cmake/Modules/FindOpenJPEG.cmake +++ b/build_files/cmake/Modules/FindOpenJPEG.cmake @@ -47,6 +47,7 @@ FIND_PATH(OPENJPEG_INCLUDE_DIR FIND_LIBRARY(OPENJPEG_LIBRARY NAMES openjpeg + openjp2 HINTS ${_openjpeg_SEARCH_DIRS} PATH_SUFFIXES diff --git a/build_files/cmake/config/blender_release.cmake b/build_files/cmake/config/blender_release.cmake index 26267fd314ae..121a82f8059a 100644 --- a/build_files/cmake/config/blender_release.cmake +++ b/build_files/cmake/config/blender_release.cmake @@ -5,6 +5,7 @@ # set(WITH_ALEMBIC ON CACHE BOOL "" FORCE) +set(WITH_ASSERT_ABORT OFF CACHE BOOL "" FORCE) set(WITH_BUILDINFO ON CACHE BOOL "" FORCE) set(WITH_BULLET ON CACHE BOOL "" FORCE) set(WITH_CODEC_AVI ON CACHE BOOL "" FORCE) diff --git a/build_files/cmake/macros.cmake b/build_files/cmake/macros.cmake index ae95479e4d6b..d810bf766588 100644 --- a/build_files/cmake/macros.cmake +++ b/build_files/cmake/macros.cmake @@ -870,164 +870,6 @@ macro(message_first_run) endif() endmacro() -macro(TEST_UNORDERED_MAP_SUPPORT) - # - Detect unordered_map availability - # Test if a valid implementation of unordered_map exists - # and define the include path - # This module defines - # HAVE_UNORDERED_MAP, whether unordered_map implementation was found - # - # HAVE_STD_UNORDERED_MAP_HEADER, was found - # HAVE_UNORDERED_MAP_IN_STD_NAMESPACE, unordered_map is in namespace std - # HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE, unordered_map is in namespace std::tr1 - # - # UNORDERED_MAP_INCLUDE_PREFIX, include path prefix for unordered_map, if found - # UNORDERED_MAP_NAMESPACE, namespace for unordered_map, if found - - include(CheckIncludeFileCXX) - - # Workaround for newer GCC (6.x+) where C++11 was enabled by default, which lead us - # to a situation when there is include but which can't be used uless - # C++11 is enabled. - if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11)) - set(HAVE_STD_UNORDERED_MAP_HEADER False) - else() - CHECK_INCLUDE_FILE_CXX("unordered_map" HAVE_STD_UNORDERED_MAP_HEADER) - endif() - if(HAVE_STD_UNORDERED_MAP_HEADER) - # Even so we've found unordered_map header file it doesn't - # mean unordered_map and unordered_set will be declared in - # std namespace. - # - # Namely, MSVC 2008 have unordered_map header which declares - # unordered_map class in std::tr1 namespace. In order to support - # this, we do extra check to see which exactly namespace is - # to be used. - - include(CheckCXXSourceCompiles) - CHECK_CXX_SOURCE_COMPILES("#include - int main() { - std::unordered_map map; - return 0; - }" - HAVE_UNORDERED_MAP_IN_STD_NAMESPACE) - if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE) - message_first_run(STATUS "Found unordered_map/set in std namespace.") - - set(HAVE_UNORDERED_MAP "TRUE") - set(UNORDERED_MAP_INCLUDE_PREFIX "") - set(UNORDERED_MAP_NAMESPACE "std") - else() - CHECK_CXX_SOURCE_COMPILES("#include - int main() { - std::tr1::unordered_map map; - return 0; - }" - HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - message_first_run(STATUS "Found unordered_map/set in std::tr1 namespace.") - - set(HAVE_UNORDERED_MAP "TRUE") - set(UNORDERED_MAP_INCLUDE_PREFIX "") - set(UNORDERED_MAP_NAMESPACE "std::tr1") - else() - message_first_run(STATUS "Found but cannot find either std::unordered_map " - "or std::tr1::unordered_map.") - endif() - endif() - else() - CHECK_INCLUDE_FILE_CXX("tr1/unordered_map" HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - message_first_run(STATUS "Found unordered_map/set in std::tr1 namespace.") - - set(HAVE_UNORDERED_MAP "TRUE") - set(UNORDERED_MAP_INCLUDE_PREFIX "tr1") - set(UNORDERED_MAP_NAMESPACE "std::tr1") - else() - message_first_run(STATUS "Unable to find or . ") - endif() - endif() -endmacro() - -macro(TEST_SHARED_PTR_SUPPORT) - # This check are coming from Ceres library. - # - # Find shared pointer header and namespace. - # - # This module defines the following variables: - # - # SHARED_PTR_FOUND: TRUE if shared_ptr found. - # SHARED_PTR_TR1_MEMORY_HEADER: True if header is to be used - # for the shared_ptr object, otherwise use . - # SHARED_PTR_TR1_NAMESPACE: TRUE if shared_ptr is defined in std::tr1 namespace, - # otherwise it's assumed to be defined in std namespace. - - include(CheckIncludeFileCXX) - include(CheckCXXSourceCompiles) - set(SHARED_PTR_FOUND FALSE) - # Workaround for newer GCC (6.x+) where C++11 was enabled by default, which lead us - # to a situation when there is include but which can't be used uless - # C++11 is enabled. - if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11)) - set(HAVE_STD_MEMORY_HEADER False) - else() - CHECK_INCLUDE_FILE_CXX(memory HAVE_STD_MEMORY_HEADER) - endif() - if(HAVE_STD_MEMORY_HEADER) - # Finding the memory header doesn't mean that shared_ptr is in std - # namespace. - # - # In particular, MSVC 2008 has shared_ptr declared in std::tr1. In - # order to support this, we do an extra check to see which namespace - # should be used. - CHECK_CXX_SOURCE_COMPILES("#include - int main() { - std::shared_ptr int_ptr; - return 0; - }" - HAVE_SHARED_PTR_IN_STD_NAMESPACE) - - if(HAVE_SHARED_PTR_IN_STD_NAMESPACE) - message_first_run("-- Found shared_ptr in std namespace using header.") - set(SHARED_PTR_FOUND TRUE) - else() - CHECK_CXX_SOURCE_COMPILES("#include - int main() { - std::tr1::shared_ptr int_ptr; - return 0; - }" - HAVE_SHARED_PTR_IN_TR1_NAMESPACE) - if(HAVE_SHARED_PTR_IN_TR1_NAMESPACE) - message_first_run("-- Found shared_ptr in std::tr1 namespace using header.") - set(SHARED_PTR_TR1_NAMESPACE TRUE) - set(SHARED_PTR_FOUND TRUE) - endif() - endif() - endif() - - if(NOT SHARED_PTR_FOUND) - # Further, gcc defines shared_ptr in std::tr1 namespace and - # is to be included for this. And what makes things - # even more tricky is that gcc does have header, so - # all the checks above wouldn't find shared_ptr. - CHECK_INCLUDE_FILE_CXX("tr1/memory" HAVE_TR1_MEMORY_HEADER) - if(HAVE_TR1_MEMORY_HEADER) - CHECK_CXX_SOURCE_COMPILES("#include - int main() { - std::tr1::shared_ptr int_ptr; - return 0; - }" - HAVE_SHARED_PTR_IN_TR1_NAMESPACE_FROM_TR1_MEMORY_HEADER) - if(HAVE_SHARED_PTR_IN_TR1_NAMESPACE_FROM_TR1_MEMORY_HEADER) - message_first_run("-- Found shared_ptr in std::tr1 namespace using header.") - set(SHARED_PTR_TR1_MEMORY_HEADER TRUE) - set(SHARED_PTR_TR1_NAMESPACE TRUE) - set(SHARED_PTR_FOUND TRUE) - endif() - endif() - endif() -endmacro() - # when we have warnings as errors applied globally this # needs to be removed for some external libs which we dont maintain. @@ -1052,13 +894,19 @@ macro(remove_cc_flag endmacro() -macro(add_cc_flag +macro(add_c_flag flag) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}") endmacro() +macro(add_cxx_flag + flag) + + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}") +endmacro() + macro(remove_strict_flags) if(CMAKE_COMPILER_IS_GNUCC) @@ -1081,7 +929,8 @@ macro(remove_strict_flags) ) # negate flags implied by '-Wall' - add_cc_flag("${CC_REMOVE_STRICT_FLAGS}") + add_c_flag("${C_REMOVE_STRICT_FLAGS}") + add_cxx_flag("${CXX_REMOVE_STRICT_FLAGS}") endif() if(CMAKE_C_COMPILER_ID MATCHES "Clang") @@ -1093,7 +942,8 @@ macro(remove_strict_flags) ) # negate flags implied by '-Wall' - add_cc_flag("${CC_REMOVE_STRICT_FLAGS}") + add_c_flag("${C_REMOVE_STRICT_FLAGS}") + add_cxx_flag("${CXX_REMOVE_STRICT_FLAGS}") endif() if(MSVC) @@ -1123,28 +973,39 @@ endmacro() # note, we can only append flags on a single file so we need to negate the options. # at the moment we cant shut up ffmpeg deprecations, so use this, but will # probably add more removals here. -macro(remove_strict_flags_file +macro(remove_strict_c_flags_file filenames) - foreach(_SOURCE ${ARGV}) - if(CMAKE_COMPILER_IS_GNUCC OR - (CMAKE_C_COMPILER_ID MATCHES "Clang")) - + (CMAKE_C_COMPILER_ID MATCHES "Clang")) set_source_files_properties(${_SOURCE} PROPERTIES - COMPILE_FLAGS "${CC_REMOVE_STRICT_FLAGS}" + COMPILE_FLAGS "${C_REMOVE_STRICT_FLAGS}" ) endif() - if(MSVC) # TODO endif() - endforeach() - unset(_SOURCE) +endmacro() +macro(remove_strict_cxx_flags_file + filenames) + remove_strict_c_flags_file(${filenames} ${ARHV}) + foreach(_SOURCE ${ARGV}) + if(CMAKE_COMPILER_IS_GNUCC OR + (CMAKE_CXX_COMPILER_ID MATCHES "Clang")) + set_source_files_properties(${_SOURCE} + PROPERTIES + COMPILE_FLAGS "${CXX_REMOVE_STRICT_FLAGS}" + ) + endif() + if(MSVC) + # TODO + endif() + endforeach() + unset(_SOURCE) endmacro() # External libs may need 'signed char' to be default. diff --git a/build_files/cmake/platform/platform_apple.cmake b/build_files/cmake/platform/platform_apple.cmake index 692c8c72f916..2aee694ae096 100644 --- a/build_files/cmake/platform/platform_apple.cmake +++ b/build_files/cmake/platform/platform_apple.cmake @@ -43,7 +43,6 @@ if(WITH_OPENAL) find_package(OpenAL) if(OPENAL_FOUND) set(WITH_OPENAL ON) - set(OPENAL_INCLUDE_DIR "${LIBDIR}/openal/include") else() set(WITH_OPENAL OFF) endif() @@ -159,7 +158,10 @@ if(WITH_CODEC_FFMPEG) set(FFMPEG_LIBRARIES avcodec avdevice avformat avutil mp3lame swscale x264 xvidcore theora theoradec theoraenc vorbis vorbisenc vorbisfile ogg - ) + ) + # commenting out until libs are updated on svn. schroedinger and orc + # will be removed then + # set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} vpx webp swresample) set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} schroedinger orc vpx webp swresample) set(FFMPEG_LIBPATH ${FFMPEG}/lib) endif() @@ -169,6 +171,8 @@ if(WITH_IMAGE_OPENJPEG OR WITH_CODEC_FFMPEG) set(OPENJPEG ${LIBDIR}/openjpeg) set(WITH_SYSTEM_OPENJPEG ON) set(OPENJPEG_INCLUDE_DIRS ${OPENJPEG}/include) + # same as with ffmpeg libs, update when svn are updated + #set(OPENJPEG_LIBRARIES ${OPENJPEG}/lib/libopenjp2.a) set(OPENJPEG_LIBRARIES ${OPENJPEG}/lib/libopenjpeg.a) endif() diff --git a/build_files/cmake/platform/platform_apple_xcode.cmake b/build_files/cmake/platform/platform_apple_xcode.cmake index 1b8e13a06231..7af69c092cc0 100644 --- a/build_files/cmake/platform/platform_apple_xcode.cmake +++ b/build_files/cmake/platform/platform_apple_xcode.cmake @@ -104,7 +104,7 @@ endif() # 10.9 is our min. target, if you use higher sdk, weak linking happens if(CMAKE_OSX_DEPLOYMENT_TARGET) if(${CMAKE_OSX_DEPLOYMENT_TARGET} VERSION_LESS 10.9) - message(STATUS "Setting deployment target to 10.9, lower versions are incompatible with WITH_CXX11") + message(STATUS "Setting deployment target to 10.9, lower versions are not supported") set(CMAKE_OSX_DEPLOYMENT_TARGET "10.9" CACHE STRING "" FORCE) endif() else() diff --git a/build_files/cmake/platform/platform_unix.cmake b/build_files/cmake/platform/platform_unix.cmake index 0cb0df196dcd..219c703b7003 100644 --- a/build_files/cmake/platform/platform_unix.cmake +++ b/build_files/cmake/platform/platform_unix.cmake @@ -24,13 +24,20 @@ # Libraries configuration for any *nix system including Linux and Unix. # Detect precompiled library directory -set(LIBDIR_NAME ${CMAKE_SYSTEM_NAME}_${CMAKE_SYSTEM_PROCESSOR}) -string(TOLOWER ${LIBDIR_NAME} LIBDIR_NAME) -set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/${LIBDIR_NAME}) +if(NOT DEFINED LIBDIR) + set(LIBDIR_NAME ${CMAKE_SYSTEM_NAME}_${CMAKE_SYSTEM_PROCESSOR}) + string(TOLOWER ${LIBDIR_NAME} LIBDIR_NAME) + set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/${LIBDIR_NAME}) +else() + message(STATUS "Using pre-compiled LIBDIR: ${LIBDIR}") +endif() if(EXISTS ${LIBDIR}) file(GLOB LIB_SUBDIRS ${LIBDIR}/*) - set(CMAKE_PREFIX_PATH ${LIB_SUBDIRS}) + # NOTE: Make sure "proper" compiled zlib comes first before the one + # which is a part of OpenCollada. They have different ABI, and we + # do need to use the official one. + set(CMAKE_PREFIX_PATH ${LIBDIR}/zlib ${LIB_SUBDIRS}) set(WITH_STATIC_LIBS ON) set(WITH_OPENMP_STATIC ON) endif() @@ -354,16 +361,19 @@ if(WITH_OPENCOLORIO) endif() if(WITH_LLVM) - # Symbol conflicts with same UTF library used by OpenCollada if(EXISTS ${LIBDIR}) set(LLVM_STATIC ON) - if(WITH_OPENCOLLADA) - list(REMOVE_ITEM OPENCOLLADA_LIBRARIES ${OPENCOLLADA_UTF_LIBRARY}) - endif() endif() find_package_wrapper(LLVM) + # Symbol conflicts with same UTF library used by OpenCollada + if(EXISTS ${LIBDIR}) + if(WITH_OPENCOLLADA AND (${LLVM_VERSION} VERSION_LESS "4.0.0")) + list(REMOVE_ITEM OPENCOLLADA_LIBRARIES ${OPENCOLLADA_UTF_LIBRARY}) + endif() + endif() + if(NOT LLVM_FOUND) set(WITH_LLVM OFF) message(STATUS "LLVM not found") diff --git a/build_files/cmake/platform/platform_win32.cmake b/build_files/cmake/platform/platform_win32.cmake index 8cc5844fdbcb..636c61e935db 100644 --- a/build_files/cmake/platform/platform_win32.cmake +++ b/build_files/cmake/platform/platform_win32.cmake @@ -131,9 +131,6 @@ include(InstallRequiredSystemLibraries) remove_cc_flag("/MDd" "/MD") if(MSVC_CLANG) # Clangs version of cl doesn't support all flags - if(NOT WITH_CXX11) # C++11 is on by default in clang-cl and can't be turned off, if c++11 is not enabled in blender repress some c++11 related warnings. - set(CXX_WARN_FLAGS "-Wno-inconsistent-missing-override") - endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_WARN_FLAGS} /nologo /J /Gd /EHsc -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference ") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /nologo /J /Gd -Wno-unused-command-line-argument -Wno-microsoft-enum-forward-reference") else() @@ -268,9 +265,7 @@ if(WITH_OPENCOLLADA) ${OPENCOLLADA}/lib/opencollada/ftoa.lib ) - if(NOT WITH_LLVM) - list(APPEND OPENCOLLADA_LIBRARIES ${OPENCOLLADA}/lib/opencollada/UTF.lib) - endif() + list(APPEND OPENCOLLADA_LIBRARIES ${OPENCOLLADA}/lib/opencollada/UTF.lib) set(PCRE_LIBRARIES ${OPENCOLLADA}/lib/opencollada/pcre.lib @@ -285,8 +280,6 @@ if(WITH_CODEC_FFMPEG) windows_find_package(FFMPEG) if(NOT FFMPEG_FOUND) warn_hardcoded_paths(ffmpeg) - set(FFMPEG_LIBRARY_VERSION 57) - set(FFMPEG_LIBRARY_VERSION_AVU 55) set(FFMPEG_LIBRARIES ${LIBDIR}/ffmpeg/lib/avcodec.lib ${LIBDIR}/ffmpeg/lib/avformat.lib @@ -308,16 +301,16 @@ if(WITH_IMAGE_OPENEXR) set(OPENEXR_INCLUDE_DIRS ${OPENEXR_INCLUDE_DIR} ${OPENEXR}/include/OpenEXR) set(OPENEXR_LIBPATH ${OPENEXR}/lib) set(OPENEXR_LIBRARIES - optimized ${OPENEXR_LIBPATH}/Iex-2_2.lib - optimized ${OPENEXR_LIBPATH}/Half.lib - optimized ${OPENEXR_LIBPATH}/IlmImf-2_2.lib - optimized ${OPENEXR_LIBPATH}/Imath-2_2.lib - optimized ${OPENEXR_LIBPATH}/IlmThread-2_2.lib - debug ${OPENEXR_LIBPATH}/Iex-2_2_d.lib - debug ${OPENEXR_LIBPATH}/Half_d.lib - debug ${OPENEXR_LIBPATH}/IlmImf-2_2_d.lib - debug ${OPENEXR_LIBPATH}/Imath-2_2_d.lib - debug ${OPENEXR_LIBPATH}/IlmThread-2_2_d.lib + optimized ${OPENEXR_LIBPATH}/Iex_s.lib + optimized ${OPENEXR_LIBPATH}/Half_s.lib + optimized ${OPENEXR_LIBPATH}/IlmImf_s.lib + optimized ${OPENEXR_LIBPATH}/Imath_s.lib + optimized ${OPENEXR_LIBPATH}/IlmThread_s.lib + debug ${OPENEXR_LIBPATH}/Iex_s_d.lib + debug ${OPENEXR_LIBPATH}/Half_s_d.lib + debug ${OPENEXR_LIBPATH}/IlmImf_s_d.lib + debug ${OPENEXR_LIBPATH}/Imath_s_d.lib + debug ${OPENEXR_LIBPATH}/IlmThread_s_d.lib ) endif() endif() @@ -341,7 +334,7 @@ if(WITH_JACK) endif() if(WITH_PYTHON) - set(PYTHON_VERSION 3.6) # CACHE STRING) + set(PYTHON_VERSION 3.7) # CACHE STRING) string(REPLACE "." "" _PYTHON_VERSION_NO_DOTS ${PYTHON_VERSION}) # Use shared libs for vc2008 and vc2010 until we actually have vc2010 libs @@ -376,14 +369,13 @@ if(WITH_BOOST) warn_hardcoded_paths(BOOST) set(BOOST ${LIBDIR}/boost) set(BOOST_INCLUDE_DIR ${BOOST}/include) - if(MSVC12) - set(BOOST_LIBPATH ${BOOST}/lib) - set(BOOST_POSTFIX "vc120-mt-s-1_60.lib") - set(BOOST_DEBUG_POSTFIX "vc120-mt-sgd-1_60.lib") + set(BOOST_LIBPATH ${BOOST}/lib) + if(CMAKE_CL_64) + set(BOOST_POSTFIX "vc140-mt-s-x64-1_68.lib") + set(BOOST_DEBUG_POSTFIX "vc140-mt-sgd-x64-1_68.lib") else() - set(BOOST_LIBPATH ${BOOST}/lib) - set(BOOST_POSTFIX "vc140-mt-s-1_60.lib") - set(BOOST_DEBUG_POSTFIX "vc140-mt-sgd-1_60.lib") + set(BOOST_POSTFIX "vc140-mt-s-x32-1_68.lib") + set(BOOST_DEBUG_POSTFIX "vc140-mt-sgd-x32-1_68.lib") endif() set(BOOST_LIBRARIES optimized ${BOOST_LIBPATH}/libboost_date_time-${BOOST_POSTFIX} @@ -462,7 +454,14 @@ if(WITH_OPENCOLORIO) set(OPENCOLORIO ${LIBDIR}/opencolorio) set(OPENCOLORIO_INCLUDE_DIRS ${OPENCOLORIO}/include) set(OPENCOLORIO_LIBPATH ${LIBDIR}/opencolorio/lib) - set(OPENCOLORIO_LIBRARIES ${OPENCOLORIO_LIBPATH}/OpenColorIO.lib) + set(OPENCOLORIO_LIBRARIES + optimized ${OPENCOLORIO_LIBPATH}/OpenColorIO.lib + optimized ${OPENCOLORIO_LIBPATH}/tinyxml.lib + optimized ${OPENCOLORIO_LIBPATH}/libyaml-cpp.lib + debug ${OPENCOLORIO_LIBPATH}/OpenColorIO_d.lib + debug ${OPENCOLORIO_LIBPATH}/tinyxml_d.lib + debug ${OPENCOLORIO_LIBPATH}/libyaml-cpp_d.lib + ) set(OPENCOLORIO_DEFINITIONS) endif() @@ -474,7 +473,7 @@ if(WITH_OPENVDB) set(OPENVDB_LIBPATH ${LIBDIR}/openvdb/lib) set(OPENVDB_INCLUDE_DIRS ${OPENVDB}/include ${TBB_INCLUDE_DIR}) set(OPENVDB_LIBRARIES optimized ${OPENVDB_LIBPATH}/openvdb.lib debug ${OPENVDB_LIBPATH}/openvdb_d.lib ${TBB_LIBRARIES} ${BLOSC_LIBRARIES}) - + set(OPENVDB_DEFINITIONS -DNOMINMAX) endif() if(WITH_ALEMBIC) @@ -497,6 +496,12 @@ if(WITH_MOD_CLOTH_ELTOPO) ) endif() +if(WITH_IMAGE_OPENJPEG) + set(OPENJPEG ${LIBDIR}/openjpeg) + set(OPENJPEG_INCLUDE_DIRS ${OPENJPEG}/include/openjpeg-2.3) + set(OPENJPEG_LIBRARIES ${OPENJPEG}/lib/openjp2.lib) +endif() + if(WITH_OPENSUBDIV OR WITH_CYCLES_OPENSUBDIV) set(OPENSUBDIV_INCLUDE_DIR ${LIBDIR}/opensubdiv/include) set(OPENSUBDIV_LIBPATH ${LIBDIR}/opensubdiv/lib) @@ -556,7 +561,7 @@ set(WINTAB_INC ${LIBDIR}/wintab/include) if(WITH_OPENAL) set(OPENAL ${LIBDIR}/openal) set(OPENALDIR ${LIBDIR}/openal) - set(OPENAL_INCLUDE_DIR ${OPENAL}/include) + set(OPENAL_INCLUDE_DIR ${OPENAL}/include/AL) set(OPENAL_LIBPATH ${OPENAL}/lib) if(MSVC) set(OPENAL_LIBRARY ${OPENAL_LIBPATH}/openal32.lib) @@ -591,9 +596,11 @@ if(WITH_CYCLES_OSL) optimized ${OSL_LIB_COMP} optimized ${OSL_LIB_EXEC} optimized ${OSL_LIB_QUERY} + optimized ${CYCLES_OSL}/lib/pugixml.lib debug ${OSL_LIB_EXEC_DEBUG} debug ${OSL_LIB_COMP_DEBUG} debug ${OSL_LIB_QUERY_DEBUG} + debug ${CYCLES_OSL}/lib/pugixml_d.lib ) find_path(OSL_INCLUDE_DIR OSL/oslclosure.h PATHS ${CYCLES_OSL}/include) find_program(OSL_COMPILER NAMES oslc PATHS ${CYCLES_OSL}/bin) diff --git a/build_files/windows/autodetect_msvc.cmd b/build_files/windows/autodetect_msvc.cmd index 6fce3829e7b6..4dbe009a890f 100644 --- a/build_files/windows/autodetect_msvc.cmd +++ b/build_files/windows/autodetect_msvc.cmd @@ -1,17 +1,14 @@ echo No explicit msvc version requested, autodetecting version. -call "%~dp0\detect_msvc2013.cmd" +call "%~dp0\detect_msvc2017.cmd" if %ERRORLEVEL% EQU 0 goto DetectionComplete call "%~dp0\detect_msvc2015.cmd" if %ERRORLEVEL% EQU 0 goto DetectionComplete -call "%~dp0\detect_msvc2017.cmd" -if %ERRORLEVEL% EQU 0 goto DetectionComplete - echo Compiler Detection failed. Use verbose switch for more information. exit /b 1 :DetectionComplete -echo Compiler Detection successfull, detected VS%BUILD_VS_YEAR% +echo Compiler Detection successful, detected VS%BUILD_VS_YEAR% exit /b 0 \ No newline at end of file diff --git a/build_files/windows/check_libraries.cmd b/build_files/windows/check_libraries.cmd index c8aad7c9adb8..90c50293720c 100644 --- a/build_files/windows/check_libraries.cmd +++ b/build_files/windows/check_libraries.cmd @@ -1,4 +1,3 @@ -if "%BUILD_VS_YEAR%"=="2013" set BUILD_VS_LIBDIRPOST=vc12 if "%BUILD_VS_YEAR%"=="2015" set BUILD_VS_LIBDIRPOST=vc14 if "%BUILD_VS_YEAR%"=="2017" set BUILD_VS_LIBDIRPOST=vc14 @@ -37,7 +36,7 @@ if NOT EXIST %BUILD_VS_LIBDIR% ( echo. echo Error: Download of external libraries failed. echo This is needed for building, please manually run 'svn cleanup' and 'svn update' in - echo %BUILD_VS_LIBDIR% , until this is resolved you CANNOT make a successfull blender build + echo %BUILD_VS_LIBDIR% , until this is resolved you CANNOT make a successful blender build echo. exit /b 1 ) diff --git a/build_files/windows/configure_ninja.cmd b/build_files/windows/configure_ninja.cmd index 224d761adf6a..995d8d56fa82 100644 --- a/build_files/windows/configure_ninja.cmd +++ b/build_files/windows/configure_ninja.cmd @@ -59,7 +59,7 @@ if "%MUST_CLEAN%"=="1" ( %CMAKE% cmake --build . --config Clean ) -if NOT EXIST %BUILD_DIR%\Blender.sln set MUST_CONFIGURE=1 +if NOT EXIST %BUILD_DIR%\build.ninja set MUST_CONFIGURE=1 if "%NOBUILD%"=="1" set MUST_CONFIGURE=1 if "%MUST_CONFIGURE%"=="1" ( diff --git a/build_files/windows/detect_msvc2013.cmd b/build_files/windows/detect_msvc2013.cmd deleted file mode 100644 index 5688d31c4b68..000000000000 --- a/build_files/windows/detect_msvc2013.cmd +++ /dev/null @@ -1,3 +0,0 @@ -set BUILD_VS_VER=12 -set BUILD_VS_YEAR=2013 -call "%~dp0\detect_msvc_classic.cmd" \ No newline at end of file diff --git a/build_files/windows/detect_msvc2017.cmd b/build_files/windows/detect_msvc2017.cmd index 060e9f88617a..029f98cbe1ec 100644 --- a/build_files/windows/detect_msvc2017.cmd +++ b/build_files/windows/detect_msvc2017.cmd @@ -2,6 +2,7 @@ if NOT "%verbose%" == "" ( echo Detecting msvc 2017 ) set BUILD_VS_VER=15 +set BUILD_VS_YEAR=2017 set ProgramFilesX86=%ProgramFiles(x86)% if not exist "%ProgramFilesX86%" set ProgramFilesX86=%ProgramFiles% @@ -9,8 +10,8 @@ set vs_where=%ProgramFilesX86%\Microsoft Visual Studio\Installer\vswhere.exe if not exist "%vs_where%" ( if NOT "%verbose%" == "" ( echo Visual Studio 2017 ^(15.2 or newer^) is not detected - goto FAIL ) + goto FAIL ) if NOT "%verbose%" == "" ( diff --git a/build_files/windows/parse_arguments.cmd b/build_files/windows/parse_arguments.cmd index 8a6d743978d8..e8caddaf4ea9 100644 --- a/build_files/windows/parse_arguments.cmd +++ b/build_files/windows/parse_arguments.cmd @@ -59,8 +59,6 @@ if NOT "%1" == "" ( set VSWHERE_ARGS=-products Microsoft.VisualStudio.Product.BuildTools ) else if "%1" == "2015" ( set BUILD_VS_YEAR=2015 - ) else if "%1" == "2013" ( - set BUILD_VS_YEAR=2013 ) else if "%1" == "packagename" ( set BUILD_CMAKE_ARGS=%BUILD_CMAKE_ARGS% -DCPACK_OVERRIDE_PACKAGENAME="%2" shift /1 diff --git a/build_files/windows/show_help.cmd b/build_files/windows/show_help.cmd index 2b297120f4b6..694b28c88ed0 100644 --- a/build_files/windows/show_help.cmd +++ b/build_files/windows/show_help.cmd @@ -22,13 +22,13 @@ echo - packagename [newname] ^(override default cpack package name^) echo - buildir [newdir] ^(override default build folder^) echo - x86 ^(override host auto-detect and build 32 bit code^) echo - x64 ^(override host auto-detect and build 64 bit code^) -echo - 2013 ^(build with visual studio 2013^) -echo. -echo Experimental options -echo - 2015 ^(build with visual studio 2015^) echo - 2017 ^(build with visual studio 2017^) echo - 2017pre ^(build with visual studio 2017 pre-release^) echo - 2017b ^(build with visual studio 2017 Build Tools^) + +echo. +echo Experimental options +echo - 2015 ^(build with visual studio 2015^) echo - clang ^(enable building with clang^) echo - asan ^(enable asan when building with clang^) echo - ninja ^(enable building with ninja instead of msbuild^) diff --git a/doc/blender_file_format/BlendFileDnaExporter_25.py b/doc/blender_file_format/BlendFileDnaExporter_25.py index 64c92c7cf800..a9da79f04d8f 100755 --- a/doc/blender_file_format/BlendFileDnaExporter_25.py +++ b/doc/blender_file_format/BlendFileDnaExporter_25.py @@ -7,7 +7,7 @@ # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -22,21 +22,21 @@ # # Name: # dna.py -# +# # Description: # Creates a browsable DNA output to HTML. -# +# # Author: # Jeroen Bakker -# +# # Version: # v0.1 (12-05-2009) - migration of original source code to python. # Added code to support blender 2.5 branch # v0.2 (25-05-2009) - integrated with BlendFileReader.py -# +# # Input: # blender build executable -# +# # Output: # dna.html # dna.css (will only be created when not existing) @@ -76,12 +76,12 @@ class DNACatalogHTML: DNACatalog is a catalog of all information in the DNA1 file-block ''' - def __init__(self, catalog, bpy_module = None): + def __init__(self, catalog, bpy_module=None): self.Catalog = catalog self.bpy = bpy_module - + def WriteToHTML(self, handle): - + dna_html_template = """ @@ -105,10 +105,10 @@ def WriteToHTML(self, handle): ${structs_content} """ - + header = self.Catalog.Header bpy = self.bpy - + # ${version} and ${revision} if bpy: version = '.'.join(map(str, bpy.app.version)) @@ -116,7 +116,7 @@ def WriteToHTML(self, handle): else: version = str(header.Version) revision = 'Unknown' - + # ${bitness} if header.PointerSize == 8: bitness = '64 bit' @@ -125,10 +125,10 @@ def WriteToHTML(self, handle): # ${endianness} if header.LittleEndianness: - endianess= 'Little endianness' + endianess = 'Little endianness' else: - endianess= 'Big endianness' - + endianess = 'Big endianness' + # ${structs_list} log.debug("Creating structs index") structs_list = '' @@ -136,7 +136,7 @@ def WriteToHTML(self, handle): structureIndex = 0 for structure in self.Catalog.Structs: structs_list += list_item.format(structureIndex, structure.Type.Name) - structureIndex+=1 + structureIndex += 1 # ${structs_content} log.debug("Creating structs content") @@ -144,20 +144,20 @@ def WriteToHTML(self, handle): for structure in self.Catalog.Structs: log.debug(structure.Type.Name) structs_content += self.Structure(structure) - + d = dict( - version = version, - revision = revision, - bitness = bitness, - endianness = endianess, - structs_list = structs_list, - structs_content = structs_content + version=version, + revision=revision, + bitness=bitness, + endianness=endianess, + structs_list=structs_list, + structs_content=structs_content ) dna_html = Template(dna_html_template).substitute(d) dna_html = self.format(dna_html) handle.write(dna_html) - + def Structure(self, structure): struct_table_template = """ @@ -178,23 +178,23 @@ def Structure(self, structure):


""" - + d = dict( - struct_name = structure.Type.Name, - fields = self.StructureFields(structure, None, 0), - size = str(structure.Type.Size) + struct_name=structure.Type.Name, + fields=self.StructureFields(structure, None, 0), + size=str(structure.Type.Size) ) - + struct_table = Template(struct_table_template).substitute(d) return struct_table - + def StructureFields(self, structure, parentReference, offset): fields = '' for field in structure.Fields: fields += self.StructureField(field, structure, parentReference, offset) offset += field.Size(self.Catalog.Header) return fields - + def StructureField(self, field, structure, parentReference, offset): structure_field_template = """ @@ -205,7 +205,7 @@ def StructureField(self, field, structure, parentReference, offset): ${offset} ${size} """ - + if field.Type.Structure is None or field.Name.IsPointer(): # ${reference} @@ -216,37 +216,37 @@ def StructureField(self, field, structure, parentReference, offset): struct = '{0}'.format(structure.Type.Name) else: struct = structure.Type.Name - + # ${type} type = field.Type.Name - + # ${name} name = field.Name.Name - + # ${offset} # offset already set - + # ${size} size = field.Size(self.Catalog.Header) - + d = dict( - reference = reference, - struct = struct, - type = type, - name = name, - offset = offset, - size = size + reference=reference, + struct=struct, + type=type, + name=name, + offset=offset, + size=size ) - + structure_field = Template(structure_field_template).substitute(d) - + elif field.Type.Structure is not None: reference = field.Name.AsReference(parentReference) - structure_field = self.StructureFields(field.Type.Structure, reference, offset) + structure_field = self.StructureFields(field.Type.Structure, reference, offset) return structure_field - def indent(self, input, dent, startswith = ''): + def indent(self, input, dent, startswith=''): output = '' if dent < 0: for line in input.split('\n'): @@ -257,19 +257,19 @@ def indent(self, input, dent, startswith = ''): output += line.lstrip() + '\n' # remove indentation completely elif dent > 0: for line in input.split('\n'): - output += ' '* dent + line + '\n' + output += ' ' * dent + line + '\n' return output - + def format(self, input): diff = { - '\n' :'', - '\n' :'', - '' :' ', - '\n' :'', - '\n' :'', - '\n' :'' + '\n': '', + '\n': '', + '': ' ', + '\n': '', + '\n': '', + '\n': '' } output = self.indent(input, 0) for key, value in diff.items(): @@ -283,17 +283,17 @@ def WriteToCSS(self, handle): ''' css = """ @CHARSET "ISO-8859-1"; - + body { font-family: verdana; font-size: small; } - + div.title { font-size: large; text-align: center; } - + h1 { page-break-before: always; } @@ -304,7 +304,7 @@ def WriteToCSS(self, handle): margin-right: 3%; padding-left: 40px; } - + h1:hover{ background-color: #EBEBEB; } @@ -312,7 +312,7 @@ def WriteToCSS(self, handle): h3 { padding-left: 40px; } - + table { border-width: 1px; border-style: solid; @@ -321,21 +321,21 @@ def WriteToCSS(self, handle): width: 94%; margin: 20px 3% 10px; } - + caption { margin-bottom: 5px; } - + th { background-color: #000000; color:#ffffff; padding-left:5px; padding-right:5px; } - + tr { } - + td { border-width: 1px; border-style: solid; @@ -343,12 +343,12 @@ def WriteToCSS(self, handle): padding-left:5px; padding-right:5px; } - + label { float:right; margin-right: 3%; } - + ul.multicolumn { list-style:none; float:left; @@ -361,18 +361,18 @@ def WriteToCSS(self, handle): width:200px; margin-right:0px; } - + a { color:#a000a0; text-decoration:none; } - + a:hover { color:#a000a0; text-decoration:underline; } """ - + css = self.indent(css, 0) handle.write(css) @@ -389,13 +389,13 @@ def usage(): print("\tdefault: % blender2.5 --background -noaudio --python BlendFileDnaExporter_25.py") print("\twith options: % blender2.5 --background -noaudio --python BlendFileDnaExporter_25.py -- --dna-keep-blend --dna-debug\n") - + ###################################################### # Main ###################################################### def main(): - + import os, os.path try: @@ -408,37 +408,37 @@ def main(): else: filename = 'dna' dir = os.path.dirname(__file__) - Path_Blend = os.path.join(dir, filename + '.blend') # temporary blend file - Path_HTML = os.path.join(dir, filename + '.html') # output html file - Path_CSS = os.path.join(dir, 'dna.css') # output css file + Path_Blend = os.path.join(dir, filename + '.blend') # temporary blend file + Path_HTML = os.path.join(dir, filename + '.html') # output html file + Path_CSS = os.path.join(dir, 'dna.css') # output css file # create a blend file for dna parsing if not os.path.exists(Path_Blend): log.info("1: write temp blend file with SDNA info") log.info(" saving to: " + Path_Blend) try: - bpy.ops.wm.save_as_mainfile(filepath = Path_Blend, copy = True, compress = False) + bpy.ops.wm.save_as_mainfile(filepath=Path_Blend, copy=True, compress=False) except: log.error("Filename {0} does not exist and can't be created... quitting".format(Path_Blend)) return else: log.info("1: found blend file with SDNA info") log.info(" " + Path_Blend) - + # read blend header from blend file log.info("2: read file:") - + if not dir in sys.path: sys.path.append(dir) import BlendFileReader - + handle = BlendFileReader.openBlendFile(Path_Blend) blendfile = BlendFileReader.BlendFile(handle) catalog = DNACatalogHTML(blendfile.Catalog, bpy) # close temp file handle.close() - + # deleting or not? if '--dna-keep-blend' in sys.argv: # keep the blend, useful for studying hexdumps @@ -449,7 +449,7 @@ def main(): log.info("5: close and delete temp blend:") log.info(" {0}".format(Path_Blend)) os.remove(Path_Blend) - + # export dna to xhtml log.info("6: export sdna to xhtml file: %r" % Path_HTML) handleHTML = open(Path_HTML, "w") @@ -466,12 +466,12 @@ def main(): if not bpy.app.background: log.info("7: quit blender") bpy.ops.wm.exit_blender() - + except ImportError: log.warning(" skipping, not running in Blender") usage() sys.exit(2) - + if __name__ == '__main__': main() diff --git a/doc/blender_file_format/BlendFileReader.py b/doc/blender_file_format/BlendFileReader.py index a4d2f494c5b7..d4aed7225788 100644 --- a/doc/blender_file_format/BlendFileReader.py +++ b/doc/blender_file_format/BlendFileReader.py @@ -7,7 +7,7 @@ # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -34,6 +34,7 @@ # module global routines ###################################################### + def ReadString(handle, length): ''' ReadString reads a String of given length or a zero terminating String @@ -45,7 +46,7 @@ def ReadString(handle, length): # length == 0 means we want a zero terminating string result = "" s = ReadString(handle, 1) - while s!="\0": + while s != "\0": result += s s = ReadString(handle, 1) return result @@ -57,7 +58,7 @@ def Read(type, handle, fileheader): ''' def unpacked_bytes(type_char, size): return struct.unpack(fileheader.StructPre + type_char, handle.read(size))[0] - + if type == 'ushort': return unpacked_bytes("H", 2) # unsigned short elif type == 'short': @@ -94,10 +95,10 @@ def openBlendFile(filename): log.debug("decompressing started") fs = gzip.open(filename, "rb") handle = tempfile.TemporaryFile() - data = fs.read(1024*1024) - while data: - handle.write(data) - data = fs.read(1024*1024) + data = fs.read(1024 * 1024) + while data: + handle.write(data) + data = fs.read(1024 * 1024) log.debug("decompressing finished") fs.close() log.debug("resetting decompressed file") @@ -112,7 +113,7 @@ def Align(handle): offset = handle.tell() trim = offset % 4 if trim != 0: - handle.seek(4-trim, os.SEEK_CUR) + handle.seek(4 - trim, os.SEEK_CUR) ###################################################### @@ -121,14 +122,14 @@ def Align(handle): class BlendFile: ''' - Reads a blendfile and store the header, all the fileblocks, and catalogue + Reads a blendfile and store the header, all the fileblocks, and catalogue structs foound in the DNA fileblock - + - BlendFile.Header (BlendFileHeader instance) - BlendFile.Blocks (list of BlendFileBlock instances) - BlendFile.Catalog (DNACatalog instance) ''' - + def __init__(self, handle): log.debug("initializing reading blend-file") self.Header = BlendFileHeader(handle) @@ -141,13 +142,13 @@ def __init__(self, handle): found_dna_block = True else: fileblock.Header.skip(handle) - + self.Blocks.append(fileblock) fileblock = BlendFileBlock(handle, self) - + # appending last fileblock, "ENDB" self.Blocks.append(fileblock) - + # seems unused? """ def FindBlendFileBlocksWithCode(self, code): @@ -164,27 +165,27 @@ class BlendFileHeader: BlendFileHeader allocates the first 12 bytes of a blend file. It contains information about the hardware architecture. Header example: BLENDER_v254 - + BlendFileHeader.Magic (str) BlendFileHeader.PointerSize (int) BlendFileHeader.LittleEndianness (bool) BlendFileHeader.StructPre (str) see http://docs.python.org/py3k/library/struct.html#byte-order-size-and-alignment BlendFileHeader.Version (int) ''' - + def __init__(self, handle): log.debug("reading blend-file-header") - + self.Magic = ReadString(handle, 7) log.debug(self.Magic) - + pointersize = ReadString(handle, 1) log.debug(pointersize) if pointersize == "-": self.PointerSize = 8 if pointersize == "_": self.PointerSize = 4 - + endianness = ReadString(handle, 1) log.debug(endianness) if endianness == "v": @@ -193,11 +194,11 @@ def __init__(self, handle): if endianness == "V": self.LittleEndianness = False self.StructPre = ">" - + version = ReadString(handle, 3) log.debug(version) self.Version = int(version) - + log.debug("{0} {1} {2} {3}".format(self.Magic, self.PointerSize, self.LittleEndianness, version)) @@ -206,11 +207,11 @@ class BlendFileBlock: BlendFileBlock.File (BlendFile) BlendFileBlock.Header (FileBlockHeader) ''' - + def __init__(self, handle, blendfile): self.File = blendfile self.Header = FileBlockHeader(handle, blendfile.Header) - + def Get(self, handle, path): log.debug("find dna structure") dnaIndex = self.Header.SDNAIndex @@ -232,7 +233,7 @@ class FileBlockHeader: Count (int) FileOffset (= file pointer of datablock) ''' - + def __init__(self, handle, fileheader): self.Code = ReadString(handle, 4).strip() if self.Code != "ENDB": @@ -257,28 +258,28 @@ def skip(self, handle): class DNACatalog: ''' DNACatalog is a catalog of all information in the DNA1 file-block - + Header = None Names = None Types = None Structs = None ''' - + def __init__(self, fileheader, handle): log.debug("building DNA catalog") - self.Names=[] - self.Types=[] - self.Structs=[] + self.Names = [] + self.Types = [] + self.Structs = [] self.Header = fileheader - + SDNA = ReadString(handle, 4) - + # names NAME = ReadString(handle, 4) numberOfNames = Read('uint', handle, fileheader) log.debug("building #{0} names".format(numberOfNames)) for i in range(numberOfNames): - name = ReadString(handle,0) + name = ReadString(handle, 0) self.Names.append(DNAName(name)) Align(handle) @@ -287,7 +288,7 @@ def __init__(self, fileheader, handle): numberOfTypes = Read('uint', handle, fileheader) log.debug("building #{0} types".format(numberOfTypes)) for i in range(numberOfTypes): - type = ReadString(handle,0) + type = ReadString(handle, 0) self.Types.append(DNAType(type)) Align(handle) @@ -321,24 +322,24 @@ def __init__(self, fileheader, handle): class DNAName: ''' DNAName is a C-type name stored in the DNA. - + Name = str ''' - + def __init__(self, name): self.Name = name - + def AsReference(self, parent): if parent is None: result = "" else: - result = parent+"." - + result = parent + "." + result = result + self.ShortName() return result def ShortName(self): - result = self.Name; + result = self.Name result = result.replace("*", "") result = result.replace("(", "") result = result.replace(")", "") @@ -346,12 +347,12 @@ def ShortName(self): if Index != -1: result = result[0:Index] return result - + def IsPointer(self): - return self.Name.find("*")>-1 + return self.Name.find("*") > -1 def IsMethodPointer(self): - return self.Name.find("(*")>-1 + return self.Name.find("(*") > -1 def ArraySize(self): result = 1 @@ -360,10 +361,10 @@ def ArraySize(self): while Index != -1: Index2 = Temp.find("]") - result*=int(Temp[Index+1:Index2]) - Temp = Temp[Index2+1:] + result *= int(Temp[Index + 1:Index2]) + Temp = Temp[Index2 + 1:] Index = Temp.find("[") - + return result @@ -375,46 +376,46 @@ class DNAType: Size = int Structure = DNAStructure ''' - + def __init__(self, aName): self.Name = aName - self.Structure=None + self.Structure = None class DNAStructure: ''' DNAType is a C-type structure stored in the DNA - + Type = DNAType Fields = [DNAField] ''' - + def __init__(self, aType): self.Type = aType self.Type.Structure = self - self.Fields=[] - + self.Fields = [] + def GetField(self, header, handle, path): splitted = path.partition(".") name = splitted[0] rest = splitted[2] - offset = 0; + offset = 0 for field in self.Fields: if field.Name.ShortName() == name: - log.debug("found "+name+"@"+str(offset)) + log.debug("found " + name + "@" + str(offset)) handle.seek(offset, os.SEEK_CUR) return field.DecodeField(header, handle, rest) else: offset += field.Size(header) - log.debug("error did not find "+path) + log.debug("error did not find " + path) return None class DNAField: ''' DNAField is a coupled DNAType and DNAName. - + Type = DNAType Name = DNAName ''' @@ -422,25 +423,24 @@ class DNAField: def __init__(self, aType, aName): self.Type = aType self.Name = aName - + def Size(self, header): if self.Name.IsPointer() or self.Name.IsMethodPointer(): - return header.PointerSize*self.Name.ArraySize() + return header.PointerSize * self.Name.ArraySize() else: - return self.Type.Size*self.Name.ArraySize() + return self.Type.Size * self.Name.ArraySize() def DecodeField(self, header, handle, path): if path == "": if self.Name.IsPointer(): return Read('pointer', handle, header) - if self.Type.Name=="int": + if self.Type.Name == "int": return Read('int', handle, header) - if self.Type.Name=="short": + if self.Type.Name == "short": return Read('short', handle, header) - if self.Type.Name=="float": + if self.Type.Name == "float": return Read('float', handle, header) - if self.Type.Name=="char": + if self.Type.Name == "char": return ReadString(handle, self.Name.ArraySize()) else: return self.Type.Structure.GetField(header, handle, path) - diff --git a/doc/manpage/blender.1.py b/doc/manpage/blender.1.py index 52856717b4a2..0890547906a0 100755 --- a/doc/manpage/blender.1.py +++ b/doc/manpage/blender.1.py @@ -42,6 +42,7 @@ def man_format(data): data = data.replace("\t", " ") return data + if len(sys.argv) != 3: import getopt raise getopt.GetoptError("Usage: %s " % sys.argv[0]) diff --git a/doc/python_api/examples/bge.texture.2.py b/doc/python_api/examples/bge.texture.2.py index 96619007fbaa..5125c3d1957b 100644 --- a/doc/python_api/examples/bge.texture.2.py +++ b/doc/python_api/examples/bge.texture.2.py @@ -185,16 +185,16 @@ # Only use those for greater efficiency and compatiblity. # fg_shaders = { - '2vuy' :FragmentShader_2vuy, - '8BitYUV' :FragmentShader_2vuy, - 'v210' :FragmentShader_v210, - '10BitYUV' :FragmentShader_v210, - '8BitBGRA' :FragmentShader_R10l, - 'BGRA' :FragmentShader_R10l, - '8BitARGB' :FragmentShader_R10l, - '10BitRGBXLE':FragmentShader_R10l, - 'R10l' :FragmentShader_R10l - } + '2vuy': FragmentShader_2vuy, + '8BitYUV': FragmentShader_2vuy, + 'v210': FragmentShader_v210, + '10BitYUV': FragmentShader_v210, + '8BitBGRA': FragmentShader_R10l, + 'BGRA': FragmentShader_R10l, + '8BitARGB': FragmentShader_R10l, + '10BitRGBXLE': FragmentShader_R10l, + 'R10l': FragmentShader_R10l +} # @@ -220,6 +220,8 @@ def config_video(obj, format, pixel, is3D=False, mat=0, card=0): # Attach this function to an object that has a material with texture # and call it once to initialize the object # + + def init(cont): # config_video(cont.owner, 'HD720p5994', '8BitBGRA') # config_video(cont.owner, 'HD720p5994', '8BitYUV') diff --git a/doc/python_api/examples/bge.texture.py b/doc/python_api/examples/bge.texture.py index 8b24530b10ab..510736805a28 100644 --- a/doc/python_api/examples/bge.texture.py +++ b/doc/python_api/examples/bge.texture.py @@ -34,7 +34,7 @@ logic.mySources[0] = texture.VideoFFmpeg('movie1.avi') logic.mySources[1] = texture.VideoFFmpeg('movie2.avi') - #And then assign (and reassign) the source during the game + # And then assign (and reassign) the source during the game logic.video.source = logic.mySources[movieSel] # quick off the movie, but it wont play in the background diff --git a/doc/python_api/examples/blf.py b/doc/python_api/examples/blf.py index e288ac9db66c..5e1a2ef64a7d 100644 --- a/doc/python_api/examples/blf.py +++ b/doc/python_api/examples/blf.py @@ -15,6 +15,7 @@ "handler": None, } + def init(): """init function - runs once""" import os diff --git a/doc/python_api/examples/bmesh.ops.1.py b/doc/python_api/examples/bmesh.ops.1.py index b307624467f2..d6a5b1222d81 100644 --- a/doc/python_api/examples/bmesh.ops.1.py +++ b/doc/python_api/examples/bmesh.ops.1.py @@ -10,22 +10,22 @@ # Add a circle XXX, should return all geometry created, not just verts. bmesh.ops.create_circle( - bm, - cap_ends=False, - radius=0.2, - segments=8) + bm, + cap_ends=False, + radius=0.2, + segments=8) # Spin and deal with geometry on side 'a' edges_start_a = bm.edges[:] geom_start_a = bm.verts[:] + edges_start_a ret = bmesh.ops.spin( - bm, - geom=geom_start_a, - angle=math.radians(180.0), - steps=8, - axis=(1.0, 0.0, 0.0), - cent=(0.0, 1.0, 0.0)) + bm, + geom=geom_start_a, + angle=math.radians(180.0), + steps=8, + axis=(1.0, 0.0, 0.0), + cent=(0.0, 1.0, 0.0)) edges_end_a = [ele for ele in ret["geom_last"] if isinstance(ele, bmesh.types.BMEdge)] del ret @@ -33,8 +33,8 @@ # Extrude and create geometry on side 'b' ret = bmesh.ops.extrude_edge_only( - bm, - edges=edges_start_a) + bm, + edges=edges_start_a) geom_extrude_mid = ret["geom"] del ret @@ -45,19 +45,19 @@ edges_extrude_b = [ele for ele in geom_extrude_mid if isinstance(ele, bmesh.types.BMEdge) and ele.is_boundary] bmesh.ops.translate( - bm, - verts=verts_extrude_b, - vec=(0.0, 0.0, 1.0)) + bm, + verts=verts_extrude_b, + vec=(0.0, 0.0, 1.0)) # Create the circle on side 'b' ret = bmesh.ops.spin( - bm, - geom=verts_extrude_b + edges_extrude_b, - angle=-math.radians(180.0), - steps=8, - axis=(1.0, 0.0, 0.0), - cent=(0.0, 1.0, 1.0)) + bm, + geom=verts_extrude_b + edges_extrude_b, + angle=-math.radians(180.0), + steps=8, + axis=(1.0, 0.0, 0.0), + cent=(0.0, 1.0, 1.0)) edges_end_b = [ele for ele in ret["geom_last"] if isinstance(ele, bmesh.types.BMEdge)] del ret @@ -65,30 +65,30 @@ # Bridge the resulting edge loops of both spins 'a & b' bmesh.ops.bridge_loops( - bm, - edges=edges_end_a + edges_end_b) + bm, + edges=edges_end_a + edges_end_b) # Now we have made a links of the chain, make a copy and rotate it # (so this looks something like a chain) ret = bmesh.ops.duplicate( - bm, - geom=bm.verts[:] + bm.edges[:] + bm.faces[:]) + bm, + geom=bm.verts[:] + bm.edges[:] + bm.faces[:]) geom_dupe = ret["geom"] verts_dupe = [ele for ele in geom_dupe if isinstance(ele, bmesh.types.BMVert)] del ret # position the new link bmesh.ops.translate( - bm, - verts=verts_dupe, - vec=(0.0, 0.0, 2.0)) + bm, + verts=verts_dupe, + vec=(0.0, 0.0, 2.0)) bmesh.ops.rotate( - bm, - verts=verts_dupe, - cent=(0.0, 1.0, 0.0), - matrix=mathutils.Matrix.Rotation(math.radians(90.0), 3, 'Z')) + bm, + verts=verts_dupe, + cent=(0.0, 1.0, 0.0), + matrix=mathutils.Matrix.Rotation(math.radians(90.0), 3, 'Z')) # Done with creating the mesh, simply link it into the scene so we can see it diff --git a/doc/python_api/examples/bpy.app.handlers.1.py b/doc/python_api/examples/bpy.app.handlers.1.py index 245ac199d582..34b16c27b869 100644 --- a/doc/python_api/examples/bpy.app.handlers.1.py +++ b/doc/python_api/examples/bpy.app.handlers.1.py @@ -17,4 +17,5 @@ def load_handler(dummy): print("Load Handler:", bpy.data.filepath) + bpy.app.handlers.load_post.append(load_handler) diff --git a/doc/python_api/examples/bpy.app.handlers.py b/doc/python_api/examples/bpy.app.handlers.py index 078f9df77f2e..808115119b99 100644 --- a/doc/python_api/examples/bpy.app.handlers.py +++ b/doc/python_api/examples/bpy.app.handlers.py @@ -11,4 +11,5 @@ def my_handler(scene): print("Frame Change", scene.frame_current) + bpy.app.handlers.frame_change_pre.append(my_handler) diff --git a/doc/python_api/examples/bpy.app.translations.py b/doc/python_api/examples/bpy.app.translations.py index 4256147ef311..d18344f43be7 100644 --- a/doc/python_api/examples/bpy.app.translations.py +++ b/doc/python_api/examples/bpy.app.translations.py @@ -54,19 +54,19 @@ "Copyright (C) 2013 The Blender Foundation.", "This file is distributed under the same license as the Blender package.", "FIRST AUTHOR , YEAR."))), - ), + ), (("Operator", "Render: Copy Settings"), (("bpy.types.SCENE_OT_render_copy_settings",), ()), ("fr_FR", "Rendu : copier réglages", (False, ())), - ), + ), (("*", "Copy render settings from current scene to others"), (("bpy.types.SCENE_OT_render_copy_settings",), ()), ("fr_FR", "Copier les réglages de rendu depuis la scène courante vers d’autres", (False, ())), - ), + ), # ... etc, all messages from your addon. ) @@ -81,6 +81,7 @@ # Define remaining addon (operators, UI...) here. + def register(): # Usual operator/UI/etc. registration... diff --git a/doc/python_api/examples/bpy.props.2.py b/doc/python_api/examples/bpy.props.2.py index ec9c838f5f22..aeb3bab65b41 100644 --- a/doc/python_api/examples/bpy.props.2.py +++ b/doc/python_api/examples/bpy.props.2.py @@ -14,6 +14,7 @@ class MaterialSettings(bpy.types.PropertyGroup): my_float = bpy.props.FloatProperty() my_string = bpy.props.StringProperty() + bpy.utils.register_class(MaterialSettings) bpy.types.Material.my_settings = \ diff --git a/doc/python_api/examples/bpy.props.3.py b/doc/python_api/examples/bpy.props.3.py index 807edde8f589..340618e5ca43 100644 --- a/doc/python_api/examples/bpy.props.3.py +++ b/doc/python_api/examples/bpy.props.3.py @@ -14,6 +14,7 @@ class SceneSettingItem(bpy.types.PropertyGroup): name = bpy.props.StringProperty(name="Test Prop", default="Unknown") value = bpy.props.IntProperty(name="Test Prop", default=22) + bpy.utils.register_class(SceneSettingItem) bpy.types.Scene.my_settings = \ diff --git a/doc/python_api/examples/bpy.props.4.py b/doc/python_api/examples/bpy.props.4.py index 2b44d94f72a7..daab18c89869 100644 --- a/doc/python_api/examples/bpy.props.4.py +++ b/doc/python_api/examples/bpy.props.4.py @@ -14,6 +14,7 @@ def update_func(self, context): print("my test function", self) + bpy.types.Scene.testprop = bpy.props.FloatProperty(update=update_func) bpy.context.scene.testprop = 11.0 diff --git a/doc/python_api/examples/bpy.props.5.py b/doc/python_api/examples/bpy.props.5.py index a9e79fa02724..c428b4743f86 100644 --- a/doc/python_api/examples/bpy.props.5.py +++ b/doc/python_api/examples/bpy.props.5.py @@ -19,6 +19,7 @@ def get_float(self): def set_float(self, value): self["testprop"] = value + bpy.types.Scene.test_float = bpy.props.FloatProperty(get=get_float, set=set_float) @@ -27,6 +28,7 @@ def get_date(self): import datetime return str(datetime.datetime.now()) + bpy.types.Scene.test_date = bpy.props.StringProperty(get=get_date) @@ -40,6 +42,7 @@ def get_array(self): def set_array(self, values): self["somebool"] = values[0] and values[1] + bpy.types.Scene.test_array = bpy.props.BoolVectorProperty(size=2, get=get_array, set=set_array) @@ -50,7 +53,7 @@ def set_array(self, values): ("GREEN", "Green", "", 2), ("BLUE", "Blue", "", 3), ("YELLOW", "Yellow", "", 4), - ] +] def get_enum(self): @@ -61,6 +64,7 @@ def get_enum(self): def set_enum(self, value): print("setting value", value) + bpy.types.Scene.test_enum = bpy.props.EnumProperty(items=test_items, get=get_enum, set=set_enum) diff --git a/doc/python_api/examples/bpy.types.AddonPreferences.1.py b/doc/python_api/examples/bpy.types.AddonPreferences.1.py index e478ba9b19a5..e6c720e0fadd 100644 --- a/doc/python_api/examples/bpy.types.AddonPreferences.1.py +++ b/doc/python_api/examples/bpy.types.AddonPreferences.1.py @@ -9,7 +9,7 @@ "wiki_url": "", "tracker_url": "", "category": "Object", - } +} import bpy @@ -23,17 +23,17 @@ class ExampleAddonPreferences(AddonPreferences): bl_idname = __name__ filepath = StringProperty( - name="Example File Path", - subtype='FILE_PATH', - ) + name="Example File Path", + subtype='FILE_PATH', + ) number = IntProperty( - name="Example Number", - default=4, - ) + name="Example Number", + default=4, + ) boolean = BoolProperty( - name="Example Boolean", - default=False, - ) + name="Example Boolean", + default=False, + ) def draw(self, context): layout = self.layout diff --git a/doc/python_api/examples/bpy.types.Menu.2.py b/doc/python_api/examples/bpy.types.Menu.2.py index 50460f65b3d1..a1cce0c3ce2c 100644 --- a/doc/python_api/examples/bpy.types.Menu.2.py +++ b/doc/python_api/examples/bpy.types.Menu.2.py @@ -14,4 +14,5 @@ def menu_draw(self, context): self.layout.operator("wm.save_homefile") + bpy.types.INFO_MT_file.append(menu_draw) diff --git a/doc/python_api/examples/bpy.types.Menu.3.py b/doc/python_api/examples/bpy.types.Menu.3.py index 47c81366db46..9fe39535bbfb 100644 --- a/doc/python_api/examples/bpy.types.Menu.3.py +++ b/doc/python_api/examples/bpy.types.Menu.3.py @@ -32,7 +32,7 @@ class AddPresetObjectDraw(AddPresetBase, Operator): # variable used for all preset values preset_defines = [ "obj = bpy.context.object" - ] + ] # properties to store in the preset preset_values = [ @@ -42,7 +42,7 @@ class AddPresetObjectDraw(AddPresetBase, Operator): "obj.show_name", "obj.show_axis", "obj.show_wire", - ] + ] # where to store the preset preset_subdir = "object/draw" @@ -61,7 +61,7 @@ def panel_func(self, context): classes = ( OBJECT_MT_draw_presets, AddPresetObjectDraw, - ) +) def register(): diff --git a/doc/python_api/examples/bpy.types.Menu.4.py b/doc/python_api/examples/bpy.types.Menu.4.py index 04ceb6654dab..869def8bfe03 100644 --- a/doc/python_api/examples/bpy.types.Menu.4.py +++ b/doc/python_api/examples/bpy.types.Menu.4.py @@ -60,6 +60,7 @@ def menu_func(self, context): layout.separator() layout.operator(WM_OT_button_context_test.bl_idname) + classes = ( WM_OT_button_context_test, WM_MT_button_context, @@ -77,5 +78,6 @@ def unregister(): bpy.utils.unregister_class(cls) bpy.types.WM_MT_button_context.remove(menu_func) + if __name__ == "__main__": register() diff --git a/doc/python_api/examples/bpy.types.NodeTree.py b/doc/python_api/examples/bpy.types.NodeTree.py index da2986636ea8..e969c1a41dcd 100644 --- a/doc/python_api/examples/bpy.types.NodeTree.py +++ b/doc/python_api/examples/bpy.types.NodeTree.py @@ -21,4 +21,5 @@ class CyclesNodeTree(bpy.types.NodeTree): def poll(cls, context): return context.scene.render.engine == 'CYCLES' + bpy.utils.register_class(CyclesNodeTree) diff --git a/doc/python_api/examples/bpy.types.Operator.1.py b/doc/python_api/examples/bpy.types.Operator.1.py index 1ba13c040baa..f09ae9690017 100644 --- a/doc/python_api/examples/bpy.types.Operator.1.py +++ b/doc/python_api/examples/bpy.types.Operator.1.py @@ -42,6 +42,7 @@ def invoke(self, context, event): self.y = event.mouse_y return self.execute(context) + bpy.utils.register_class(SimpleMouseOperator) # Test call to the newly defined operator. diff --git a/doc/python_api/examples/bpy.types.Operator.2.py b/doc/python_api/examples/bpy.types.Operator.2.py index e2f9a3a84c45..d1f0edf15aaa 100644 --- a/doc/python_api/examples/bpy.types.Operator.2.py +++ b/doc/python_api/examples/bpy.types.Operator.2.py @@ -42,6 +42,7 @@ def menu_func(self, context): self.layout.operator_context = 'INVOKE_DEFAULT' self.layout.operator(ExportSomeData.bl_idname, text="Text Export Operator") + # Register and add to the file selector bpy.utils.register_class(ExportSomeData) bpy.types.INFO_MT_file_export.append(menu_func) diff --git a/doc/python_api/examples/bpy.types.Operator.4.py b/doc/python_api/examples/bpy.types.Operator.4.py index e5bc6e5c70da..90d1157343df 100644 --- a/doc/python_api/examples/bpy.types.Operator.4.py +++ b/doc/python_api/examples/bpy.types.Operator.4.py @@ -41,6 +41,7 @@ def draw(self, context): col.prop(self, "my_string") + bpy.utils.register_class(CustomDrawOperator) # test call diff --git a/doc/python_api/examples/bpy.types.Operator.py b/doc/python_api/examples/bpy.types.Operator.py index 4baa9380aa60..c9bf169f73e9 100644 --- a/doc/python_api/examples/bpy.types.Operator.py +++ b/doc/python_api/examples/bpy.types.Operator.py @@ -22,6 +22,7 @@ def execute(self, context): print("Hello World") return {'FINISHED'} + bpy.utils.register_class(HelloWorldOperator) # test call to the newly defined operator diff --git a/doc/python_api/examples/bpy.types.PropertyGroup.py b/doc/python_api/examples/bpy.types.PropertyGroup.py index 2c2aa6d9b11c..974142a79b23 100644 --- a/doc/python_api/examples/bpy.types.PropertyGroup.py +++ b/doc/python_api/examples/bpy.types.PropertyGroup.py @@ -31,6 +31,7 @@ class MyPropertyGroup(bpy.types.PropertyGroup): custom_1 = bpy.props.FloatProperty(name="My Float") custom_2 = bpy.props.IntProperty(name="My Int") + bpy.utils.register_class(MyPropertyGroup) bpy.types.Object.my_prop_grp = bpy.props.PointerProperty(type=MyPropertyGroup) diff --git a/doc/python_api/examples/bpy.types.WindowManager.popup_menu.py b/doc/python_api/examples/bpy.types.WindowManager.popup_menu.py index 8d2e101be5f1..e6329f677f70 100644 --- a/doc/python_api/examples/bpy.types.WindowManager.popup_menu.py +++ b/doc/python_api/examples/bpy.types.WindowManager.popup_menu.py @@ -10,4 +10,5 @@ def draw(self, context): self.layout.label("Hello World") + bpy.context.window_manager.popup_menu(draw, title="Greeting", icon='INFO') diff --git a/doc/python_api/examples/bpy.types.bpy_struct.keyframe_insert.1.py b/doc/python_api/examples/bpy.types.bpy_struct.keyframe_insert.1.py index 6889fe75277f..d46ffcc8373e 100644 --- a/doc/python_api/examples/bpy.types.bpy_struct.keyframe_insert.1.py +++ b/doc/python_api/examples/bpy.types.bpy_struct.keyframe_insert.1.py @@ -12,6 +12,7 @@ class MyPropGroup(bpy.types.PropertyGroup): nested = bpy.props.FloatProperty(name="Nested", default=0.0) + # register it so its available for all bones bpy.utils.register_class(MyPropGroup) bpy.types.Bone.my_prop = PointerProperty(type=MyPropGroup, diff --git a/doc/python_api/examples/gpu.offscreen.1.py b/doc/python_api/examples/gpu.offscreen.1.py index 75ddf804e707..b4eb7452ca1b 100644 --- a/doc/python_api/examples/gpu.offscreen.1.py +++ b/doc/python_api/examples/gpu.offscreen.1.py @@ -23,9 +23,9 @@ def draw_callback_px(self, context): @staticmethod def handle_add(self, context): OffScreenDraw._handle_draw = bpy.types.SpaceView3D.draw_handler_add( - self.draw_callback_px, (self, context), - 'WINDOW', 'POST_PIXEL', - ) + self.draw_callback_px, (self, context), + 'WINDOW', 'POST_PIXEL', + ) @staticmethod def handle_remove(): @@ -57,19 +57,19 @@ def _update_offscreen(context, offscreen): modelview_matrix = camera.matrix_world.inverted() projection_matrix = camera.calc_matrix_camera( - render.resolution_x, - render.resolution_y, - render.pixel_aspect_x, - render.pixel_aspect_y, - ) + render.resolution_x, + render.resolution_y, + render.pixel_aspect_x, + render.pixel_aspect_y, + ) offscreen.draw_view3d( - scene, - context.space_data, - context.region, - projection_matrix, - modelview_matrix, - ) + scene, + context.space_data, + context.region, + projection_matrix, + modelview_matrix, + ) @staticmethod def _opengl_draw(context, texture, aspect_ratio, scale): diff --git a/doc/python_api/sphinx_doc_gen.py b/doc/python_api/sphinx_doc_gen.py index 50b07cabff4f..93ffad12bd62 100644 --- a/doc/python_api/sphinx_doc_gen.py +++ b/doc/python_api/sphinx_doc_gen.py @@ -73,6 +73,8 @@ def rna_info_BuildRNAInfo_cache(): if rna_info_BuildRNAInfo_cache.ret is None: rna_info_BuildRNAInfo_cache.ret = rna_info.BuildRNAInfo() return rna_info_BuildRNAInfo_cache.ret + + rna_info_BuildRNAInfo_cache.ret = None # --- end rna_info cache @@ -431,7 +433,7 @@ def handle_args(): BLENDER_VERSION_DOTS = ".".join(blender_version_strings) if BLENDER_REVISION != "Unknown": # '2.62a SHA1' (release) or '2.62.1 SHA1' (non-release) - BLENDER_VERSION_DOTS += " " + BLENDER_REVISION + BLENDER_VERSION_DOTS += " " + BLENDER_REVISION if is_release: # '2_62a_release' @@ -513,6 +515,8 @@ def escape_rst(text): """ Escape plain text which may contain characters used by RST. """ return text.translate(escape_rst.trans) + + escape_rst.trans = str.maketrans({ "`": "\\`", "|": "\\|", @@ -1015,6 +1019,7 @@ def module_grouping_sort_key(name): file.close() + # Changes in Blender will force errors here context_type_map = { "active_base": ("ObjectBase", False), diff --git a/doc/python_api/sphinx_doc_gen_monkeypatch.py b/doc/python_api/sphinx_doc_gen_monkeypatch.py index 9fdbf613d96a..58d09f71e9af 100644 --- a/doc/python_api/sphinx_doc_gen_monkeypatch.py +++ b/doc/python_api/sphinx_doc_gen_monkeypatch.py @@ -21,7 +21,7 @@ # bpy_types_Operator_bl_property__doc__ = ( -""" + """ The name of a property to use as this operators primary property. Currently this is only used to select the default property when expanding an operator into a menu. diff --git a/doc/python_api/sphinx_doc_update.py b/doc/python_api/sphinx_doc_update.py index 561e58dec66a..af44137aca46 100755 --- a/doc/python_api/sphinx_doc_update.py +++ b/doc/python_api/sphinx_doc_update.py @@ -29,7 +29,7 @@ Example usage: - ./sphinx_doc_update.py --mirror ../../../docs/remote_api_backup/ --source ../.. --blender ../../../build_cmake/bin/blender --user foobar --password barfoo + ./sphinx_doc_update.py --mirror ../../../docs/remote_api_backup/ --source ../.. --blender ../../../build_cmake/bin/blender --user foobar --password barfoo """ @@ -107,14 +107,16 @@ def main(): with tempfile.TemporaryDirectory() as tmp_dir: # II) Generate doc source in temp dir. - doc_gen_cmd = (args.blender, "--background", "-noaudio", "--factory-startup", "--python-exit-code", "1", - "--python", "%s/doc/python_api/sphinx_doc_gen.py" % args.source_dir, "--", - "--output", tmp_dir) + doc_gen_cmd = ( + args.blender, "--background", "-noaudio", "--factory-startup", "--python-exit-code", "1", + "--python", "%s/doc/python_api/sphinx_doc_gen.py" % args.source_dir, "--", + "--output", tmp_dir + ) subprocess.run(doc_gen_cmd) # III) Get Blender version info. getver_file = os.path.join(tmp_dir, "blendver.txt") - getver_script = ("" + getver_script = ( "import sys, bpy\n" "with open(sys.argv[-1], 'w') as f:\n" " is_release = bpy.app.version_cycle in {'rc', 'release'}\n" @@ -124,7 +126,8 @@ def main(): " f.write('%d.%d%s\\n' % (bpy.app.version[0], bpy.app.version[1], bpy.app.version_char)\n" " if is_release else '%s\\n' % branch)\n" " f.write('%d_%d%s_release' % (bpy.app.version[0], bpy.app.version[1], bpy.app.version_char)\n" - " if is_release else '%d_%d_%d' % bpy.app.version)\n") + " if is_release else '%d_%d_%d' % bpy.app.version)\n" + ) get_ver_cmd = (args.blender, "--background", "-noaudio", "--factory-startup", "--python-exit-code", "1", "--python-expr", getver_script, "--", getver_file) subprocess.run(get_ver_cmd) diff --git a/extern/rangetree/CMakeLists.txt b/extern/rangetree/CMakeLists.txt index e8e9b15f8b13..77c293e851ab 100644 --- a/extern/rangetree/CMakeLists.txt +++ b/extern/rangetree/CMakeLists.txt @@ -28,4 +28,3 @@ set(SRC ) blender_add_lib(extern_rangetree "${SRC}" "${INC}" "") - diff --git a/extern/recastnavigation/CMakeLists.txt b/extern/recastnavigation/CMakeLists.txt index 19ac6e9dde81..150926317378 100644 --- a/extern/recastnavigation/CMakeLists.txt +++ b/extern/recastnavigation/CMakeLists.txt @@ -25,7 +25,7 @@ remove_cc_flag_unsigned_char() -set(INC +set(INC Recast/Include Detour/Include ) @@ -34,7 +34,7 @@ set(INC_SYS ) -set(SRC +set(SRC recast-capi.cpp recast-capi.h diff --git a/extern/xdnd/xdnd.c b/extern/xdnd/xdnd.c index 50d1fec49698..e8c51377e278 100644 --- a/extern/xdnd/xdnd.c +++ b/extern/xdnd/xdnd.c @@ -121,10 +121,10 @@ char *xdnd_debug_milliseconds (void) #define dnd_debug3(a,b,c) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds (), b, c) #define dnd_debug4(a,b,c,d) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds (), b, c, d) #else -#define dnd_debug1(a) -#define dnd_debug2(a,b) -#define dnd_debug3(a,b,c) -#define dnd_debug4(a,b,c,d) +#define dnd_debug1(a) do {} while (0) +#define dnd_debug2(a,b) do {} while (0) +#define dnd_debug3(a,b,c) do {} while (0) +#define dnd_debug4(a,b,c,d) do {} while (0) #endif #define dnd_warning(a) fprintf (stderr, a) diff --git a/intern/audaspace/CMakeLists.txt b/intern/audaspace/CMakeLists.txt index dd446613fd0b..93dd4d6ac102 100644 --- a/intern/audaspace/CMakeLists.txt +++ b/intern/audaspace/CMakeLists.txt @@ -243,7 +243,7 @@ if(WITH_CODEC_FFMPEG) ffmpeg/AUD_FFMPEGWriter.h ) - remove_strict_flags_file( + remove_strict_cxx_flags_file( ffmpeg/AUD_FFMPEGFactory.cpp ffmpeg/AUD_FFMPEGReader.cpp ffmpeg/AUD_FFMPEGWriter.cpp @@ -294,7 +294,7 @@ if(WITH_JACK) jack/AUD_JackDevice.h jack/AUD_JackLibrary.h - ) + ) if(WITH_JACK_DYNLOAD) add_definitions(-DWITH_JACK_DYNLOAD) diff --git a/intern/audaspace/OpenAL/AUD_OpenALDevice.h b/intern/audaspace/OpenAL/AUD_OpenALDevice.h index f0e478249671..4fe7a5dcf390 100644 --- a/intern/audaspace/OpenAL/AUD_OpenALDevice.h +++ b/intern/audaspace/OpenAL/AUD_OpenALDevice.h @@ -37,8 +37,8 @@ #include "AUD_Buffer.h" //struct AUD_OpenALBufferedFactory; -#include -#include +#include +#include #include #include diff --git a/intern/clog/clog.c b/intern/clog/clog.c index 2e5201d63b04..f64e7c19a5fa 100644 --- a/intern/clog/clog.c +++ b/intern/clog/clog.c @@ -470,7 +470,7 @@ void CLG_logf( static void CLG_ctx_output_set(CLogContext *ctx, void *file_handle) { ctx->output_file = file_handle; - ctx->output = fileno(file_handle); + ctx->output = fileno(ctx->output_file); #if defined(__unix__) || defined(__APPLE__) ctx->use_color = isatty(ctx->output); #endif @@ -559,7 +559,7 @@ static void CLG_ctx_free(CLogContext *ctx) * \{ */ /* We could support multiple at once, for now this seems not needed. */ -struct CLogContext *g_ctx = NULL; +static struct CLogContext *g_ctx = NULL; void CLG_init(void) { diff --git a/intern/cycles/CMakeLists.txt b/intern/cycles/CMakeLists.txt index 233bc639fd8d..0147a4306f46 100644 --- a/intern/cycles/CMakeLists.txt +++ b/intern/cycles/CMakeLists.txt @@ -200,6 +200,9 @@ endif() if(WITH_CYCLES_OSL) add_definitions(-DWITH_OSL) + #osl 1.9.x + add_definitions(-DOSL_STATIC_BUILD) + #pre 1.9 add_definitions(-DOSL_STATIC_LIBRARY) include_directories( SYSTEM @@ -224,31 +227,6 @@ endif() # TODO(sergey): Consider removing it, only causes confusion in interface. set(WITH_CYCLES_DEVICE_MULTI TRUE) -if(CYCLES_STANDALONE_REPOSITORY) - TEST_UNORDERED_MAP_SUPPORT() -endif() -if(WITH_CXX11) - add_definitions(-DCYCLES_STD_UNORDERED_MAP) -elseif(HAVE_STD_UNORDERED_MAP_HEADER) - if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE) - add_definitions(-DCYCLES_STD_UNORDERED_MAP) - else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - add_definitions(-DCYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) - else() - add_definitions(-DCYCLES_NO_UNORDERED_MAP) - message(STATUS "Replacing unordered_map/set with map/set (warning: slower!)") - endif() - endif() -else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - add_definitions(-DCYCLES_TR1_UNORDERED_MAP) - else() - add_definitions(-DCYCLES_NO_UNORDERED_MAP) - message(STATUS "Replacing unordered_map/set with map/set (warning: slower!)") - endif() -endif() - # Logging capabilities using GLog library. if(WITH_CYCLES_LOGGING) add_definitions(-DWITH_CYCLES_LOGGING) @@ -355,4 +333,3 @@ endif() if(NOT WITH_BLENDER AND WITH_CYCLES_STANDALONE) delayed_do_install(${CMAKE_BINARY_DIR}/bin) endif() - diff --git a/intern/cycles/app/cycles_cubin_cc.cpp b/intern/cycles/app/cycles_cubin_cc.cpp index 3c83bf2dae3a..da8ca53c8dfc 100644 --- a/intern/cycles/app/cycles_cubin_cc.cpp +++ b/intern/cycles/app/cycles_cubin_cc.cpp @@ -159,12 +159,11 @@ bool link_ptxas(CompilationSettings &settings) " --gpu-name sm_" + std::to_string(settings.target_arch) + " -m" + std::to_string(settings.bits); - if (settings.verbose) - { + if(settings.verbose) { ptx += " --verbose"; printf("%s\n", ptx.c_str()); } - + int pxresult = system(ptx.c_str()); if(pxresult) { fprintf(stderr, "Error: ptxas failed (%x)\n\n", pxresult); diff --git a/intern/cycles/app/cycles_server.cpp b/intern/cycles/app/cycles_server.cpp index e65b9d769e46..e2166473aa3a 100644 --- a/intern/cycles/app/cycles_server.cpp +++ b/intern/cycles/app/cycles_server.cpp @@ -112,4 +112,3 @@ int main(int argc, const char **argv) return 0; } - diff --git a/intern/cycles/app/cycles_standalone.cpp b/intern/cycles/app/cycles_standalone.cpp index c682744f5faf..1ec8d18f410d 100644 --- a/intern/cycles/app/cycles_standalone.cpp +++ b/intern/cycles/app/cycles_standalone.cpp @@ -524,4 +524,3 @@ int main(int argc, const char **argv) return 0; } - diff --git a/intern/cycles/app/cycles_xml.cpp b/intern/cycles/app/cycles_xml.cpp index a46955322e38..895a83818df0 100644 --- a/intern/cycles/app/cycles_xml.cpp +++ b/intern/cycles/app/cycles_xml.cpp @@ -184,7 +184,7 @@ static bool xml_equal_string(xml_node node, const char *name, const char *value) if(attr) return string_iequals(attr.value(), value); - + return false; } @@ -697,4 +697,3 @@ void xml_read_file(Scene *scene, const char *filepath) } CCL_NAMESPACE_END - diff --git a/intern/cycles/app/io_export_cycles_xml.py b/intern/cycles/app/io_export_cycles_xml.py index 7d6d85f88af5..816536c00712 100644 --- a/intern/cycles/app/io_export_cycles_xml.py +++ b/intern/cycles/app/io_export_cycles_xml.py @@ -39,7 +39,7 @@ def write(node, fname): f = open(fname, "w") f.write(s) - + class CyclesXMLSettings(bpy.types.PropertyGroup): @classmethod def register(cls): @@ -53,11 +53,11 @@ def register(cls): maxlen=256, default='', subtype='FILE_PATH') - + @classmethod def unregister(cls): del bpy.types.Scene.cycles_xml - + # User Interface Drawing Code class RenderButtonsPanel(): bl_space_type = 'PROPERTIES' @@ -75,13 +75,13 @@ class PHYSICS_PT_fluid_export(RenderButtonsPanel, bpy.types.Panel): def draw(self, context): layout = self.layout - + cycles = context.scene.cycles_xml - + #layout.prop(cycles, "filepath") layout.operator("export_mesh.cycles_xml") - + # Export Operator class ExportCyclesXML(bpy.types.Operator, ExportHelper): bl_idname = "export_mesh.cycles_xml" @@ -118,23 +118,23 @@ def execute(self, context): P += "%f %f %f " % (v.co[0], v.co[1], v.co[2]) verts_and_uvs = zip(mesh.tessfaces, mesh.tessface_uv_textures.active.data) - + for f, uvf in verts_and_uvs: vcount = len(f.vertices) nverts += str(vcount) + " " for v in f.vertices: verts += str(v) + " " - + uvs += str(uvf.uv1[0]) + " " + str(uvf.uv1[1]) + " " uvs += str(uvf.uv2[0]) + " " + str(uvf.uv2[1]) + " " uvs += str(uvf.uv3[0]) + " " + str(uvf.uv3[1]) + " " if vcount==4: uvs += " " + str(uvf.uv4[0]) + " " + str(uvf.uv4[1]) + " " - + node = etree.Element('mesh', attrib={'nverts': nverts.strip(), 'verts': verts.strip(), 'P': P, 'UV' : uvs.strip()}) - + # write to file write(node, filepath) @@ -148,5 +148,3 @@ def unregister(): if __name__ == "__main__": register() - - diff --git a/intern/cycles/blender/CMakeLists.txt b/intern/cycles/blender/CMakeLists.txt index ae4977aaed03..9a26ce86bc95 100644 --- a/intern/cycles/blender/CMakeLists.txt +++ b/intern/cycles/blender/CMakeLists.txt @@ -39,7 +39,7 @@ set(SRC set(ADDON_FILES addon/__init__.py - addon/engine.py + addon/engine.py addon/osl.py addon/presets.py addon/properties.py @@ -63,4 +63,3 @@ endif() add_dependencies(bf_intern_cycles bf_rna) delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${ADDON_FILES}" ${CYCLES_INSTALL_PATH}) - diff --git a/intern/cycles/blender/addon/__init__.py b/intern/cycles/blender/addon/__init__.py index a2d6262fb208..038126278aa5 100644 --- a/intern/cycles/blender/addon/__init__.py +++ b/intern/cycles/blender/addon/__init__.py @@ -45,9 +45,9 @@ import bpy from . import ( - engine, - version_update, - ) + engine, + version_update, +) class CyclesRender(bpy.types.RenderEngine): diff --git a/intern/cycles/blender/addon/engine.py b/intern/cycles/blender/addon/engine.py index 1f97eff9bd0f..87dcbe486c72 100644 --- a/intern/cycles/blender/addon/engine.py +++ b/intern/cycles/blender/addon/engine.py @@ -52,7 +52,9 @@ def _workaround_buggy_drivers(): def _configure_argument_parser(): import argparse - parser = argparse.ArgumentParser(description="Cycles Addon argument parser") + # No help because it conflicts with general Python scripts argument parsing + parser = argparse.ArgumentParser(description="Cycles Addon argument parser", + add_help=False) parser.add_argument("--cycles-resumable-num-chunks", help="Number of chunks to split sample range into", default=None) @@ -65,6 +67,9 @@ def _configure_argument_parser(): parser.add_argument("--cycles-resumable-end-chunk", help="End chunk to render", default=None) + parser.add_argument("--cycles-print-stats", + help="Print rendering statistics to stderr", + action='store_true') return parser @@ -82,15 +87,20 @@ def _parse_command_line(): if args.cycles_resumable_current_chunk is not None: import _cycles _cycles.set_resumable_chunk( - int(args.cycles_resumable_num_chunks), - int(args.cycles_resumable_current_chunk)) + int(args.cycles_resumable_num_chunks), + int(args.cycles_resumable_current_chunk), + ) elif args.cycles_resumable_start_chunk is not None and \ - args.cycles_resumable_end_chunk: + args.cycles_resumable_end_chunk: import _cycles _cycles.set_resumable_chunk_range( - int(args.cycles_resumable_num_chunks), - int(args.cycles_resumable_start_chunk), - int(args.cycles_resumable_end_chunk)) + int(args.cycles_resumable_num_chunks), + int(args.cycles_resumable_start_chunk), + int(args.cycles_resumable_end_chunk), + ) + if args.cycles_print_stats: + import _cycles + _cycles.enable_print_stats() def init(): @@ -206,6 +216,7 @@ def system_info(): import _cycles return _cycles.system_info() + def register_passes(engine, scene, srl): engine.register_pass(scene, srl, "Combined", 4, "RGBA", 'COLOR') @@ -254,3 +265,10 @@ def register_passes(engine, scene, srl): engine.register_pass(scene, srl, "Denoising Shadow B", 3, "XYV", 'VECTOR') engine.register_pass(scene, srl, "Denoising Image", 3, "RGB", 'COLOR') engine.register_pass(scene, srl, "Denoising Image Variance", 3, "RGB", 'COLOR') + + clean_options = ("denoising_diffuse_direct", "denoising_diffuse_indirect", + "denoising_glossy_direct", "denoising_glossy_indirect", + "denoising_transmission_direct", "denoising_transmission_indirect", + "denoising_subsurface_direct", "denoising_subsurface_indirect") + if any(getattr(crl, option) for option in clean_options): + engine.register_pass(scene, srl, "Denoising Clean", 3, "RGB", 'COLOR') diff --git a/intern/cycles/blender/addon/properties.py b/intern/cycles/blender/addon/properties.py index 4484dcfbfd74..80b83c940123 100644 --- a/intern/cycles/blender/addon/properties.py +++ b/intern/cycles/blender/addon/properties.py @@ -31,7 +31,7 @@ enum_devices = ( ('CPU', "CPU", "Use CPU for rendering"), ('GPU', "GPU Compute", "Use GPU compute device for rendering, configured in the system tab in the user preferences"), - ) +) if _cycles.with_network: enum_devices += (('NETWORK', "Networked Device", "Use networked device for rendering"),) @@ -39,34 +39,35 @@ enum_feature_set = ( ('SUPPORTED', "Supported", "Only use finished and supported features"), ('EXPERIMENTAL', "Experimental", "Use experimental and incomplete features that might be broken or change in the future", 'ERROR', 1), - ) +) enum_displacement_methods = ( ('BUMP', "Bump Only", "Bump mapping to simulate the appearance of displacement"), ('DISPLACEMENT', "Displacement Only", "Use true displacement of surface only, requires fine subdivision"), ('BOTH', "Displacement and Bump", "Combination of true displacement and bump mapping for finer detail"), - ) +) enum_bvh_layouts = ( ('BVH2', "BVH2", "", 1), ('BVH4', "BVH4", "", 2), - ) + ('BVH8', "BVH8", "", 4), +) enum_bvh_types = ( ('DYNAMIC_BVH', "Dynamic BVH", "Objects can be individually updated, at the cost of slower render time"), ('STATIC_BVH', "Static BVH", "Any object modification requires a complete BVH rebuild, but renders faster"), - ) +) enum_filter_types = ( ('BOX', "Box", "Box filter"), ('GAUSSIAN', "Gaussian", "Gaussian filter"), ('BLACKMAN_HARRIS', "Blackman-Harris", "Blackman-Harris filter"), - ) +) enum_aperture_types = ( ('RADIUS', "Radius", "Directly change the size of the aperture"), ('FSTOP', "F-stop", "Change the size of the aperture by f-stop"), - ) +) enum_panorama_types = ( ('EQUIRECTANGULAR', "Equirectangular", "Render the scene with a spherical camera, also known as Lat Long panorama"), @@ -74,23 +75,23 @@ ('FISHEYE_EQUISOLID', "Fisheye Equisolid", "Similar to most fisheye modern lens, takes sensor dimensions into consideration"), ('MIRRORBALL', "Mirror Ball", "Uses the mirror ball mapping"), - ) +) enum_curve_primitives = ( ('TRIANGLES', "Triangles", "Create triangle geometry around strands"), ('LINE_SEGMENTS', "Line Segments", "Use line segment primitives"), ('CURVE_SEGMENTS', "Curve Segments", "Use segmented cardinal curve primitives"), - ) +) enum_triangle_curves = ( ('CAMERA_TRIANGLES', "Planes", "Create individual triangles forming planes that face camera"), ('TESSELLATED_TRIANGLES', "Tessellated", "Create mesh surrounding each strand"), - ) +) enum_curve_shape = ( ('RIBBONS', "Ribbons", "Ignore thickness of each strand"), ('THICK', "Thick", "Use thickness of strand when rendering"), - ) +) enum_tile_order = ( ('CENTER', "Center", "Render from center to the edges"), @@ -99,46 +100,46 @@ ('TOP_TO_BOTTOM', "Top to Bottom", "Render from top to bottom"), ('BOTTOM_TO_TOP', "Bottom to Top", "Render from bottom to top"), ('HILBERT_SPIRAL', "Hilbert Spiral", "Render in a Hilbert Spiral"), - ) +) enum_use_layer_samples = ( ('USE', "Use", "Per render layer number of samples override scene samples"), ('BOUNDED', "Bounded", "Bound per render layer number of samples by global samples"), ('IGNORE', "Ignore", "Ignore per render layer number of samples"), - ) +) enum_sampling_pattern = ( ('SOBOL', "Sobol", "Use Sobol random sampling pattern"), ('CORRELATED_MUTI_JITTER', "Correlated Multi-Jitter", "Use Correlated Multi-Jitter random sampling pattern"), - ) +) enum_integrator = ( ('BRANCHED_PATH', "Branched Path Tracing", "Path tracing integrator that branches on the first bounce, giving more control over the number of light and material samples"), ('PATH', "Path Tracing", "Pure path tracing integrator"), - ) +) enum_volume_sampling = ( ('DISTANCE', "Distance", "Use distance sampling, best for dense volumes with lights far away"), ('EQUIANGULAR', "Equiangular", "Use equiangular sampling, best for volumes with low density with light inside or near the volume"), ('MULTIPLE_IMPORTANCE', "Multiple Importance", "Combine distance and equi-angular sampling for volumes where neither method is ideal"), - ) +) enum_volume_interpolation = ( ('LINEAR', "Linear", "Good smoothness and speed"), ('CUBIC', "Cubic", "Smoothed high quality interpolation, but slower") - ) +) enum_world_mis = ( ('NONE', "None", "Don't sample the background, faster but might cause noise for non-solid backgrounds"), ('AUTOMATIC', "Auto", "Automatically try to determine the best setting"), ('MANUAL', "Manual", "Manually set the resolution of the sampling map, higher values are slower and require more memory but reduce noise") - ) +) enum_device_type = ( ('CPU', "CPU", "CPU", 0), ('CUDA', "CUDA", "CUDA", 1), ('OPENCL', "OpenCL", "OpenCL", 2) - ) +) enum_texture_limit = ( ('OFF', "No Limit", "No texture size limit", 0), @@ -149,423 +150,424 @@ ('2048', "2048", "Limit texture size to 2048 pixels", 5), ('4096', "4096", "Limit texture size to 4096 pixels", 6), ('8192', "8192", "Limit texture size to 8192 pixels", 7), - ) +) + class CyclesRenderSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Scene.cycles = PointerProperty( - name="Cycles Render Settings", - description="Cycles render settings", - type=cls, - ) + name="Cycles Render Settings", + description="Cycles render settings", + type=cls, + ) cls.device = EnumProperty( - name="Device", - description="Device to use for rendering", - items=enum_devices, - default='CPU', - ) + name="Device", + description="Device to use for rendering", + items=enum_devices, + default='CPU', + ) cls.feature_set = EnumProperty( - name="Feature Set", - description="Feature set to use for rendering", - items=enum_feature_set, - default='SUPPORTED', - ) + name="Feature Set", + description="Feature set to use for rendering", + items=enum_feature_set, + default='SUPPORTED', + ) cls.shading_system = BoolProperty( - name="Open Shading Language", - description="Use Open Shading Language (CPU rendering only)", - ) + name="Open Shading Language", + description="Use Open Shading Language (CPU rendering only)", + ) cls.progressive = EnumProperty( - name="Integrator", - description="Method to sample lights and materials", - items=enum_integrator, - default='PATH', - ) + name="Integrator", + description="Method to sample lights and materials", + items=enum_integrator, + default='PATH', + ) cls.use_square_samples = BoolProperty( - name="Square Samples", - description="Square sampling values for easier artist control", - default=False, - ) + name="Square Samples", + description="Square sampling values for easier artist control", + default=False, + ) cls.samples = IntProperty( - name="Samples", - description="Number of samples to render for each pixel", - min=1, max=2147483647, - default=128, - ) + name="Samples", + description="Number of samples to render for each pixel", + min=1, max=2147483647, + default=128, + ) cls.preview_samples = IntProperty( - name="Preview Samples", - description="Number of samples to render in the viewport, unlimited if 0", - min=0, max=2147483647, - default=32, - ) + name="Preview Samples", + description="Number of samples to render in the viewport, unlimited if 0", + min=0, max=2147483647, + default=32, + ) cls.preview_pause = BoolProperty( - name="Pause Preview", - description="Pause all viewport preview renders", - default=False, - ) + name="Pause Preview", + description="Pause all viewport preview renders", + default=False, + ) cls.preview_active_layer = BoolProperty( - name="Preview Active Layer", - description="Preview active render layer in viewport", - default=False, - ) + name="Preview Active Layer", + description="Preview active render layer in viewport", + default=False, + ) cls.aa_samples = IntProperty( - name="AA Samples", - description="Number of antialiasing samples to render for each pixel", - min=1, max=2097151, - default=128, - ) + name="AA Samples", + description="Number of antialiasing samples to render for each pixel", + min=1, max=2097151, + default=128, + ) cls.preview_aa_samples = IntProperty( - name="AA Samples", - description="Number of antialiasing samples to render in the viewport, unlimited if 0", - min=0, max=2097151, - default=32, - ) + name="AA Samples", + description="Number of antialiasing samples to render in the viewport, unlimited if 0", + min=0, max=2097151, + default=32, + ) cls.diffuse_samples = IntProperty( - name="Diffuse Samples", - description="Number of diffuse bounce samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Diffuse Samples", + description="Number of diffuse bounce samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.glossy_samples = IntProperty( - name="Glossy Samples", - description="Number of glossy bounce samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Glossy Samples", + description="Number of glossy bounce samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.transmission_samples = IntProperty( - name="Transmission Samples", - description="Number of transmission bounce samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Transmission Samples", + description="Number of transmission bounce samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.ao_samples = IntProperty( - name="Ambient Occlusion Samples", - description="Number of ambient occlusion samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Ambient Occlusion Samples", + description="Number of ambient occlusion samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.mesh_light_samples = IntProperty( - name="Mesh Light Samples", - description="Number of mesh emission light samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Mesh Light Samples", + description="Number of mesh emission light samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.subsurface_samples = IntProperty( - name="Subsurface Samples", - description="Number of subsurface scattering samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Subsurface Samples", + description="Number of subsurface scattering samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.volume_samples = IntProperty( - name="Volume Samples", - description="Number of volume scattering samples to render for each AA sample", - min=1, max=1024, - default=1, - ) + name="Volume Samples", + description="Number of volume scattering samples to render for each AA sample", + min=1, max=1024, + default=1, + ) cls.sampling_pattern = EnumProperty( - name="Sampling Pattern", - description="Random sampling pattern used by the integrator", - items=enum_sampling_pattern, - default='SOBOL', - ) + name="Sampling Pattern", + description="Random sampling pattern used by the integrator", + items=enum_sampling_pattern, + default='SOBOL', + ) cls.use_layer_samples = EnumProperty( - name="Layer Samples", - description="How to use per render layer sample settings", - items=enum_use_layer_samples, - default='USE', - ) + name="Layer Samples", + description="How to use per render layer sample settings", + items=enum_use_layer_samples, + default='USE', + ) cls.sample_all_lights_direct = BoolProperty( - name="Sample All Direct Lights", - description="Sample all lights (for direct samples), rather than randomly picking one", - default=True, - ) + name="Sample All Direct Lights", + description="Sample all lights (for direct samples), rather than randomly picking one", + default=True, + ) cls.sample_all_lights_indirect = BoolProperty( - name="Sample All Indirect Lights", - description="Sample all lights (for indirect samples), rather than randomly picking one", - default=True, - ) + name="Sample All Indirect Lights", + description="Sample all lights (for indirect samples), rather than randomly picking one", + default=True, + ) cls.light_sampling_threshold = FloatProperty( - name="Light Sampling Threshold", - description="Probabilistically terminate light samples when the light contribution is below this threshold (more noise but faster rendering). " - "Zero disables the test and never ignores lights", - min=0.0, max=1.0, - default=0.01, - ) + name="Light Sampling Threshold", + description="Probabilistically terminate light samples when the light contribution is below this threshold (more noise but faster rendering). " + "Zero disables the test and never ignores lights", + min=0.0, max=1.0, + default=0.01, + ) cls.caustics_reflective = BoolProperty( - name="Reflective Caustics", - description="Use reflective caustics, resulting in a brighter image (more noise but added realism)", - default=True, - ) + name="Reflective Caustics", + description="Use reflective caustics, resulting in a brighter image (more noise but added realism)", + default=True, + ) cls.caustics_refractive = BoolProperty( - name="Refractive Caustics", - description="Use refractive caustics, resulting in a brighter image (more noise but added realism)", - default=True, - ) + name="Refractive Caustics", + description="Use refractive caustics, resulting in a brighter image (more noise but added realism)", + default=True, + ) cls.blur_glossy = FloatProperty( - name="Filter Glossy", - description="Adaptively blur glossy shaders after blurry bounces, " - "to reduce noise at the cost of accuracy", - min=0.0, max=10.0, - default=1.0, - ) + name="Filter Glossy", + description="Adaptively blur glossy shaders after blurry bounces, " + "to reduce noise at the cost of accuracy", + min=0.0, max=10.0, + default=1.0, + ) cls.max_bounces = IntProperty( - name="Max Bounces", - description="Total maximum number of bounces", - min=0, max=1024, - default=12, - ) + name="Max Bounces", + description="Total maximum number of bounces", + min=0, max=1024, + default=12, + ) cls.diffuse_bounces = IntProperty( - name="Diffuse Bounces", - description="Maximum number of diffuse reflection bounces, bounded by total maximum", - min=0, max=1024, - default=4, - ) + name="Diffuse Bounces", + description="Maximum number of diffuse reflection bounces, bounded by total maximum", + min=0, max=1024, + default=4, + ) cls.glossy_bounces = IntProperty( - name="Glossy Bounces", - description="Maximum number of glossy reflection bounces, bounded by total maximum", - min=0, max=1024, - default=4, - ) + name="Glossy Bounces", + description="Maximum number of glossy reflection bounces, bounded by total maximum", + min=0, max=1024, + default=4, + ) cls.transmission_bounces = IntProperty( - name="Transmission Bounces", - description="Maximum number of transmission bounces, bounded by total maximum", - min=0, max=1024, - default=12, - ) + name="Transmission Bounces", + description="Maximum number of transmission bounces, bounded by total maximum", + min=0, max=1024, + default=12, + ) cls.volume_bounces = IntProperty( - name="Volume Bounces", - description="Maximum number of volumetric scattering events", - min=0, max=1024, - default=0, - ) + name="Volume Bounces", + description="Maximum number of volumetric scattering events", + min=0, max=1024, + default=0, + ) cls.transparent_max_bounces = IntProperty( - name="Transparent Max Bounces", - description="Maximum number of transparent bounces", - min=0, max=1024, - default=8, - ) + name="Transparent Max Bounces", + description="Maximum number of transparent bounces", + min=0, max=1024, + default=8, + ) cls.volume_step_size = FloatProperty( - name="Step Size", - description="Distance between volume shader samples when rendering the volume " - "(lower values give more accurate and detailed results, but also increased render time)", - default=0.1, - min=0.0000001, max=100000.0, soft_min=0.01, soft_max=1.0, precision=4 - ) + name="Step Size", + description="Distance between volume shader samples when rendering the volume " + "(lower values give more accurate and detailed results, but also increased render time)", + default=0.1, + min=0.0000001, max=100000.0, soft_min=0.01, soft_max=1.0, precision=4 + ) cls.volume_max_steps = IntProperty( - name="Max Steps", - description="Maximum number of steps through the volume before giving up, " - "to avoid extremely long render times with big objects or small step sizes", - default=1024, - min=2, max=65536 - ) + name="Max Steps", + description="Maximum number of steps through the volume before giving up, " + "to avoid extremely long render times with big objects or small step sizes", + default=1024, + min=2, max=65536 + ) cls.dicing_rate = FloatProperty( - name="Dicing Rate", - description="Size of a micropolygon in pixels", - min=0.1, max=1000.0, soft_min=0.5, - default=1.0, - subtype="PIXEL" - ) + name="Dicing Rate", + description="Size of a micropolygon in pixels", + min=0.1, max=1000.0, soft_min=0.5, + default=1.0, + subtype="PIXEL" + ) cls.preview_dicing_rate = FloatProperty( - name="Preview Dicing Rate", - description="Size of a micropolygon in pixels during preview render", - min=0.1, max=1000.0, soft_min=0.5, - default=8.0, - subtype="PIXEL" - ) + name="Preview Dicing Rate", + description="Size of a micropolygon in pixels during preview render", + min=0.1, max=1000.0, soft_min=0.5, + default=8.0, + subtype="PIXEL" + ) cls.max_subdivisions = IntProperty( - name="Max Subdivisions", - description="Stop subdividing when this level is reached even if the dice rate would produce finer tessellation", - min=0, max=16, - default=12, - ) + name="Max Subdivisions", + description="Stop subdividing when this level is reached even if the dice rate would produce finer tessellation", + min=0, max=16, + default=12, + ) cls.dicing_camera = PointerProperty( - name="Dicing Camera", - description="Camera to use as reference point when subdividing geometry, useful to avoid crawling " - "artifacts in animations when the scene camera is moving", - type=bpy.types.Object, - poll=lambda self, obj: obj.type == 'CAMERA', - ) + name="Dicing Camera", + description="Camera to use as reference point when subdividing geometry, useful to avoid crawling " + "artifacts in animations when the scene camera is moving", + type=bpy.types.Object, + poll=lambda self, obj: obj.type == 'CAMERA', + ) cls.offscreen_dicing_scale = FloatProperty( - name="Offscreen Dicing Scale", - description="Multiplier for dicing rate of geometry outside of the camera view. The dicing rate " - "of objects is gradually increased the further they are outside the camera view. " - "Lower values provide higher quality reflections and shadows for off screen objects, " - "while higher values use less memory", - min=1.0, soft_max=25.0, - default=4.0, - ) + name="Offscreen Dicing Scale", + description="Multiplier for dicing rate of geometry outside of the camera view. The dicing rate " + "of objects is gradually increased the further they are outside the camera view. " + "Lower values provide higher quality reflections and shadows for off screen objects, " + "while higher values use less memory", + min=1.0, soft_max=25.0, + default=4.0, + ) cls.film_exposure = FloatProperty( - name="Exposure", - description="Image brightness scale", - min=0.0, max=10.0, - default=1.0, - ) + name="Exposure", + description="Image brightness scale", + min=0.0, max=10.0, + default=1.0, + ) cls.film_transparent = BoolProperty( - name="Transparent", - description="World background is transparent, for compositing the render over another background", - default=False, - ) + name="Transparent", + description="World background is transparent, for compositing the render over another background", + default=False, + ) cls.film_transparent_glass = BoolProperty( - name="Transparent Glass", - description="Render transmissive surfaces as transparent, for compositing glass over another background", - default=False, - ) + name="Transparent Glass", + description="Render transmissive surfaces as transparent, for compositing glass over another background", + default=False, + ) cls.film_transparent_roughness = FloatProperty( - name="Transparent Roughness Threshold", - description="For transparent transmission, keep surfaces with roughness above the threshold opaque", - min=0.0, max=1.0, - default=0.1, - ) + name="Transparent Roughness Threshold", + description="For transparent transmission, keep surfaces with roughness above the threshold opaque", + min=0.0, max=1.0, + default=0.1, + ) # Really annoyingly, we have to keep it around for a few releases, # otherwise forward compatibility breaks in really bad manner: CRASH! # # TODO(sergey): Remove this during 2.8x series of Blender. cls.filter_type = EnumProperty( - name="Filter Type", - description="Pixel filter type", - items=enum_filter_types, - default='BLACKMAN_HARRIS', - ) + name="Filter Type", + description="Pixel filter type", + items=enum_filter_types, + default='BLACKMAN_HARRIS', + ) cls.pixel_filter_type = EnumProperty( - name="Filter Type", - description="Pixel filter type", - items=enum_filter_types, - default='BLACKMAN_HARRIS', - ) + name="Filter Type", + description="Pixel filter type", + items=enum_filter_types, + default='BLACKMAN_HARRIS', + ) cls.filter_width = FloatProperty( - name="Filter Width", - description="Pixel filter width", - min=0.01, max=10.0, - default=1.5, - ) + name="Filter Width", + description="Pixel filter width", + min=0.01, max=10.0, + default=1.5, + ) cls.seed = IntProperty( - name="Seed", - description="Seed value for integrator to get different noise patterns", - min=0, max=2147483647, - default=0, - ) + name="Seed", + description="Seed value for integrator to get different noise patterns", + min=0, max=2147483647, + default=0, + ) cls.use_animated_seed = BoolProperty( - name="Use Animated Seed", - description="Use different seed values (and hence noise patterns) at different frames", - default=False, - ) + name="Use Animated Seed", + description="Use different seed values (and hence noise patterns) at different frames", + default=False, + ) cls.sample_clamp_direct = FloatProperty( - name="Clamp Direct", - description="If non-zero, the maximum value for a direct sample, " - "higher values will be scaled down to avoid too " - "much noise and slow convergence at the cost of accuracy", - min=0.0, max=1e8, - default=0.0, - ) + name="Clamp Direct", + description="If non-zero, the maximum value for a direct sample, " + "higher values will be scaled down to avoid too " + "much noise and slow convergence at the cost of accuracy", + min=0.0, max=1e8, + default=0.0, + ) cls.sample_clamp_indirect = FloatProperty( - name="Clamp Indirect", - description="If non-zero, the maximum value for an indirect sample, " - "higher values will be scaled down to avoid too " - "much noise and slow convergence at the cost of accuracy", - min=0.0, max=1e8, - default=10.0, - ) + name="Clamp Indirect", + description="If non-zero, the maximum value for an indirect sample, " + "higher values will be scaled down to avoid too " + "much noise and slow convergence at the cost of accuracy", + min=0.0, max=1e8, + default=10.0, + ) cls.debug_tile_size = IntProperty( - name="Tile Size", - description="", - min=1, max=4096, - default=1024, - ) + name="Tile Size", + description="", + min=1, max=4096, + default=1024, + ) cls.preview_start_resolution = IntProperty( - name="Start Resolution", - description="Resolution to start rendering preview at, " - "progressively increasing it to the full viewport size", - min=8, max=16384, - default=64, - ) + name="Start Resolution", + description="Resolution to start rendering preview at, " + "progressively increasing it to the full viewport size", + min=8, max=16384, + default=64, + ) cls.debug_reset_timeout = FloatProperty( - name="Reset timeout", - description="", - min=0.01, max=10.0, - default=0.1, - ) + name="Reset timeout", + description="", + min=0.01, max=10.0, + default=0.1, + ) cls.debug_cancel_timeout = FloatProperty( - name="Cancel timeout", - description="", - min=0.01, max=10.0, - default=0.1, - ) + name="Cancel timeout", + description="", + min=0.01, max=10.0, + default=0.1, + ) cls.debug_text_timeout = FloatProperty( - name="Text timeout", - description="", - min=0.01, max=10.0, - default=1.0, - ) + name="Text timeout", + description="", + min=0.01, max=10.0, + default=1.0, + ) cls.debug_bvh_type = EnumProperty( - name="Viewport BVH Type", - description="Choose between faster updates, or faster render", - items=enum_bvh_types, - default='DYNAMIC_BVH', - ) + name="Viewport BVH Type", + description="Choose between faster updates, or faster render", + items=enum_bvh_types, + default='DYNAMIC_BVH', + ) cls.debug_use_spatial_splits = BoolProperty( - name="Use Spatial Splits", - description="Use BVH spatial splits: longer builder time, faster render", - default=False, - ) + name="Use Spatial Splits", + description="Use BVH spatial splits: longer builder time, faster render", + default=False, + ) cls.debug_use_hair_bvh = BoolProperty( - name="Use Hair BVH", - description="Use special type BVH optimized for hair (uses more ram but renders faster)", - default=True, - ) + name="Use Hair BVH", + description="Use special type BVH optimized for hair (uses more ram but renders faster)", + default=True, + ) cls.debug_bvh_time_steps = IntProperty( - name="BVH Time Steps", - description="Split BVH primitives by this number of time steps to speed up render time in cost of memory", - default=0, - min=0, max=16, - ) + name="BVH Time Steps", + description="Split BVH primitives by this number of time steps to speed up render time in cost of memory", + default=0, + min=0, max=16, + ) cls.tile_order = EnumProperty( - name="Tile Order", - description="Tile order for rendering", - items=enum_tile_order, - default='HILBERT_SPIRAL', - options=set(), # Not animatable! - ) + name="Tile Order", + description="Tile order for rendering", + items=enum_tile_order, + default='HILBERT_SPIRAL', + options=set(), # Not animatable! + ) cls.use_progressive_refine = BoolProperty( - name="Progressive Refine", - description="Instead of rendering each tile until it is finished, " - "refine the whole image progressively " - "(this renders somewhat slower, " - "but time can be saved by manually stopping the render when the noise is low enough)", - default=False, - ) + name="Progressive Refine", + description="Instead of rendering each tile until it is finished, " + "refine the whole image progressively " + "(this renders somewhat slower, " + "but time can be saved by manually stopping the render when the noise is low enough)", + default=False, + ) cls.bake_type = EnumProperty( name="Bake Type", @@ -584,34 +586,34 @@ def register(cls): ('GLOSSY', "Glossy", ""), ('TRANSMISSION', "Transmission", ""), ('SUBSURFACE', "Subsurface", ""), - ), - ) + ), + ) cls.use_camera_cull = BoolProperty( - name="Use Camera Cull", - description="Allow objects to be culled based on the camera frustum", - default=False, - ) + name="Use Camera Cull", + description="Allow objects to be culled based on the camera frustum", + default=False, + ) cls.camera_cull_margin = FloatProperty( - name="Camera Cull Margin", - description="Margin for the camera space culling", - default=0.1, - min=0.0, max=5.0 - ) + name="Camera Cull Margin", + description="Margin for the camera space culling", + default=0.1, + min=0.0, max=5.0 + ) cls.use_distance_cull = BoolProperty( - name="Use Distance Cull", - description="Allow objects to be culled based on the distance from camera", - default=False, - ) + name="Use Distance Cull", + description="Allow objects to be culled based on the distance from camera", + default=False, + ) cls.distance_cull_margin = FloatProperty( - name="Cull Distance", - description="Cull objects which are further away from camera than this distance", - default=50, - min=0.0 - ) + name="Cull Distance", + description="Cull objects which are further away from camera than this distance", + default=50, + min=0.0 + ) cls.motion_blur_position = EnumProperty( name="Motion Blur Position", @@ -621,8 +623,8 @@ def register(cls): ('START', "Start on Frame", "The shutter opens at the current frame"), ('CENTER', "Center on Frame", "The shutter is open during the current frame"), ('END', "End on Frame", "The shutter closes at the current frame"), - ), - ) + ), + ) cls.rolling_shutter_type = EnumProperty( name="Shutter Type", @@ -632,43 +634,43 @@ def register(cls): ('NONE', "None", "No rolling shutter effect used"), ('TOP', "Top-Bottom", "Sensor is being scanned from top to bottom") # TODO(seergey): Are there real cameras with different scanning direction? - ), - ) + ), + ) cls.rolling_shutter_duration = FloatProperty( name="Rolling Shutter Duration", description="Scanline \"exposure\" time for the rolling shutter effect", default=0.1, min=0.0, max=1.0, - ) + ) cls.texture_limit = EnumProperty( name="Viewport Texture Limit", default='OFF', description="Limit texture size used by viewport rendering", items=enum_texture_limit - ) + ) cls.texture_limit_render = EnumProperty( name="Render Texture Limit", default='OFF', description="Limit texture size used by final rendering", items=enum_texture_limit - ) + ) cls.ao_bounces = IntProperty( name="AO Bounces", default=0, description="Approximate indirect light with background tinted ambient occlusion at the specified bounce, 0 disables this feature", min=0, max=1024, - ) + ) cls.ao_bounces_render = IntProperty( name="AO Bounces Render", default=0, description="Approximate indirect light with background tinted ambient occlusion at the specified bounce, 0 disables this feature", min=0, max=1024, - ) + ) # Various fine-tuning debug flags @@ -683,10 +685,10 @@ def devices_update_callback(self, context): cls.debug_use_cpu_sse3 = BoolProperty(name="SSE3", default=True) cls.debug_use_cpu_sse2 = BoolProperty(name="SSE2", default=True) cls.debug_bvh_layout = EnumProperty( - name="BVH Layout", - items=enum_bvh_layouts, - default='BVH4', - ) + name="BVH Layout", + items=enum_bvh_layouts, + default='BVH8', + ) cls.debug_use_cpu_split_kernel = BoolProperty(name="Split Kernel", default=False) cls.debug_use_cuda_adaptive_compile = BoolProperty(name="Adaptive Compile", default=False) @@ -699,9 +701,9 @@ def devices_update_callback(self, context): ('DEFAULT', "Default", ""), ('MEGA', "Mega", ""), ('SPLIT', "Split", ""), - ), + ), update=devices_update_callback - ) + ) cls.debug_opencl_device_type = EnumProperty( name="OpenCL Device Type", @@ -713,20 +715,20 @@ def devices_update_callback(self, context): ('CPU', "CPU", ""), ('GPU', "GPU", ""), ('ACCELERATOR', "Accelerator", ""), - ), + ), update=devices_update_callback - ) + ) cls.debug_opencl_kernel_single_program = BoolProperty( name="Single Program", default=True, update=devices_update_callback, - ) + ) cls.debug_use_opencl_debug = BoolProperty(name="Debug OpenCL", default=False) cls.debug_opencl_mem_limit = IntProperty(name="Memory limit", default=0, - description="Artificial limit on OpenCL memory usage in MB (0 to disable limit)") + description="Artificial limit on OpenCL memory usage in MB (0 to disable limit)") @classmethod def unregister(cls): @@ -739,101 +741,101 @@ def register(cls): import math bpy.types.Camera.cycles = PointerProperty( - name="Cycles Camera Settings", - description="Cycles camera settings", - type=cls, - ) + name="Cycles Camera Settings", + description="Cycles camera settings", + type=cls, + ) cls.aperture_type = EnumProperty( - name="Aperture Type", - description="Use f-stop number or aperture radius", - items=enum_aperture_types, - default='RADIUS', - ) + name="Aperture Type", + description="Use f-stop number or aperture radius", + items=enum_aperture_types, + default='RADIUS', + ) cls.aperture_fstop = FloatProperty( - name="Aperture f-stop", - description="F-stop ratio (lower numbers give more defocus, higher numbers give a sharper image)", - min=0.0, soft_min=0.1, soft_max=64.0, - default=5.6, - step=10, - precision=1, - ) + name="Aperture f-stop", + description="F-stop ratio (lower numbers give more defocus, higher numbers give a sharper image)", + min=0.0, soft_min=0.1, soft_max=64.0, + default=5.6, + step=10, + precision=1, + ) cls.aperture_size = FloatProperty( - name="Aperture Size", - description="Radius of the aperture for depth of field (higher values give more defocus)", - min=0.0, soft_max=10.0, - default=0.0, - step=1, - precision=4, - subtype='DISTANCE', - ) + name="Aperture Size", + description="Radius of the aperture for depth of field (higher values give more defocus)", + min=0.0, soft_max=10.0, + default=0.0, + step=1, + precision=4, + subtype='DISTANCE', + ) cls.aperture_blades = IntProperty( - name="Aperture Blades", - description="Number of blades in aperture for polygonal bokeh (at least 3)", - min=0, max=100, - default=0, - ) + name="Aperture Blades", + description="Number of blades in aperture for polygonal bokeh (at least 3)", + min=0, max=100, + default=0, + ) cls.aperture_rotation = FloatProperty( - name="Aperture Rotation", - description="Rotation of blades in aperture", - soft_min=-math.pi, soft_max=math.pi, - subtype='ANGLE', - default=0, - ) + name="Aperture Rotation", + description="Rotation of blades in aperture", + soft_min=-math.pi, soft_max=math.pi, + subtype='ANGLE', + default=0, + ) cls.aperture_ratio = FloatProperty( - name="Aperture Ratio", - description="Distortion to simulate anamorphic lens bokeh", - min=0.01, soft_min=1.0, soft_max=2.0, - default=1.0, - precision=4, - ) + name="Aperture Ratio", + description="Distortion to simulate anamorphic lens bokeh", + min=0.01, soft_min=1.0, soft_max=2.0, + default=1.0, + precision=4, + ) cls.panorama_type = EnumProperty( - name="Panorama Type", - description="Distortion to use for the calculation", - items=enum_panorama_types, - default='FISHEYE_EQUISOLID', - ) + name="Panorama Type", + description="Distortion to use for the calculation", + items=enum_panorama_types, + default='FISHEYE_EQUISOLID', + ) cls.fisheye_fov = FloatProperty( - name="Field of View", - description="Field of view for the fisheye lens", - min=0.1745, soft_max=2.0 * math.pi, max=10.0 * math.pi, - subtype='ANGLE', - default=math.pi, - ) + name="Field of View", + description="Field of view for the fisheye lens", + min=0.1745, soft_max=2.0 * math.pi, max=10.0 * math.pi, + subtype='ANGLE', + default=math.pi, + ) cls.fisheye_lens = FloatProperty( - name="Fisheye Lens", - description="Lens focal length (mm)", - min=0.01, soft_max=15.0, max=100.0, - default=10.5, - ) + name="Fisheye Lens", + description="Lens focal length (mm)", + min=0.01, soft_max=15.0, max=100.0, + default=10.5, + ) cls.latitude_min = FloatProperty( - name="Min Latitude", - description="Minimum latitude (vertical angle) for the equirectangular lens", - min=-0.5 * math.pi, max=0.5 * math.pi, - subtype='ANGLE', - default=-0.5 * math.pi, - ) + name="Min Latitude", + description="Minimum latitude (vertical angle) for the equirectangular lens", + min=-0.5 * math.pi, max=0.5 * math.pi, + subtype='ANGLE', + default=-0.5 * math.pi, + ) cls.latitude_max = FloatProperty( - name="Max Latitude", - description="Maximum latitude (vertical angle) for the equirectangular lens", - min=-0.5 * math.pi, max=0.5 * math.pi, - subtype='ANGLE', - default=0.5 * math.pi, - ) + name="Max Latitude", + description="Maximum latitude (vertical angle) for the equirectangular lens", + min=-0.5 * math.pi, max=0.5 * math.pi, + subtype='ANGLE', + default=0.5 * math.pi, + ) cls.longitude_min = FloatProperty( - name="Min Longitude", - description="Minimum longitude (horizontal angle) for the equirectangular lens", - min=-math.pi, max=math.pi, - subtype='ANGLE', - default=-math.pi, - ) + name="Min Longitude", + description="Minimum longitude (horizontal angle) for the equirectangular lens", + min=-math.pi, max=math.pi, + subtype='ANGLE', + default=-math.pi, + ) cls.longitude_max = FloatProperty( - name="Max Longitude", - description="Maximum longitude (horizontal angle) for the equirectangular lens", - min=-math.pi, max=math.pi, - subtype='ANGLE', - default=math.pi, - ) + name="Max Longitude", + description="Maximum longitude (horizontal angle) for the equirectangular lens", + min=-math.pi, max=math.pi, + subtype='ANGLE', + default=math.pi, + ) @classmethod def unregister(cls): @@ -844,49 +846,49 @@ class CyclesMaterialSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Material.cycles = PointerProperty( - name="Cycles Material Settings", - description="Cycles material settings", - type=cls, - ) + name="Cycles Material Settings", + description="Cycles material settings", + type=cls, + ) cls.sample_as_light = BoolProperty( - name="Multiple Importance Sample", - description="Use multiple importance sampling for this material, " - "disabling may reduce overall noise for large " - "objects that emit little light compared to other light sources", - default=True, - ) + name="Multiple Importance Sample", + description="Use multiple importance sampling for this material, " + "disabling may reduce overall noise for large " + "objects that emit little light compared to other light sources", + default=True, + ) cls.use_transparent_shadow = BoolProperty( - name="Transparent Shadows", - description="Use transparent shadows for this material if it contains a Transparent BSDF, " - "disabling will render faster but not give accurate shadows", - default=True, - ) + name="Transparent Shadows", + description="Use transparent shadows for this material if it contains a Transparent BSDF, " + "disabling will render faster but not give accurate shadows", + default=True, + ) cls.homogeneous_volume = BoolProperty( - name="Homogeneous Volume", - description="When using volume rendering, assume volume has the same density everywhere " - "(not using any textures), for faster rendering", - default=False, - ) + name="Homogeneous Volume", + description="When using volume rendering, assume volume has the same density everywhere " + "(not using any textures), for faster rendering", + default=False, + ) cls.volume_sampling = EnumProperty( - name="Volume Sampling", - description="Sampling method to use for volumes", - items=enum_volume_sampling, - default='MULTIPLE_IMPORTANCE', - ) + name="Volume Sampling", + description="Sampling method to use for volumes", + items=enum_volume_sampling, + default='MULTIPLE_IMPORTANCE', + ) cls.volume_interpolation = EnumProperty( - name="Volume Interpolation", - description="Interpolation method to use for smoke/fire volumes", - items=enum_volume_interpolation, - default='LINEAR', - ) + name="Volume Interpolation", + description="Interpolation method to use for smoke/fire volumes", + items=enum_volume_interpolation, + default='LINEAR', + ) cls.displacement_method = EnumProperty( - name="Displacement Method", - description="Method to use for the displacement", - items=enum_displacement_methods, - default='DISPLACEMENT', - ) + name="Displacement Method", + description="Method to use for the displacement", + items=enum_displacement_methods, + default='DISPLACEMENT', + ) @classmethod def unregister(cls): @@ -897,39 +899,39 @@ class CyclesLampSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Lamp.cycles = PointerProperty( - name="Cycles Lamp Settings", - description="Cycles lamp settings", - type=cls, - ) + name="Cycles Lamp Settings", + description="Cycles lamp settings", + type=cls, + ) cls.cast_shadow = BoolProperty( - name="Cast Shadow", - description="Lamp casts shadows", - default=True, - ) + name="Cast Shadow", + description="Lamp casts shadows", + default=True, + ) cls.samples = IntProperty( - name="Samples", - description="Number of light samples to render for each AA sample", - min=1, max=10000, - default=1, - ) + name="Samples", + description="Number of light samples to render for each AA sample", + min=1, max=10000, + default=1, + ) cls.max_bounces = IntProperty( - name="Max Bounces", - description="Maximum number of bounces the light will contribute to the render", - min=0, max=1024, - default=1024, - ) + name="Max Bounces", + description="Maximum number of bounces the light will contribute to the render", + min=0, max=1024, + default=1024, + ) cls.use_multiple_importance_sampling = BoolProperty( - name="Multiple Importance Sample", - description="Use multiple importance sampling for the lamp, " - "reduces noise for area lamps and sharp glossy materials", - default=True, - ) + name="Multiple Importance Sample", + description="Use multiple importance sampling for the lamp, " + "reduces noise for area lamps and sharp glossy materials", + default=True, + ) cls.is_portal = BoolProperty( - name="Is Portal", - description="Use this area lamp to guide sampling of the background, " - "note that this will make the lamp invisible", - default=False, - ) + name="Is Portal", + description="Use this area lamp to guide sampling of the background, " + "note that this will make the lamp invisible", + default=False, + ) @classmethod def unregister(cls): @@ -940,54 +942,54 @@ class CyclesWorldSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.World.cycles = PointerProperty( - name="Cycles World Settings", - description="Cycles world settings", - type=cls, - ) + name="Cycles World Settings", + description="Cycles world settings", + type=cls, + ) cls.sampling_method = EnumProperty( - name="Sampling method", - description="How to sample the background light", - items=enum_world_mis, - default='AUTOMATIC', - ) + name="Sampling method", + description="How to sample the background light", + items=enum_world_mis, + default='AUTOMATIC', + ) cls.sample_map_resolution = IntProperty( - name="Map Resolution", - description="Importance map size is resolution x resolution/2; " - "higher values potentially produce less noise, at the cost of memory and speed", - min=4, max=8192, - default=1024, - ) + name="Map Resolution", + description="Importance map size is resolution x resolution/2; " + "higher values potentially produce less noise, at the cost of memory and speed", + min=4, max=8192, + default=1024, + ) cls.samples = IntProperty( - name="Samples", - description="Number of light samples to render for each AA sample", - min=1, max=10000, - default=1, - ) + name="Samples", + description="Number of light samples to render for each AA sample", + min=1, max=10000, + default=1, + ) cls.max_bounces = IntProperty( - name="Max Bounces", - description="Maximum number of bounces the background light will contribute to the render", - min=0, max=1024, - default=1024, - ) + name="Max Bounces", + description="Maximum number of bounces the background light will contribute to the render", + min=0, max=1024, + default=1024, + ) cls.homogeneous_volume = BoolProperty( - name="Homogeneous Volume", - description="When using volume rendering, assume volume has the same density everywhere" - "(not using any textures), for faster rendering", - default=False, - ) + name="Homogeneous Volume", + description="When using volume rendering, assume volume has the same density everywhere" + "(not using any textures), for faster rendering", + default=False, + ) cls.volume_sampling = EnumProperty( - name="Volume Sampling", - description="Sampling method to use for volumes", - items=enum_volume_sampling, - default='EQUIANGULAR', - ) + name="Volume Sampling", + description="Sampling method to use for volumes", + items=enum_volume_sampling, + default='EQUIANGULAR', + ) cls.volume_interpolation = EnumProperty( - name="Volume Interpolation", - description="Interpolation method to use for volumes", - items=enum_volume_interpolation, - default='LINEAR', - ) + name="Volume Interpolation", + description="Interpolation method to use for volumes", + items=enum_volume_interpolation, + default='LINEAR', + ) @classmethod def unregister(cls): @@ -998,47 +1000,47 @@ class CyclesVisibilitySettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Object.cycles_visibility = PointerProperty( - name="Cycles Visibility Settings", - description="Cycles visibility settings", - type=cls, - ) + name="Cycles Visibility Settings", + description="Cycles visibility settings", + type=cls, + ) bpy.types.World.cycles_visibility = PointerProperty( - name="Cycles Visibility Settings", - description="Cycles visibility settings", - type=cls, - ) + name="Cycles Visibility Settings", + description="Cycles visibility settings", + type=cls, + ) cls.camera = BoolProperty( - name="Camera", - description="Object visibility for camera rays", - default=True, - ) + name="Camera", + description="Object visibility for camera rays", + default=True, + ) cls.diffuse = BoolProperty( - name="Diffuse", - description="Object visibility for diffuse reflection rays", - default=True, - ) + name="Diffuse", + description="Object visibility for diffuse reflection rays", + default=True, + ) cls.glossy = BoolProperty( - name="Glossy", - description="Object visibility for glossy reflection rays", - default=True, - ) + name="Glossy", + description="Object visibility for glossy reflection rays", + default=True, + ) cls.transmission = BoolProperty( - name="Transmission", - description="Object visibility for transmission rays", - default=True, - ) + name="Transmission", + description="Object visibility for transmission rays", + default=True, + ) cls.shadow = BoolProperty( - name="Shadow", - description="Object visibility for shadow rays", - default=True, - ) + name="Shadow", + description="Object visibility for shadow rays", + default=True, + ) cls.scatter = BoolProperty( - name="Volume Scatter", - description="Object visibility for volume scatter rays", - default=True, - ) + name="Volume Scatter", + description="Object visibility for volume scatter rays", + default=True, + ) @classmethod def unregister(cls): @@ -1050,20 +1052,20 @@ class CyclesMeshSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Mesh.cycles = PointerProperty( - name="Cycles Mesh Settings", - description="Cycles mesh settings", - type=cls, - ) + name="Cycles Mesh Settings", + description="Cycles mesh settings", + type=cls, + ) bpy.types.Curve.cycles = PointerProperty( - name="Cycles Mesh Settings", - description="Cycles mesh settings", - type=cls, - ) + name="Cycles Mesh Settings", + description="Cycles mesh settings", + type=cls, + ) bpy.types.MetaBall.cycles = PointerProperty( - name="Cycles Mesh Settings", - description="Cycles mesh settings", - type=cls, - ) + name="Cycles Mesh Settings", + description="Cycles mesh settings", + type=cls, + ) @classmethod def unregister(cls): @@ -1076,69 +1078,68 @@ class CyclesObjectSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Object.cycles = PointerProperty( - name="Cycles Object Settings", - description="Cycles object settings", - type=cls, - ) + name="Cycles Object Settings", + description="Cycles object settings", + type=cls, + ) cls.use_motion_blur = BoolProperty( - name="Use Motion Blur", - description="Use motion blur for this object", - default=True, - ) + name="Use Motion Blur", + description="Use motion blur for this object", + default=True, + ) cls.use_deform_motion = BoolProperty( - name="Use Deformation Motion", - description="Use deformation motion blur for this object", - default=True, - ) + name="Use Deformation Motion", + description="Use deformation motion blur for this object", + default=True, + ) cls.motion_steps = IntProperty( - name="Motion Steps", - description="Control accuracy of motion blur, more steps gives more memory usage (actual number of steps is 2^(steps - 1))", - min=1, soft_max=8, - default=1, - ) + name="Motion Steps", + description="Control accuracy of motion blur, more steps gives more memory usage (actual number of steps is 2^(steps - 1))", + min=1, soft_max=8, + default=1, + ) cls.use_camera_cull = BoolProperty( - name="Use Camera Cull", - description="Allow this object and its duplicators to be culled by camera space culling", - default=False, - ) + name="Use Camera Cull", + description="Allow this object and its duplicators to be culled by camera space culling", + default=False, + ) cls.use_distance_cull = BoolProperty( - name="Use Distance Cull", - description="Allow this object and its duplicators to be culled by distance from camera", - default=False, - ) + name="Use Distance Cull", + description="Allow this object and its duplicators to be culled by distance from camera", + default=False, + ) cls.use_adaptive_subdivision = BoolProperty( - name="Use Adaptive Subdivision", - description="Use adaptive render time subdivision", - default=False, - ) + name="Use Adaptive Subdivision", + description="Use adaptive render time subdivision", + default=False, + ) cls.dicing_rate = FloatProperty( - name="Dicing Scale", - description="Multiplier for scene dicing rate (located in the Geometry Panel)", - min=0.1, max=1000.0, soft_min=0.5, - default=1.0, - ) + name="Dicing Scale", + description="Multiplier for scene dicing rate (located in the Geometry Panel)", + min=0.1, max=1000.0, soft_min=0.5, + default=1.0, + ) cls.is_shadow_catcher = BoolProperty( - name="Shadow Catcher", - description="Only render shadows on this object, for compositing renders into real footage", - default=False, - ) + name="Shadow Catcher", + description="Only render shadows on this object, for compositing renders into real footage", + default=False, + ) cls.is_holdout = BoolProperty( - name="Holdout", - description="Render objects as a holdout or matte, creating a " - "hole in the image with zero alpha, to fill out in " - "compositing with real footange or another render", - default=False, - ) - + name="Holdout", + description="Render objects as a holdout or matte, creating a " + "hole in the image with zero alpha, to fill out in " + "compositing with real footange or another render", + default=False, + ) @classmethod def unregister(cls): @@ -1149,192 +1150,194 @@ class CyclesCurveRenderSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Scene.cycles_curves = PointerProperty( - name="Cycles Hair Rendering Settings", - description="Cycles hair rendering settings", - type=cls, - ) + name="Cycles Hair Rendering Settings", + description="Cycles hair rendering settings", + type=cls, + ) cls.primitive = EnumProperty( - name="Primitive", - description="Type of primitive used for hair rendering", - items=enum_curve_primitives, - default='LINE_SEGMENTS', - ) + name="Primitive", + description="Type of primitive used for hair rendering", + items=enum_curve_primitives, + default='LINE_SEGMENTS', + ) cls.shape = EnumProperty( - name="Shape", - description="Form of hair", - items=enum_curve_shape, - default='THICK', - ) + name="Shape", + description="Form of hair", + items=enum_curve_shape, + default='THICK', + ) cls.cull_backfacing = BoolProperty( - name="Cull back-faces", - description="Do not test the back-face of each strand", - default=True, - ) + name="Cull back-faces", + description="Do not test the back-face of each strand", + default=True, + ) cls.use_curves = BoolProperty( - name="Use Cycles Hair Rendering", - description="Activate Cycles hair rendering for particle system", - default=True, - ) + name="Use Cycles Hair Rendering", + description="Activate Cycles hair rendering for particle system", + default=True, + ) cls.resolution = IntProperty( - name="Resolution", - description="Resolution of generated mesh", - min=3, max=64, - default=3, - ) + name="Resolution", + description="Resolution of generated mesh", + min=3, max=64, + default=3, + ) cls.minimum_width = FloatProperty( - name="Minimal width", - description="Minimal pixel width for strands (0 - deactivated)", - min=0.0, max=100.0, - default=0.0, - ) + name="Minimal width", + description="Minimal pixel width for strands (0 - deactivated)", + min=0.0, max=100.0, + default=0.0, + ) cls.maximum_width = FloatProperty( - name="Maximal width", - description="Maximum extension that strand radius can be increased by", - min=0.0, max=100.0, - default=0.1, - ) + name="Maximal width", + description="Maximum extension that strand radius can be increased by", + min=0.0, max=100.0, + default=0.1, + ) cls.subdivisions = IntProperty( - name="Subdivisions", - description="Number of subdivisions used in Cardinal curve intersection (power of 2)", - min=0, max=24, - default=4, - ) + name="Subdivisions", + description="Number of subdivisions used in Cardinal curve intersection (power of 2)", + min=0, max=24, + default=4, + ) @classmethod def unregister(cls): del bpy.types.Scene.cycles_curves + def update_render_passes(self, context): scene = context.scene rd = scene.render rl = rd.layers.active rl.update_render_passes() + class CyclesRenderLayerSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.SceneRenderLayer.cycles = PointerProperty( - name="Cycles SceneRenderLayer Settings", - description="Cycles SceneRenderLayer Settings", - type=cls, - ) + name="Cycles SceneRenderLayer Settings", + description="Cycles SceneRenderLayer Settings", + type=cls, + ) cls.pass_debug_bvh_traversed_nodes = BoolProperty( - name="Debug BVH Traversed Nodes", - description="Store Debug BVH Traversed Nodes pass", - default=False, - update=update_render_passes, - ) + name="Debug BVH Traversed Nodes", + description="Store Debug BVH Traversed Nodes pass", + default=False, + update=update_render_passes, + ) cls.pass_debug_bvh_traversed_instances = BoolProperty( - name="Debug BVH Traversed Instances", - description="Store Debug BVH Traversed Instances pass", - default=False, - update=update_render_passes, - ) + name="Debug BVH Traversed Instances", + description="Store Debug BVH Traversed Instances pass", + default=False, + update=update_render_passes, + ) cls.pass_debug_bvh_intersections = BoolProperty( - name="Debug BVH Intersections", - description="Store Debug BVH Intersections", - default=False, - update=update_render_passes, - ) + name="Debug BVH Intersections", + description="Store Debug BVH Intersections", + default=False, + update=update_render_passes, + ) cls.pass_debug_ray_bounces = BoolProperty( - name="Debug Ray Bounces", - description="Store Debug Ray Bounces pass", - default=False, - update=update_render_passes, - ) + name="Debug Ray Bounces", + description="Store Debug Ray Bounces pass", + default=False, + update=update_render_passes, + ) cls.pass_debug_render_time = BoolProperty( - name="Debug Render Time", - description="Render time in milliseconds per sample and pixel", - default=False, - update=update_render_passes, - ) + name="Debug Render Time", + description="Render time in milliseconds per sample and pixel", + default=False, + update=update_render_passes, + ) cls.use_pass_volume_direct = BoolProperty( - name="Volume Direct", - description="Deliver direct volumetric scattering pass", - default=False, - update=update_render_passes, - ) + name="Volume Direct", + description="Deliver direct volumetric scattering pass", + default=False, + update=update_render_passes, + ) cls.use_pass_volume_indirect = BoolProperty( - name="Volume Indirect", - description="Deliver indirect volumetric scattering pass", - default=False, - update=update_render_passes, - ) + name="Volume Indirect", + description="Deliver indirect volumetric scattering pass", + default=False, + update=update_render_passes, + ) cls.use_denoising = BoolProperty( - name="Use Denoising", - description="Denoise the rendered image", - default=False, - update=update_render_passes, - ) + name="Use Denoising", + description="Denoise the rendered image", + default=False, + update=update_render_passes, + ) cls.denoising_diffuse_direct = BoolProperty( - name="Diffuse Direct", - description="Denoise the direct diffuse lighting", - default=True, - ) + name="Diffuse Direct", + description="Denoise the direct diffuse lighting", + default=True, + ) cls.denoising_diffuse_indirect = BoolProperty( - name="Diffuse Indirect", - description="Denoise the indirect diffuse lighting", - default=True, - ) + name="Diffuse Indirect", + description="Denoise the indirect diffuse lighting", + default=True, + ) cls.denoising_glossy_direct = BoolProperty( - name="Glossy Direct", - description="Denoise the direct glossy lighting", - default=True, - ) + name="Glossy Direct", + description="Denoise the direct glossy lighting", + default=True, + ) cls.denoising_glossy_indirect = BoolProperty( - name="Glossy Indirect", - description="Denoise the indirect glossy lighting", - default=True, - ) + name="Glossy Indirect", + description="Denoise the indirect glossy lighting", + default=True, + ) cls.denoising_transmission_direct = BoolProperty( - name="Transmission Direct", - description="Denoise the direct transmission lighting", - default=True, - ) + name="Transmission Direct", + description="Denoise the direct transmission lighting", + default=True, + ) cls.denoising_transmission_indirect = BoolProperty( - name="Transmission Indirect", - description="Denoise the indirect transmission lighting", - default=True, - ) + name="Transmission Indirect", + description="Denoise the indirect transmission lighting", + default=True, + ) cls.denoising_subsurface_direct = BoolProperty( - name="Subsurface Direct", - description="Denoise the direct subsurface lighting", - default=True, - ) + name="Subsurface Direct", + description="Denoise the direct subsurface lighting", + default=True, + ) cls.denoising_subsurface_indirect = BoolProperty( - name="Subsurface Indirect", - description="Denoise the indirect subsurface lighting", - default=True, - ) + name="Subsurface Indirect", + description="Denoise the indirect subsurface lighting", + default=True, + ) cls.denoising_strength = FloatProperty( - name="Denoising Strength", - description="Controls neighbor pixel weighting for the denoising filter (lower values preserve more detail, but aren't as smooth)", - min=0.0, max=1.0, - default=0.5, - ) + name="Denoising Strength", + description="Controls neighbor pixel weighting for the denoising filter (lower values preserve more detail, but aren't as smooth)", + min=0.0, max=1.0, + default=0.5, + ) cls.denoising_feature_strength = FloatProperty( - name="Denoising Feature Strength", - description="Controls removal of noisy image feature passes (lower values preserve more detail, but aren't as smooth)", - min=0.0, max=1.0, - default=0.5, - ) + name="Denoising Feature Strength", + description="Controls removal of noisy image feature passes (lower values preserve more detail, but aren't as smooth)", + min=0.0, max=1.0, + default=0.5, + ) cls.denoising_radius = IntProperty( - name="Denoising Radius", - description="Size of the image area that's used to denoise a pixel (higher values are smoother, but might lose detail and are slower)", - min=1, max=25, - default=8, + name="Denoising Radius", + description="Size of the image area that's used to denoise a pixel (higher values are smoother, but might lose detail and are slower)", + min=1, max=25, + default=8, ) cls.denoising_relative_pca = BoolProperty( - name="Relative filter", - description="When removing pixels that don't carry information, use a relative threshold instead of an absolute one (can help to reduce artifacts, but might cause detail loss around edges)", - default=False, + name="Relative filter", + description="When removing pixels that don't carry information, use a relative threshold instead of an absolute one (can help to reduce artifacts, but might cause detail loss around edges)", + default=False, ) cls.denoising_store_passes = BoolProperty( - name="Store denoising passes", - description="Store the denoising feature passes and the noisy image", - default=False, - update=update_render_passes, + name="Store denoising passes", + description="Store the denoising feature passes and the noisy image", + default=False, + update=update_render_passes, ) @classmethod @@ -1346,39 +1349,39 @@ class CyclesCurveSettings(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.ParticleSettings.cycles = PointerProperty( - name="Cycles Hair Settings", - description="Cycles hair settings", - type=cls, - ) + name="Cycles Hair Settings", + description="Cycles hair settings", + type=cls, + ) cls.radius_scale = FloatProperty( - name="Radius Scaling", - description="Multiplier of width properties", - min=0.0, max=1000.0, - default=0.01, - ) + name="Radius Scaling", + description="Multiplier of width properties", + min=0.0, max=1000.0, + default=0.01, + ) cls.root_width = FloatProperty( - name="Root Size", - description="Strand's width at root", - min=0.0, max=1000.0, - default=1.0, - ) + name="Root Size", + description="Strand's width at root", + min=0.0, max=1000.0, + default=1.0, + ) cls.tip_width = FloatProperty( - name="Tip Multiplier", - description="Strand's width at tip", - min=0.0, max=1000.0, - default=0.0, - ) + name="Tip Multiplier", + description="Strand's width at tip", + min=0.0, max=1000.0, + default=0.0, + ) cls.shape = FloatProperty( - name="Strand Shape", - description="Strand shape parameter", - min=-1.0, max=1.0, - default=0.0, - ) + name="Strand Shape", + description="Strand shape parameter", + min=-1.0, max=1.0, + default=0.0, + ) cls.use_closetip = BoolProperty( - name="Close tip", - description="Set tip radius to zero", - default=True, - ) + name="Close tip", + description="Set tip radius to zero", + default=True, + ) @classmethod def unregister(cls): @@ -1408,10 +1411,10 @@ def get_device_types(self, context): return list compute_device_type = EnumProperty( - name="Compute Device Type", - description="Device to use for computation (rendering with Cycles)", - items=get_device_types, - ) + name="Compute Device Type", + description="Device to use for computation (rendering with Cycles)", + items=get_device_types, + ) devices = bpy.props.CollectionProperty(type=CyclesDeviceSettings) @@ -1421,7 +1424,6 @@ def find_existing_device_entry(self, device): return device_entry return None - def update_device_entries(self, device_list): for device in device_list: if not device[1] in {'CUDA', 'OPENCL', 'CPU'}: @@ -1431,15 +1433,14 @@ def update_device_entries(self, device_list): if not entry: # Create new entry if no existing one was found entry = self.devices.add() - entry.id = device[2] + entry.id = device[2] entry.name = device[0] entry.type = device[1] - entry.use = entry.type != 'CPU' + entry.use = entry.type != 'CPU' elif entry.name != device[0]: # Update name in case it changed entry.name = device[0] - def get_devices(self): import _cycles # Layout of the device tuples: (Name, Type, Persistent ID) @@ -1465,7 +1466,6 @@ def get_devices(self): opencl_devices.extend(cpu_devices) return cuda_devices, opencl_devices - def get_num_gpu_devices(self): import _cycles device_list = _cycles.available_devices() @@ -1478,11 +1478,9 @@ def get_num_gpu_devices(self): num += 1 return num - def has_active_device(self): return self.get_num_gpu_devices() > 0 - def draw_impl(self, layout, context): layout.label(text="Cycles Compute Device:") layout.row().prop(self, "compute_device_type", expand=True) @@ -1500,7 +1498,6 @@ def draw_impl(self, layout, context): for device in opencl_devices: box.prop(device, "use", text=device.name) - def draw(self, context): self.draw_impl(self.layout, context) diff --git a/intern/cycles/blender/addon/ui.py b/intern/cycles/blender/addon/ui.py index 2b11a2eefb00..5edbcb196727 100644 --- a/intern/cycles/blender/addon/ui.py +++ b/intern/cycles/blender/addon/ui.py @@ -19,10 +19,10 @@ import bpy from bpy.types import ( - Panel, - Menu, - Operator, - ) + Panel, + Menu, + Operator, +) class CYCLES_MT_sampling_presets(Menu): @@ -86,6 +86,7 @@ def use_sample_all_lights(context): return cscene.sample_all_lights_direct or cscene.sample_all_lights_indirect + def show_device_active(context): cscene = context.scene.cycles if cscene.device != 'GPU': @@ -965,9 +966,9 @@ class CYCLES_LAMP_PT_preview(CyclesButtonsPanel, Panel): @classmethod def poll(cls, context): return context.lamp and \ - not (context.lamp.type == 'AREA' and - context.lamp.cycles.is_portal) \ - and CyclesButtonsPanel.poll(context) + not (context.lamp.type == 'AREA' and + context.lamp.cycles.is_portal) \ + and CyclesButtonsPanel.poll(context) def draw(self, context): self.layout.template_preview(context.lamp) @@ -1035,7 +1036,7 @@ class CYCLES_LAMP_PT_nodes(CyclesButtonsPanel, Panel): def poll(cls, context): return context.lamp and not (context.lamp.type == 'AREA' and context.lamp.cycles.is_portal) and \ - CyclesButtonsPanel.poll(context) + CyclesButtonsPanel.poll(context) def draw(self, context): layout = self.layout @@ -1741,6 +1742,7 @@ def draw(self, context): col = split.column() col.prop(cscene, "ao_bounces_render") + def draw_device(self, context): scene = context.scene layout = self.layout @@ -1823,7 +1825,7 @@ def get_panels(): 'WORLD_PT_mist', 'WORLD_PT_preview', 'WORLD_PT_world' - } + } panels = [] for panel in bpy.types.Panel.__subclasses__(): diff --git a/intern/cycles/blender/addon/version_update.py b/intern/cycles/blender/addon/version_update.py index 922ea9d9d7f2..f14fe9abc3d9 100644 --- a/intern/cycles/blender/addon/version_update.py +++ b/intern/cycles/blender/addon/version_update.py @@ -75,19 +75,25 @@ def foreach_cycles_node(callback): traversed = set() for material in bpy.data.materials: if check_is_new_shading_material(material): - foreach_notree_node(material.node_tree, - callback, - traversed) + foreach_notree_node( + material.node_tree, + callback, + traversed, + ) for world in bpy.data.worlds: if check_is_new_shading_world(world): - foreach_notree_node(world.node_tree, - callback, - traversed) + foreach_notree_node( + world.node_tree, + callback, + traversed, + ) for lamp in bpy.data.lamps: if check_is_new_shading_world(lamp): - foreach_notree_node(lamp.node_tree, - callback, - traversed) + foreach_notree_node( + lamp.node_tree, + callback, + traversed, + ) def displacement_node_insert(material, nodetree, traversed): @@ -102,10 +108,12 @@ def displacement_node_insert(material, nodetree, traversed): # Gather links to replace displacement_links = [] for link in nodetree.links: - if link.to_node.bl_idname == 'ShaderNodeOutputMaterial' and \ - link.from_node.bl_idname != 'ShaderNodeDisplacement' and \ - link.to_socket.identifier == 'Displacement': - displacement_links.append(link) + if ( + link.to_node.bl_idname == 'ShaderNodeOutputMaterial' and + link.from_node.bl_idname != 'ShaderNodeDisplacement' and + link.to_socket.identifier == 'Displacement' + ): + displacement_links.append(link) # Replace links with displacement node for link in displacement_links: @@ -117,20 +125,22 @@ def displacement_node_insert(material, nodetree, traversed): nodetree.links.remove(link) node = nodetree.nodes.new(type='ShaderNodeDisplacement') - node.location[0] = 0.5 * (from_node.location[0] + to_node.location[0]); - node.location[1] = 0.5 * (from_node.location[1] + to_node.location[1]); + node.location[0] = 0.5 * (from_node.location[0] + to_node.location[0]) + node.location[1] = 0.5 * (from_node.location[1] + to_node.location[1]) node.inputs['Scale'].default_value = 0.1 node.inputs['Midlevel'].default_value = 0.0 nodetree.links.new(from_socket, node.inputs['Height']) nodetree.links.new(node.outputs['Displacement'], to_socket) + def displacement_nodes_insert(): traversed = set() for material in bpy.data.materials: if check_is_new_shading_material(material): displacement_node_insert(material, material.node_tree, traversed) + def displacement_principled_nodes(node): if node.bl_idname == 'ShaderNodeDisplacement': if node.space != 'WORLD': @@ -139,6 +149,7 @@ def displacement_principled_nodes(node): if node.subsurface_method != 'RANDOM_WALK': node.subsurface_method = 'BURLEY' + def square_roughness_node_insert(material, nodetree, traversed): if nodetree in traversed: return @@ -163,7 +174,7 @@ def square_roughness_node_insert(material, nodetree, traversed): for link in nodetree.links: if link.to_node.bl_idname in roughness_node_types and \ link.to_socket.identifier == 'Roughness': - roughness_links.append(link) + roughness_links.append(link) # Replace links with sqrt node for link in roughness_links: @@ -176,13 +187,14 @@ def square_roughness_node_insert(material, nodetree, traversed): node = nodetree.nodes.new(type='ShaderNodeMath') node.operation = 'POWER' - node.location[0] = 0.5 * (from_node.location[0] + to_node.location[0]); - node.location[1] = 0.5 * (from_node.location[1] + to_node.location[1]); + node.location[0] = 0.5 * (from_node.location[0] + to_node.location[0]) + node.location[1] = 0.5 * (from_node.location[1] + to_node.location[1]) nodetree.links.new(from_socket, node.inputs[0]) node.inputs[1].default_value = 0.5 nodetree.links.new(node.outputs['Value'], to_socket) + def square_roughness_nodes_insert(): traversed = set() for material in bpy.data.materials: @@ -288,7 +300,7 @@ def ambient_occlusion_node_relink(material, nodetree, traversed): ao_links = [] for link in nodetree.links: if link.from_node.bl_idname == 'ShaderNodeAmbientOcclusion': - ao_links.append(link) + ao_links.append(link) # Replace links for link in ao_links: @@ -298,6 +310,7 @@ def ambient_occlusion_node_relink(material, nodetree, traversed): nodetree.links.remove(link) nodetree.links.new(from_node.outputs['Color'], to_socket) + def ambient_occlusion_nodes_relink(): traversed = set() for material in bpy.data.materials: @@ -335,9 +348,11 @@ def do_versions(self): for scene in bpy.data.scenes: cscene = scene.cycles sample_clamp = cscene.get("sample_clamp", False) - if (sample_clamp and + if ( + sample_clamp and not cscene.is_property_set("sample_clamp_direct") and - not cscene.is_property_set("sample_clamp_indirect")): + not cscene.is_property_set("sample_clamp_indirect") + ): cscene.sample_clamp_direct = sample_clamp cscene.sample_clamp_indirect = sample_clamp @@ -353,10 +368,11 @@ def do_versions(self): if bpy.data.version <= (2, 72, 0): for scene in bpy.data.scenes: cscene = scene.cycles - if (cscene.get("no_caustics", False) and + if ( + cscene.get("no_caustics", False) and not cscene.is_property_set("caustics_reflective") and - not cscene.is_property_set("caustics_refractive")): - + not cscene.is_property_set("caustics_refractive") + ): cscene.caustics_reflective = False cscene.caustics_refractive = False @@ -467,7 +483,7 @@ def do_versions(self): cworld = world.cycles # World MIS if not cworld.is_property_set("sampling_method"): - if cworld.get("sample_as_light", False): + if cworld.get("sample_as_light", True): cworld.sampling_method = 'MANUAL' else: cworld.sampling_method = 'NONE' diff --git a/intern/cycles/blender/blender_camera.cpp b/intern/cycles/blender/blender_camera.cpp index 435afabc2bbf..5a447a347a3c 100644 --- a/intern/cycles/blender/blender_camera.cpp +++ b/intern/cycles/blender/blender_camera.cpp @@ -124,7 +124,7 @@ static float blender_camera_focal_distance(BL::RenderEngine& b_engine, if(!b_dof_object) return b_camera.dof_distance(); - + /* for dof object, return distance along camera Z direction */ BL::Array b_ob_matrix; b_engine.camera_model_matrix(b_ob, bcam->use_spherical_stereo, b_ob_matrix); @@ -457,6 +457,7 @@ static void blender_camera_sync(Camera *cam, cam->matrix = blender_camera_matrix(bcam->matrix, bcam->type, bcam->panorama_type); + cam->motion.clear(); cam->motion.resize(bcam->motion_steps, cam->matrix); cam->use_perspective_motion = false; cam->shuttertime = bcam->shuttertime; @@ -725,7 +726,7 @@ static void blender_camera_view_subset(BL::RenderEngine& b_engine, blender_camera_viewplane(&cam_bcam, cam_bcam.full_width, cam_bcam.full_height, &cam, &cam_aspect, &sensor_size); - + /* return */ *view_box = view * (1.0f/view_aspect); *cam_box = cam * (1.0f/cam_aspect); @@ -894,4 +895,3 @@ BufferParams BlenderSync::get_buffer_params(BL::RenderSettings& b_render, } CCL_NAMESPACE_END - diff --git a/intern/cycles/blender/blender_object.cpp b/intern/cycles/blender/blender_object.cpp index 86b04f5030cd..35bf7beda414 100644 --- a/intern/cycles/blender/blender_object.cpp +++ b/intern/cycles/blender/blender_object.cpp @@ -125,7 +125,7 @@ void BlenderSync::sync_light(BL::Object& b_parent, *use_portal = true; return; } - + BL::Lamp b_lamp(b_ob.data()); /* type */ @@ -185,7 +185,7 @@ void BlenderSync::sync_light(BL::Object& b_parent, PointerRNA clamp = RNA_pointer_get(&b_lamp.ptr, "cycles"); light->cast_shadow = get_boolean(clamp, "cast_shadow"); light->use_mis = get_boolean(clamp, "use_multiple_importance_sampling"); - + int samples = get_int(clamp, "samples"); if(get_boolean(cscene, "use_square_samples")) light->samples = samples * samples; @@ -287,7 +287,7 @@ Object *BlenderSync::sync_object(BL::Object& b_parent, { BL::Object b_ob = (b_dupli_ob ? b_dupli_ob.object() : b_parent); bool motion = motion_time != 0.0f; - + /* light is handled separately */ if(object_is_light(b_ob)) { /* don't use lamps for excluded layers used as mask layer */ @@ -360,7 +360,7 @@ Object *BlenderSync::sync_object(BL::Object& b_parent, if(object_map.sync(&object, b_ob, b_parent, key)) object_updated = true; - + /* mesh sync */ object->mesh = sync_mesh(b_ob, object_updated, hide_tris); @@ -414,6 +414,7 @@ Object *BlenderSync::sync_object(BL::Object& b_parent, mesh->motion_steps = motion_steps; } + object->motion.clear(); object->motion.resize(motion_steps, transform_empty()); if(motion_steps) { @@ -501,7 +502,7 @@ static bool object_render_hide(BL::Object& b_ob, } parent = parent.parent(); } - + hide_triangles = hide_emitter; if(show_emitter) { @@ -529,7 +530,7 @@ void BlenderSync::sync_objects(float motion_time) /* layer data */ uint scene_layer = render_layer.scene_layer; bool motion = motion_time != 0.0f; - + if(!motion) { /* prepare for sync */ light_map.pre_sync(); @@ -754,4 +755,3 @@ void BlenderSync::sync_motion(BL::RenderSettings& b_render, } CCL_NAMESPACE_END - diff --git a/intern/cycles/blender/blender_object_cull.cpp b/intern/cycles/blender/blender_object_cull.cpp index bdf7dc469b25..680d9d7b1ffe 100644 --- a/intern/cycles/blender/blender_object_cull.cpp +++ b/intern/cycles/blender/blender_object_cull.cpp @@ -146,4 +146,3 @@ bool BlenderObjectCulling::test_distance(Scene *scene, float3 bb[8]) } CCL_NAMESPACE_END - diff --git a/intern/cycles/blender/blender_particles.cpp b/intern/cycles/blender/blender_particles.cpp index 00f8cb3cf1b2..727d9acf729e 100644 --- a/intern/cycles/blender/blender_particles.cpp +++ b/intern/cycles/blender/blender_particles.cpp @@ -68,7 +68,7 @@ bool BlenderSync::sync_dupli_particle(BL::Object& b_ob, /* add particle */ BL::Particle b_pa = b_psys.particles[persistent_id[0]]; Particle pa; - + pa.index = persistent_id[0]; pa.age = b_scene.frame_current() - b_pa.birth_time(); pa.lifetime = b_pa.lifetime(); diff --git a/intern/cycles/blender/blender_python.cpp b/intern/cycles/blender/blender_python.cpp index 76cc18dd9a1d..4b01eb5f2d45 100644 --- a/intern/cycles/blender/blender_python.cpp +++ b/intern/cycles/blender/blender_python.cpp @@ -331,7 +331,7 @@ static PyObject *draw_func(PyObject * /*self*/, PyObject *args) if(!PyArg_ParseTuple(args, "OOO", &pysession, &pyv3d, &pyrv3d)) return NULL; - + BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession); if(PyLong_AsVoidPtr(pyrv3d)) { @@ -590,7 +590,7 @@ static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args) if(!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile)) return NULL; - + /* return */ if(!OSLShaderManager::osl_compile(inputfile, outputfile)) Py_RETURN_FALSE; @@ -734,6 +734,12 @@ static PyObject *set_resumable_chunk_range_func(PyObject * /*self*/, PyObject *a Py_RETURN_NONE; } +static PyObject *enable_print_stats_func(PyObject * /*self*/, PyObject * /*args*/) +{ + BlenderSession::print_render_stats = true; + Py_RETURN_NONE; +} + static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/) { vector& devices = Device::available_devices(); @@ -772,6 +778,9 @@ static PyMethodDef methods[] = { {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""}, {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""}, + /* Statistics. */ + {"enable_print_stats", enable_print_stats_func, METH_NOARGS, ""}, + /* Resumable render */ {"set_resumable_chunk", set_resumable_chunk_func, METH_VARARGS, ""}, {"set_resumable_chunk_range", set_resumable_chunk_range_func, METH_VARARGS, ""}, diff --git a/intern/cycles/blender/blender_session.cpp b/intern/cycles/blender/blender_session.cpp index 00d23b9095e5..a07131d04aeb 100644 --- a/intern/cycles/blender/blender_session.cpp +++ b/intern/cycles/blender/blender_session.cpp @@ -28,6 +28,7 @@ #include "render/scene.h" #include "render/session.h" #include "render/shader.h" +#include "render/stats.h" #include "util/util_color.h" #include "util/util_foreach.h" @@ -48,6 +49,7 @@ int BlenderSession::num_resumable_chunks = 0; int BlenderSession::current_resumable_chunk = 0; int BlenderSession::start_resumable_chunk = 0; int BlenderSession::end_resumable_chunk = 0; +bool BlenderSession::print_render_stats = false; BlenderSession::BlenderSession(BL::RenderEngine& b_engine, BL::UserPreferences& b_userpref, @@ -408,26 +410,19 @@ void BlenderSession::render() PointerRNA crl = RNA_pointer_get(&b_layer_iter->ptr, "cycles"); bool use_denoising = get_boolean(crl, "use_denoising"); - buffer_params.denoising_data_pass = use_denoising; + session->tile_manager.schedule_denoising = use_denoising; + buffer_params.denoising_data_pass = use_denoising; + buffer_params.denoising_clean_pass = (scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES); + session->params.use_denoising = use_denoising; - scene->film->denoising_data_pass = buffer_params.denoising_data_pass; - scene->film->denoising_flags = 0; - if(!get_boolean(crl, "denoising_diffuse_direct")) scene->film->denoising_flags |= DENOISING_CLEAN_DIFFUSE_DIR; - if(!get_boolean(crl, "denoising_diffuse_indirect")) scene->film->denoising_flags |= DENOISING_CLEAN_DIFFUSE_IND; - if(!get_boolean(crl, "denoising_glossy_direct")) scene->film->denoising_flags |= DENOISING_CLEAN_GLOSSY_DIR; - if(!get_boolean(crl, "denoising_glossy_indirect")) scene->film->denoising_flags |= DENOISING_CLEAN_GLOSSY_IND; - if(!get_boolean(crl, "denoising_transmission_direct")) scene->film->denoising_flags |= DENOISING_CLEAN_TRANSMISSION_DIR; - if(!get_boolean(crl, "denoising_transmission_indirect")) scene->film->denoising_flags |= DENOISING_CLEAN_TRANSMISSION_IND; - if(!get_boolean(crl, "denoising_subsurface_direct")) scene->film->denoising_flags |= DENOISING_CLEAN_SUBSURFACE_DIR; - if(!get_boolean(crl, "denoising_subsurface_indirect")) scene->film->denoising_flags |= DENOISING_CLEAN_SUBSURFACE_IND; - scene->film->denoising_clean_pass = (scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES); - buffer_params.denoising_clean_pass = scene->film->denoising_clean_pass; session->params.denoising_radius = get_int(crl, "denoising_radius"); session->params.denoising_strength = get_float(crl, "denoising_strength"); session->params.denoising_feature_strength = get_float(crl, "denoising_feature_strength"); session->params.denoising_relative_pca = get_boolean(crl, "denoising_relative_pca"); + scene->film->denoising_data_pass = buffer_params.denoising_data_pass; + scene->film->denoising_clean_pass = buffer_params.denoising_clean_pass; scene->film->pass_alpha_threshold = b_layer_iter->pass_alpha_threshold(); scene->film->tag_passes_update(scene, passes); scene->film->tag_update(scene); @@ -492,6 +487,12 @@ void BlenderSession::render() /* free result without merging */ end_render_result(b_engine, b_rr, true, true, false); + if(!b_engine.is_preview() && background && print_render_stats) { + RenderStats stats; + session->scene->collect_statistics(&stats); + printf("Render statistics:\n%s\n", stats.full_report().c_str()); + } + if(session->progress.get_cancel()) break; } diff --git a/intern/cycles/blender/blender_session.h b/intern/cycles/blender/blender_session.h index 3804e07cffcb..08f5c873bef5 100644 --- a/intern/cycles/blender/blender_session.h +++ b/intern/cycles/blender/blender_session.h @@ -143,6 +143,8 @@ class BlenderSession { static int start_resumable_chunk; static int end_resumable_chunk; + static bool print_render_stats; + protected: void do_write_update_render_result(BL::RenderResult& b_rr, BL::RenderLayer& b_rlay, diff --git a/intern/cycles/blender/blender_shader.cpp b/intern/cycles/blender/blender_shader.cpp index 89612b74c39c..3eefb92f6aff 100644 --- a/intern/cycles/blender/blender_shader.cpp +++ b/intern/cycles/blender/blender_shader.cpp @@ -154,7 +154,7 @@ static SocketType::Type convert_socket_type(BL::NodeSocket& b_socket) return SocketType::STRING; case BL::NodeSocket::type_SHADER: return SocketType::CLOSURE; - + default: return SocketType::UNDEFINED; } @@ -443,7 +443,7 @@ static ShaderNode *add_node(Scene *scene, else if(b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) { BL::ShaderNodeBsdfGlossy b_glossy_node(b_node); GlossyBsdfNode *glossy = new GlossyBsdfNode(); - + switch(b_glossy_node.distribution()) { case BL::ShaderNodeBsdfGlossy::distribution_SHARP: glossy->distribution = CLOSURE_BSDF_REFLECTION_ID; @@ -524,6 +524,12 @@ static ShaderNode *add_node(Scene *scene, } node = hair; } + else if(b_node.is_a(&RNA_ShaderNodeBsdfHairPrincipled)) { + BL::ShaderNodeBsdfHairPrincipled b_principled_hair_node(b_node); + PrincipledHairBsdfNode *principled_hair = new PrincipledHairBsdfNode(); + principled_hair->parametrization = (NodePrincipledHairParametrization) get_enum(b_principled_hair_node.ptr, "parametrization", NODE_PRINCIPLED_HAIR_NUM, NODE_PRINCIPLED_HAIR_REFLECTANCE); + node = principled_hair; + } else if(b_node.is_a(&RNA_ShaderNodeBsdfPrincipled)) { BL::ShaderNodeBsdfPrincipled b_principled_node(b_node); PrincipledBsdfNode *principled = new PrincipledBsdfNode(); @@ -748,6 +754,8 @@ static ShaderNode *add_node(Scene *scene, BL::ShaderNodeTexVoronoi b_voronoi_node(b_node); VoronoiTextureNode *voronoi = new VoronoiTextureNode(); voronoi->coloring = (NodeVoronoiColoring)b_voronoi_node.coloring(); + voronoi->metric = (NodeVoronoiDistanceMetric)b_voronoi_node.distance(); + voronoi->feature = (NodeVoronoiFeature)b_voronoi_node.feature(); BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping()); get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping); node = voronoi; @@ -943,7 +951,7 @@ static ShaderInput *node_find_input_by_name(ShaderNode *node, BL::NodeSocket& b_socket) { string name = b_socket.name(); - + if(node_use_modified_socket_name(node)) { BL::Node::inputs_iterator b_input; bool found = false; @@ -1049,7 +1057,7 @@ static void add_nodes(Scene *scene, for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) { BL::NodeSocket to_socket(b_link->to_socket()); SocketType::Type to_socket_type = convert_socket_type(to_socket); - if (to_socket_type == SocketType::UNDEFINED) { + if(to_socket_type == SocketType::UNDEFINED) { continue; } @@ -1062,7 +1070,7 @@ static void add_nodes(Scene *scene, } } else if(b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) { - + BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL); if(b_node->is_a(&RNA_ShaderNodeGroup)) b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree()); @@ -1076,7 +1084,7 @@ static void add_nodes(Scene *scene, */ for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) { SocketType::Type input_type = convert_socket_type(*b_input); - if (input_type == SocketType::UNDEFINED) { + if(input_type == SocketType::UNDEFINED) { continue; } @@ -1092,7 +1100,7 @@ static void add_nodes(Scene *scene, } for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) { SocketType::Type output_type = convert_socket_type(*b_output); - if (output_type == SocketType::UNDEFINED) { + if(output_type == SocketType::UNDEFINED) { continue; } @@ -1104,7 +1112,7 @@ static void add_nodes(Scene *scene, output_map[b_output->ptr.data] = proxy->outputs[0]; } - + if(b_group_ntree) { add_nodes(scene, b_engine, @@ -1481,4 +1489,3 @@ void BlenderSync::sync_shaders() } CCL_NAMESPACE_END - diff --git a/intern/cycles/blender/blender_sync.cpp b/intern/cycles/blender/blender_sync.cpp index 283aa5600fd2..5e47252e336f 100644 --- a/intern/cycles/blender/blender_sync.cpp +++ b/intern/cycles/blender/blender_sync.cpp @@ -142,7 +142,7 @@ bool BlenderSync::sync_recalc() if(b_ob->is_updated_data() || b_ob->data().is_updated()) light_map.set_recalc(*b_ob); } - + if(b_ob->is_updated_data()) { BL::Object::particle_systems_iterator b_psys; for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys) @@ -301,7 +301,7 @@ void BlenderSync::sync_integrator() integrator->mesh_light_samples = mesh_light_samples * mesh_light_samples; integrator->subsurface_samples = subsurface_samples * subsurface_samples; integrator->volume_samples = volume_samples * volume_samples; - } + } else { integrator->diffuse_samples = diffuse_samples; integrator->glossy_samples = glossy_samples; @@ -336,7 +336,7 @@ void BlenderSync::sync_film() Film *film = scene->film; Film prevfilm = *film; - + film->exposure = get_float(cscene, "film_exposure"); film->filter_type = (FilterType)get_enum(cscene, "pixel_filter_type", @@ -541,6 +541,7 @@ int BlenderSync::get_denoising_pass(BL::RenderPass& b_pass) MAP_PASS("Shadow B", DENOISING_PASS_SHADOW_B); MAP_PASS("Image", DENOISING_PASS_COLOR); MAP_PASS("Image Variance", DENOISING_PASS_COLOR_VAR); + MAP_PASS("Clean", DENOISING_PASS_CLEAN); #undef MAP_PASS return -1; @@ -570,6 +571,7 @@ array BlenderSync::sync_render_passes(BL::RenderLayer& b_rlay, Pass::add(pass_type, passes); } + scene->film->denoising_flags = 0; PointerRNA crp = RNA_pointer_get(&b_srlay.ptr, "cycles"); if(get_boolean(crp, "denoising_store_passes") && get_boolean(crp, "use_denoising")) @@ -584,6 +586,21 @@ array BlenderSync::sync_render_passes(BL::RenderLayer& b_rlay, b_engine.add_pass("Denoising Shadow B", 3, "XYV", b_srlay.name().c_str()); b_engine.add_pass("Denoising Image", 3, "RGB", b_srlay.name().c_str()); b_engine.add_pass("Denoising Image Variance", 3, "RGB", b_srlay.name().c_str()); + +#define MAP_OPTION(name, flag) if(!get_boolean(crp, name)) scene->film->denoising_flags |= flag; + MAP_OPTION("denoising_diffuse_direct", DENOISING_CLEAN_DIFFUSE_DIR); + MAP_OPTION("denoising_diffuse_indirect", DENOISING_CLEAN_DIFFUSE_IND); + MAP_OPTION("denoising_glossy_direct", DENOISING_CLEAN_GLOSSY_DIR); + MAP_OPTION("denoising_glossy_indirect", DENOISING_CLEAN_GLOSSY_IND); + MAP_OPTION("denoising_transmission_direct", DENOISING_CLEAN_TRANSMISSION_DIR); + MAP_OPTION("denoising_transmission_indirect", DENOISING_CLEAN_TRANSMISSION_IND); + MAP_OPTION("denoising_subsurface_direct", DENOISING_CLEAN_SUBSURFACE_DIR); + MAP_OPTION("denoising_subsurface_indirect", DENOISING_CLEAN_SUBSURFACE_IND); +#undef MAP_OPTION + + if(scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES) { + b_engine.add_pass("Denoising Clean", 3, "RGB", b_srlay.name().c_str()); + } } #ifdef __KERNEL_DEBUG__ if(get_boolean(crp, "pass_debug_bvh_traversed_nodes")) { @@ -633,7 +650,7 @@ SceneParams BlenderSync::get_scene_params(BL::Scene& b_scene, params.shadingsystem = SHADINGSYSTEM_SVM; else if(shadingsystem == 1) params.shadingsystem = SHADINGSYSTEM_OSL; - + if(background || DebugFlags().viewport_static_bvh) params.bvh_type = SceneParams::BVH_STATIC; else @@ -662,7 +679,15 @@ SceneParams BlenderSync::get_scene_params(BL::Scene& b_scene, params.texture_limit = 0; } - params.bvh_layout = DebugFlags().cpu.bvh_layout; + /* TODO(sergey): Once OSL supports per-microarchitecture optimization get + * rid of this. + */ + if(params.shadingsystem == SHADINGSYSTEM_OSL) { + params.bvh_layout = BVH_LAYOUT_BVH4; + } + else { + params.bvh_layout = DebugFlags().cpu.bvh_layout; + } return params; } @@ -698,7 +723,7 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine, /* device type */ vector& devices = Device::available_devices(); - + /* device default CPU */ foreach(DeviceInfo& device, devices) { if(device.type == DEVICE_CPU) { @@ -773,7 +798,7 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine, int aa_samples = get_int(cscene, "aa_samples"); int preview_samples = get_int(cscene, "preview_samples"); int preview_aa_samples = get_int(cscene, "preview_aa_samples"); - + if(get_boolean(cscene, "use_square_samples")) { aa_samples = aa_samples * aa_samples; preview_aa_samples = preview_aa_samples * preview_aa_samples; @@ -869,7 +894,7 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine, params.shadingsystem = SHADINGSYSTEM_SVM; else if(shadingsystem == 1) params.shadingsystem = SHADINGSYSTEM_OSL; - + /* color managagement */ #ifdef GLEW_MX /* When using GLEW MX we need to check whether we've got an OpenGL @@ -894,4 +919,3 @@ SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine, } CCL_NAMESPACE_END - diff --git a/intern/cycles/blender/blender_sync.h b/intern/cycles/blender/blender_sync.h index 1e7b0b32518e..5e63f76033d2 100644 --- a/intern/cycles/blender/blender_sync.h +++ b/intern/cycles/blender/blender_sync.h @@ -214,4 +214,3 @@ class BlenderSync { CCL_NAMESPACE_END #endif /* __BLENDER_SYNC_H__ */ - diff --git a/intern/cycles/blender/blender_util.h b/intern/cycles/blender/blender_util.h index 5176f9c3b502..7e61888348b8 100644 --- a/intern/cycles/blender/blender_util.h +++ b/intern/cycles/blender/blender_util.h @@ -293,7 +293,7 @@ static inline int4 get_int4(const BL::Array& array) return make_int4(array[0], array[1], array[2], array[3]); } -static inline uint get_layer(const BL::Array& array) +static inline uint get_layer(const BL::Array& array) { uint layer = 0; @@ -304,8 +304,8 @@ static inline uint get_layer(const BL::Array& array) return layer; } -static inline uint get_layer(const BL::Array& array, - const BL::Array& local_array, +static inline uint get_layer(const BL::Array& array, + const BL::Array& local_array, bool is_light = false, uint scene_layers = (1 << 20) - 1) { diff --git a/intern/cycles/bvh/CMakeLists.txt b/intern/cycles/bvh/CMakeLists.txt index b8171e7f70df..fcd28572fdf5 100644 --- a/intern/cycles/bvh/CMakeLists.txt +++ b/intern/cycles/bvh/CMakeLists.txt @@ -10,6 +10,7 @@ set(SRC bvh.cpp bvh2.cpp bvh4.cpp + bvh8.cpp bvh_binning.cpp bvh_build.cpp bvh_node.cpp @@ -22,6 +23,7 @@ set(SRC_HEADERS bvh.h bvh2.h bvh4.h + bvh8.h bvh_binning.h bvh_build.h bvh_node.h diff --git a/intern/cycles/bvh/bvh.cpp b/intern/cycles/bvh/bvh.cpp index b524ca07d8dc..bc73a3ad264c 100644 --- a/intern/cycles/bvh/bvh.cpp +++ b/intern/cycles/bvh/bvh.cpp @@ -22,6 +22,7 @@ #include "bvh/bvh2.h" #include "bvh/bvh4.h" +#include "bvh/bvh8.h" #include "bvh/bvh_build.h" #include "bvh/bvh_node.h" @@ -38,6 +39,7 @@ const char *bvh_layout_name(BVHLayout layout) switch(layout) { case BVH_LAYOUT_BVH2: return "BVH2"; case BVH_LAYOUT_BVH4: return "BVH4"; + case BVH_LAYOUT_BVH8: return "BVH8"; case BVH_LAYOUT_NONE: return "NONE"; case BVH_LAYOUT_ALL: return "ALL"; } @@ -92,6 +94,8 @@ BVH *BVH::create(const BVHParams& params, const vector& objects) return new BVH2(params, objects); case BVH_LAYOUT_BVH4: return new BVH4(params, objects); + case BVH_LAYOUT_BVH8: + return new BVH8(params, objects); case BVH_LAYOUT_NONE: case BVH_LAYOUT_ALL: break; @@ -215,6 +219,38 @@ void BVH::refit_primitives(int start, int end, BoundBox& bbox, uint& visibility) } } visibility |= ob->visibility_for_tracing(); + + } +} + +bool BVH::leaf_check(const BVHNode *node, BVH_TYPE bvh) +{ + if(node->is_leaf()) { + return node->is_unaligned; + } + else { + return node_is_unaligned(node, bvh); + } +} + +bool BVH::node_is_unaligned(const BVHNode *node, BVH_TYPE bvh) +{ + const BVHNode *node0 = node->get_child(0); + const BVHNode *node1 = node->get_child(1); + + switch(bvh) { + case bvh2: + return node0->is_unaligned || node1->is_unaligned; + break; + case bvh4: + return leaf_check(node0, bvh2) || leaf_check(node1, bvh2); + break; + case bvh8: + return leaf_check(node0, bvh4) || leaf_check(node1, bvh4); + break; + default: + assert(0); + return false; } } @@ -291,8 +327,8 @@ void BVH::pack_instances(size_t nodes_size, size_t leaf_nodes_size) * BVH's are stored in global arrays. This function merges them into the * top level BVH, adjusting indexes and offsets where appropriate. */ - /* TODO(sergey): This code needs adjustment for wider BVH than 4. */ const bool use_qbvh = (params.bvh_layout == BVH_LAYOUT_BVH4); + const bool use_obvh = (params.bvh_layout == BVH_LAYOUT_BVH8); /* Adjust primitive index to point to the triangle in the global array, for * meshes with transform applied and already in the top level BVH. @@ -469,14 +505,26 @@ void BVH::pack_instances(size_t nodes_size, size_t leaf_nodes_size) for(size_t i = 0, j = 0; i < bvh_nodes_size; j++) { size_t nsize, nsize_bbox; if(bvh_nodes[i].x & PATH_RAY_NODE_UNALIGNED) { - nsize = use_qbvh - ? BVH_UNALIGNED_QNODE_SIZE - : BVH_UNALIGNED_NODE_SIZE; - nsize_bbox = (use_qbvh)? 13: 0; + if(use_obvh) { + nsize = BVH_UNALIGNED_ONODE_SIZE; + nsize_bbox = BVH_UNALIGNED_ONODE_SIZE-1; + } + else { + nsize = use_qbvh + ? BVH_UNALIGNED_QNODE_SIZE + : BVH_UNALIGNED_NODE_SIZE; + nsize_bbox = (use_qbvh) ? BVH_UNALIGNED_QNODE_SIZE-1 : 0; + } } else { - nsize = (use_qbvh)? BVH_QNODE_SIZE: BVH_NODE_SIZE; - nsize_bbox = (use_qbvh)? 7: 0; + if(use_obvh) { + nsize = BVH_ONODE_SIZE; + nsize_bbox = BVH_ONODE_SIZE-1; + } + else { + nsize = (use_qbvh)? BVH_QNODE_SIZE: BVH_NODE_SIZE; + nsize_bbox = (use_qbvh)? BVH_QNODE_SIZE-1 : 0; + } } memcpy(pack_nodes + pack_nodes_offset, @@ -485,16 +533,29 @@ void BVH::pack_instances(size_t nodes_size, size_t leaf_nodes_size) /* Modify offsets into arrays */ int4 data = bvh_nodes[i + nsize_bbox]; - - data.z += (data.z < 0)? -noffset_leaf: noffset; - data.w += (data.w < 0)? -noffset_leaf: noffset; - - if(use_qbvh) { - data.x += (data.x < 0)? -noffset_leaf: noffset; - data.y += (data.y < 0)? -noffset_leaf: noffset; + int4 data1 = bvh_nodes[i + nsize_bbox-1]; + if(use_obvh) { + data.z += (data.z < 0) ? -noffset_leaf : noffset; + data.w += (data.w < 0) ? -noffset_leaf : noffset; + data.x += (data.x < 0) ? -noffset_leaf : noffset; + data.y += (data.y < 0) ? -noffset_leaf : noffset; + data1.z += (data1.z < 0) ? -noffset_leaf : noffset; + data1.w += (data1.w < 0) ? -noffset_leaf : noffset; + data1.x += (data1.x < 0) ? -noffset_leaf : noffset; + data1.y += (data1.y < 0) ? -noffset_leaf : noffset; + } + else { + data.z += (data.z < 0) ? -noffset_leaf : noffset; + data.w += (data.w < 0) ? -noffset_leaf : noffset; + if(use_qbvh) { + data.x += (data.x < 0)? -noffset_leaf: noffset; + data.y += (data.y < 0)? -noffset_leaf: noffset; + } } - pack_nodes[pack_nodes_offset + nsize_bbox] = data; + if(use_obvh) { + pack_nodes[pack_nodes_offset + nsize_bbox - 1] = data1; + } /* Usually this copies nothing, but we better * be prepared for possible node size extension. diff --git a/intern/cycles/bvh/bvh.h b/intern/cycles/bvh/bvh.h index 6a82f9156928..86be0bae4be3 100644 --- a/intern/cycles/bvh/bvh.h +++ b/intern/cycles/bvh/bvh.h @@ -73,6 +73,12 @@ struct PackedBVH { } }; +enum BVH_TYPE { + bvh2, + bvh4, + bvh8 +}; + /* BVH */ class BVH @@ -93,6 +99,8 @@ class BVH /* Refit range of primitives. */ void refit_primitives(int start, int end, BoundBox& bbox, uint& visibility); + static __forceinline bool leaf_check(const BVHNode *node, BVH_TYPE bvh); + static bool node_is_unaligned(const BVHNode *node, BVH_TYPE bvh); /* triangles and strands */ void pack_primitives(); diff --git a/intern/cycles/bvh/bvh2.cpp b/intern/cycles/bvh/bvh2.cpp index 9d89d2b6afbf..4a423c165591 100644 --- a/intern/cycles/bvh/bvh2.cpp +++ b/intern/cycles/bvh/bvh2.cpp @@ -25,13 +25,6 @@ CCL_NAMESPACE_BEGIN -static bool node_bvh_is_unaligned(const BVHNode *node) -{ - const BVHNode *node0 = node->get_child(0), - *node1 = node->get_child(1); - return node0->is_unaligned || node1->is_unaligned; -} - BVH2::BVH2(const BVHParams& params_, const vector& objects_) : BVH(params_, objects_) { @@ -195,7 +188,7 @@ void BVH2::pack_nodes(const BVHNode *root) } else { stack.push_back(BVHStackEntry(root, nextNodeIdx)); - nextNodeIdx += node_bvh_is_unaligned(root) + nextNodeIdx += node_is_unaligned(root, bvh2) ? BVH_UNALIGNED_NODE_SIZE : BVH_NODE_SIZE; } @@ -218,7 +211,7 @@ void BVH2::pack_nodes(const BVHNode *root) } else { idx[i] = nextNodeIdx; - nextNodeIdx += node_bvh_is_unaligned(e.node->get_child(i)) + nextNodeIdx += node_is_unaligned(e.node->get_child(i), bvh2) ? BVH_UNALIGNED_NODE_SIZE : BVH_NODE_SIZE; } diff --git a/intern/cycles/bvh/bvh4.cpp b/intern/cycles/bvh/bvh4.cpp index 4faf47af7bb5..a449587e6076 100644 --- a/intern/cycles/bvh/bvh4.cpp +++ b/intern/cycles/bvh/bvh4.cpp @@ -30,27 +30,6 @@ CCL_NAMESPACE_BEGIN * Perhaps we can merge nodes in actual tree and make our * life easier all over the place. */ -static bool node_qbvh_is_unaligned(const BVHNode *node) -{ - const BVHNode *node0 = node->get_child(0), - *node1 = node->get_child(1); - bool has_unaligned = false; - if(node0->is_leaf()) { - has_unaligned |= node0->is_unaligned; - } - else { - has_unaligned |= node0->get_child(0)->is_unaligned; - has_unaligned |= node0->get_child(1)->is_unaligned; - } - if(node1->is_leaf()) { - has_unaligned |= node1->is_unaligned; - } - else { - has_unaligned |= node1->get_child(0)->is_unaligned; - has_unaligned |= node1->get_child(1)->is_unaligned; - } - return has_unaligned; -} BVH4::BVH4(const BVHParams& params_, const vector& objects_) : BVH(params_, objects_) @@ -304,7 +283,7 @@ void BVH4::pack_nodes(const BVHNode *root) } else { stack.push_back(BVHStackEntry(root, nextNodeIdx)); - nextNodeIdx += node_qbvh_is_unaligned(root) + nextNodeIdx += node_is_unaligned(root, bvh4) ? BVH_UNALIGNED_QNODE_SIZE : BVH_QNODE_SIZE; } @@ -348,7 +327,7 @@ void BVH4::pack_nodes(const BVHNode *root) } else { idx = nextNodeIdx; - nextNodeIdx += node_qbvh_is_unaligned(nodes[i]) + nextNodeIdx += node_is_unaligned(nodes[i], bvh4) ? BVH_UNALIGNED_QNODE_SIZE : BVH_QNODE_SIZE; } @@ -438,7 +417,7 @@ void BVH4::refit_node(int idx, bool leaf, BoundBox& bbox, uint& visibility) visibility, 0.0f, 1.0f, - 4); + num_nodes); } else { pack_aligned_node(idx, @@ -447,7 +426,7 @@ void BVH4::refit_node(int idx, bool leaf, BoundBox& bbox, uint& visibility) visibility, 0.0f, 1.0f, - 4); + num_nodes); } } } diff --git a/intern/cycles/bvh/bvh8.cpp b/intern/cycles/bvh/bvh8.cpp new file mode 100644 index 000000000000..70d003d938aa --- /dev/null +++ b/intern/cycles/bvh/bvh8.cpp @@ -0,0 +1,512 @@ +/* +* Original code Copyright 2017, Intel Corporation +* Modifications Copyright 2018, Blender Foundation. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Intel Corporation nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "bvh/bvh8.h" + +#include "render/mesh.h" +#include "render/object.h" + +#include "bvh/bvh_node.h" +#include "bvh/bvh_unaligned.h" + +CCL_NAMESPACE_BEGIN + +BVH8::BVH8(const BVHParams& params_, const vector& objects_) +: BVH(params_, objects_) +{ +} + +void BVH8::pack_leaf(const BVHStackEntry& e, const LeafNode *leaf) +{ + float4 data[BVH_ONODE_LEAF_SIZE]; + memset(data, 0, sizeof(data)); + if(leaf->num_triangles() == 1 && pack.prim_index[leaf->lo] == -1) { + /* object */ + data[0].x = __int_as_float(~(leaf->lo)); + data[0].y = __int_as_float(0); + } + else { + /* triangle */ + data[0].x = __int_as_float(leaf->lo); + data[0].y = __int_as_float(leaf->hi); + } + data[0].z = __uint_as_float(leaf->visibility); + if(leaf->num_triangles() != 0) { + data[0].w = __uint_as_float(pack.prim_type[leaf->lo]); + } + + memcpy(&pack.leaf_nodes[e.idx], data, sizeof(float4)*BVH_ONODE_LEAF_SIZE); +} + +void BVH8::pack_inner(const BVHStackEntry& e, + const BVHStackEntry *en, + int num) +{ + bool has_unaligned = false; + /* Check whether we have to create unaligned node or all nodes are aligned + * and we can cut some corner here. + */ + if(params.use_unaligned_nodes) { + for(int i = 0; i < num; i++) { + if(en[i].node->is_unaligned) { + has_unaligned = true; + break; + } + } + } + if(has_unaligned) { + /* There's no unaligned children, pack into AABB node. */ + pack_unaligned_inner(e, en, num); + } + else { + /* Create unaligned node with orientation transform for each of the + * children. + */ + pack_aligned_inner(e, en, num); + } +} + +void BVH8::pack_aligned_inner(const BVHStackEntry& e, + const BVHStackEntry *en, + int num) +{ + BoundBox bounds[8]; + int child[8]; + for(int i = 0; i < num; ++i) { + bounds[i] = en[i].node->bounds; + child[i] = en[i].encodeIdx(); + } + pack_aligned_node(e.idx, + bounds, + child, + e.node->visibility, + e.node->time_from, + e.node->time_to, + num); +} + +void BVH8::pack_aligned_node(int idx, + const BoundBox *bounds, + const int *child, + const uint visibility, + const float time_from, + const float time_to, + const int num) +{ + float8 data[8]; + memset(data, 0, sizeof(data)); + + data[0].a = __uint_as_float(visibility & ~PATH_RAY_NODE_UNALIGNED); + data[0].b = time_from; + data[0].c = time_to; + for(int i = 0; i < num; i++) { + float3 bb_min = bounds[i].min; + float3 bb_max = bounds[i].max; + + data[1][i] = bb_min.x; + data[2][i] = bb_max.x; + data[3][i] = bb_min.y; + data[4][i] = bb_max.y; + data[5][i] = bb_min.z; + data[6][i] = bb_max.z; + + data[7][i] = __int_as_float(child[i]); + } + + for(int i = num; i < 8; i++) { + /* We store BB which would never be recorded as intersection + * so kernel might safely assume there are always 4 child nodes. + */ + data[1][i] = FLT_MAX; + data[2][i] = -FLT_MAX; + + data[3][i] = FLT_MAX; + data[4][i] = -FLT_MAX; + + data[5][i] = FLT_MAX; + data[6][i] = -FLT_MAX; + + data[7][i] = __int_as_float(0); + } + memcpy(&pack.nodes[idx], data, sizeof(float4)*BVH_ONODE_SIZE); +} + +void BVH8::pack_unaligned_inner(const BVHStackEntry& e, + const BVHStackEntry *en, + int num) +{ + Transform aligned_space[8]; + BoundBox bounds[8]; + int child[8]; + for(int i = 0; i < num; ++i) { + aligned_space[i] = en[i].node->get_aligned_space(); + bounds[i] = en[i].node->bounds; + child[i] = en[i].encodeIdx(); + } + pack_unaligned_node(e.idx, + aligned_space, + bounds, + child, + e.node->visibility, + e.node->time_from, + e.node->time_to, + num); +} + +void BVH8::pack_unaligned_node(int idx, + const Transform *aligned_space, + const BoundBox *bounds, + const int *child, + const uint visibility, + const float time_from, + const float time_to, + const int num) +{ + float8 data[BVH_UNALIGNED_ONODE_SIZE]; + memset(data, 0, sizeof(data)); + data[0].a = __uint_as_float(visibility | PATH_RAY_NODE_UNALIGNED); + data[0].b = time_from; + data[0].c = time_to; + + for(int i = 0; i < num; i++) { + Transform space = BVHUnaligned::compute_node_transform( + bounds[i], + aligned_space[i]); + + data[1][i] = space.x.x; + data[2][i] = space.x.y; + data[3][i] = space.x.z; + + data[4][i] = space.y.x; + data[5][i] = space.y.y; + data[6][i] = space.y.z; + + data[7][i] = space.z.x; + data[8][i] = space.z.y; + data[9][i] = space.z.z; + + data[10][i] = space.x.w; + data[11][i] = space.y.w; + data[12][i] = space.z.w; + + data[13][i] = __int_as_float(child[i]); + } + + for(int i = num; i < 8; i++) { + /* We store BB which would never be recorded as intersection + * so kernel might safely assume there are always 4 child nodes. + */ + + data[1][i] = 1.0f; + data[2][i] = 0.0f; + data[3][i] = 0.0f; + + data[4][i] = 0.0f; + data[5][i] = 0.0f; + data[6][i] = 0.0f; + + data[7][i] = 0.0f; + data[8][i] = 0.0f; + data[9][i] = 0.0f; + + data[10][i] = -FLT_MAX; + data[11][i] = -FLT_MAX; + data[12][i] = -FLT_MAX; + + data[13][i] = __int_as_float(0); + } + + memcpy(&pack.nodes[idx], data, sizeof(float4)*BVH_UNALIGNED_ONODE_SIZE); +} + +/* Quad SIMD Nodes */ + +void BVH8::pack_nodes(const BVHNode *root) +{ + /* Calculate size of the arrays required. */ + const size_t num_nodes = root->getSubtreeSize(BVH_STAT_ONODE_COUNT); + const size_t num_leaf_nodes = root->getSubtreeSize(BVH_STAT_LEAF_COUNT); + assert(num_leaf_nodes <= num_nodes); + const size_t num_inner_nodes = num_nodes - num_leaf_nodes; + size_t node_size; + if(params.use_unaligned_nodes) { + const size_t num_unaligned_nodes = + root->getSubtreeSize(BVH_STAT_UNALIGNED_INNER_ONODE_COUNT); + node_size = (num_unaligned_nodes * BVH_UNALIGNED_ONODE_SIZE) + + (num_inner_nodes - num_unaligned_nodes) * BVH_ONODE_SIZE; + } + else { + node_size = num_inner_nodes * BVH_ONODE_SIZE; + } + /* Resize arrays. */ + pack.nodes.clear(); + pack.leaf_nodes.clear(); + /* For top level BVH, first merge existing BVH's so we know the offsets. */ + if(params.top_level) { + pack_instances(node_size, num_leaf_nodes*BVH_ONODE_LEAF_SIZE); + } + else { + pack.nodes.resize(node_size); + pack.leaf_nodes.resize(num_leaf_nodes*BVH_ONODE_LEAF_SIZE); + } + + int nextNodeIdx = 0, nextLeafNodeIdx = 0; + + vector stack; + stack.reserve(BVHParams::MAX_DEPTH*2); + if(root->is_leaf()) { + stack.push_back(BVHStackEntry(root, nextLeafNodeIdx++)); + } + else { + stack.push_back(BVHStackEntry(root, nextNodeIdx)); + nextNodeIdx += node_is_unaligned(root, bvh8) + ? BVH_UNALIGNED_ONODE_SIZE + : BVH_ONODE_SIZE; + } + + while(stack.size()) { + BVHStackEntry e = stack.back(); + stack.pop_back(); + + if(e.node->is_leaf()) { + /* leaf node */ + const LeafNode *leaf = reinterpret_cast(e.node); + pack_leaf(e, leaf); + } + else { + /* Inner node. */ + const BVHNode *node = e.node; + const BVHNode *node0 = node->get_child(0); + const BVHNode *node1 = node->get_child(1); + /* Collect nodes. */ + const BVHNode *nodes[8]; + int numnodes = 0; + if(node0->is_leaf()) { + nodes[numnodes++] = node0; + } + else { + const BVHNode *node00 = node0->get_child(0), + *node01 = node0->get_child(1); + if(node00->is_leaf()) { + nodes[numnodes++] = node00; + } + else { + nodes[numnodes++] = node00->get_child(0); + nodes[numnodes++] = node00->get_child(1); + } + if(node01->is_leaf()) { + nodes[numnodes++] = node01; + } + else { + nodes[numnodes++] = node01->get_child(0); + nodes[numnodes++] = node01->get_child(1); + } + } + if(node1->is_leaf()) { + nodes[numnodes++] = node1; + } + else { + const BVHNode *node10 = node1->get_child(0), + *node11 = node1->get_child(1); + if(node10->is_leaf()) { + nodes[numnodes++] = node10; + } + else { + nodes[numnodes++] = node10->get_child(0); + nodes[numnodes++] = node10->get_child(1); + } + if(node11->is_leaf()) { + nodes[numnodes++] = node11; + } + else { + nodes[numnodes++] = node11->get_child(0); + nodes[numnodes++] = node11->get_child(1); + } + } + /* Push entries on the stack. */ + for(int i = 0; i < numnodes; ++i) { + int idx; + if(nodes[i]->is_leaf()) { + idx = nextLeafNodeIdx++; + } + else { + idx = nextNodeIdx; + nextNodeIdx += node_is_unaligned(nodes[i], bvh8) + ? BVH_UNALIGNED_ONODE_SIZE + : BVH_ONODE_SIZE; + } + stack.push_back(BVHStackEntry(nodes[i], idx)); + } + /* Set node. */ + pack_inner(e, &stack[stack.size() - numnodes], numnodes); + } + } + assert(node_size == nextNodeIdx); + /* Root index to start traversal at, to handle case of single leaf node. */ + pack.root_index = (root->is_leaf()) ? -1 : 0; +} + +void BVH8::refit_nodes() +{ + assert(!params.top_level); + + BoundBox bbox = BoundBox::empty; + uint visibility = 0; + refit_node(0, (pack.root_index == -1)? true: false, bbox, visibility); +} + +void BVH8::refit_node(int idx, bool leaf, BoundBox& bbox, uint& visibility) +{ + if(leaf) { + int4 *data = &pack.leaf_nodes[idx]; + int4 c = data[0]; + /* Refit leaf node. */ + for(int prim = c.x; prim < c.y; prim++) { + int pidx = pack.prim_index[prim]; + int tob = pack.prim_object[prim]; + Object *ob = objects[tob]; + + if(pidx == -1) { + /* Object instance. */ + bbox.grow(ob->bounds); + } + else { + /* Primitives. */ + const Mesh *mesh = ob->mesh; + + if(pack.prim_type[prim] & PRIMITIVE_ALL_CURVE) { + /* Curves. */ + int str_offset = (params.top_level) ? mesh->curve_offset : 0; + Mesh::Curve curve = mesh->get_curve(pidx - str_offset); + int k = PRIMITIVE_UNPACK_SEGMENT(pack.prim_type[prim]); + + curve.bounds_grow(k, &mesh->curve_keys[0], &mesh->curve_radius[0], bbox); + + visibility |= PATH_RAY_CURVE; + + /* Motion curves. */ + if(mesh->use_motion_blur) { + Attribute *attr = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION); + + if(attr) { + size_t mesh_size = mesh->curve_keys.size(); + size_t steps = mesh->motion_steps - 1; + float3 *key_steps = attr->data_float3(); + + for(size_t i = 0; i < steps; i++) { + curve.bounds_grow(k, key_steps + i*mesh_size, &mesh->curve_radius[0], bbox); + } + } + } + } + else { + /* Triangles. */ + int tri_offset = (params.top_level) ? mesh->tri_offset : 0; + Mesh::Triangle triangle = mesh->get_triangle(pidx - tri_offset); + const float3 *vpos = &mesh->verts[0]; + + triangle.bounds_grow(vpos, bbox); + + /* Motion triangles. */ + if(mesh->use_motion_blur) { + Attribute *attr = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION); + + if(attr) { + size_t mesh_size = mesh->verts.size(); + size_t steps = mesh->motion_steps - 1; + float3 *vert_steps = attr->data_float3(); + + for(size_t i = 0; i < steps; i++) { + triangle.bounds_grow(vert_steps + i*mesh_size, bbox); + } + } + } + } + } + + visibility |= ob->visibility; + } + + float4 leaf_data[BVH_ONODE_LEAF_SIZE]; + leaf_data[0].x = __int_as_float(c.x); + leaf_data[0].y = __int_as_float(c.y); + leaf_data[0].z = __uint_as_float(visibility); + leaf_data[0].w = __uint_as_float(c.w); + memcpy(&pack.leaf_nodes[idx], leaf_data, sizeof(float4)*BVH_ONODE_LEAF_SIZE); + } + else { + float8 *data = (float8*)&pack.nodes[idx]; + bool is_unaligned = (__float_as_uint(data[0].a) & PATH_RAY_NODE_UNALIGNED) != 0; + /* Refit inner node, set bbox from children. */ + BoundBox child_bbox[8] = { BoundBox::empty, BoundBox::empty, + BoundBox::empty, BoundBox::empty, + BoundBox::empty, BoundBox::empty, + BoundBox::empty, BoundBox::empty }; + int child[8]; + uint child_visibility[8] = { 0 }; + int num_nodes = 0; + + for(int i = 0; i < 8; ++i) { + child[i] = __float_as_int(data[(is_unaligned) ? 13: 7][i]); + + if(child[i] != 0) { + refit_node((child[i] < 0)? -child[i]-1: child[i], (child[i] < 0), + child_bbox[i], child_visibility[i]); + ++num_nodes; + bbox.grow(child_bbox[i]); + visibility |= child_visibility[i]; + } + } + + if(is_unaligned) { + Transform aligned_space[8] = { transform_identity(), transform_identity(), + transform_identity(), transform_identity(), + transform_identity(), transform_identity(), + transform_identity(), transform_identity()}; + pack_unaligned_node(idx, + aligned_space, + child_bbox, + child, + visibility, + 0.0f, + 1.0f, + num_nodes); + } + else { + pack_aligned_node(idx, + child_bbox, + child, + visibility, + 0.0f, + 1.0f, + num_nodes); + } + } +} + +CCL_NAMESPACE_END diff --git a/intern/cycles/bvh/bvh8.h b/intern/cycles/bvh/bvh8.h new file mode 100644 index 000000000000..274a2442c7e6 --- /dev/null +++ b/intern/cycles/bvh/bvh8.h @@ -0,0 +1,98 @@ +/* +* Original code Copyright 2017, Intel Corporation +* Modifications Copyright 2018, Blender Foundation. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Intel Corporation nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef __BVH8_H__ +#define __BVH8_H__ + +#include "bvh/bvh.h" +#include "bvh/bvh_params.h" + +#include "util/util_types.h" +#include "util/util_vector.h" + +CCL_NAMESPACE_BEGIN + +class BVHNode; +struct BVHStackEntry; +class BVHParams; +class BoundBox; +class LeafNode; +class Object; +class Progress; + +#define BVH_ONODE_SIZE 16 +#define BVH_ONODE_LEAF_SIZE 1 +#define BVH_UNALIGNED_ONODE_SIZE 28 + +/* BVH8 +* +* Octo BVH, with each node having eight children, to use with SIMD instructions. +*/ +class BVH8 : public BVH { +protected: + /* constructor */ + friend class BVH; + BVH8(const BVHParams& params, const vector& objects); + + /* pack */ + void pack_nodes(const BVHNode *root); + + void pack_leaf(const BVHStackEntry& e, const LeafNode *leaf); + void pack_inner(const BVHStackEntry& e, const BVHStackEntry *en, int num); + + void pack_aligned_inner(const BVHStackEntry& e, + const BVHStackEntry *en, + int num); + void pack_aligned_node(int idx, + const BoundBox *bounds, + const int *child, + const uint visibility, + const float time_from, + const float time_to, + const int num); + + void pack_unaligned_inner(const BVHStackEntry& e, + const BVHStackEntry *en, + int num); + void pack_unaligned_node(int idx, + const Transform *aligned_space, + const BoundBox *bounds, + const int *child, + const uint visibility, + const float time_from, + const float time_to, + const int num); + + /* refit */ + void refit_nodes(); + void refit_node(int idx, bool leaf, BoundBox& bbox, uint& visibility); +}; + +CCL_NAMESPACE_END + +#endif /* __BVH8_H__ */ diff --git a/intern/cycles/bvh/bvh_binning.cpp b/intern/cycles/bvh/bvh_binning.cpp index 63a7fc116680..f574f31b3587 100644 --- a/intern/cycles/bvh/bvh_binning.cpp +++ b/intern/cycles/bvh/bvh_binning.cpp @@ -251,4 +251,3 @@ void BVHObjectBinning::split(BVHReference* prims, } CCL_NAMESPACE_END - diff --git a/intern/cycles/bvh/bvh_node.cpp b/intern/cycles/bvh/bvh_node.cpp index 24af919ff467..fd8b49776992 100644 --- a/intern/cycles/bvh/bvh_node.cpp +++ b/intern/cycles/bvh/bvh_node.cpp @@ -61,6 +61,55 @@ int BVHNode::getSubtreeSize(BVH_STAT stat) const } } return cnt; + case BVH_STAT_ONODE_COUNT: + cnt = 1; + for(int i = 0; i < num_children(); i++) { + BVHNode *node = get_child(i); + if(node->is_leaf()) { + cnt += 1; + } + else { + for(int j = 0; j < node->num_children(); j++) + { + BVHNode *node_next = node->get_child(j); + if(node_next->is_leaf()) { + cnt += 1; + } + else { + for(int k = 0; k < node_next->num_children(); k++) { + cnt += node_next->get_child(k)->getSubtreeSize(stat); + } + } + } + } + } + return cnt; + case BVH_STAT_UNALIGNED_INNER_ONODE_COUNT: + { + bool has_unaligned = false; + for(int i = 0; i < num_children(); i++) { + BVHNode *node = get_child(i); + if(node->is_leaf()) { + has_unaligned |= node->is_unaligned; + } + else { + for(int j = 0; j < node->num_children(); j++) { + BVHNode *node_next = node->get_child(j); + if(node_next->is_leaf()) { + has_unaligned |= node_next->is_unaligned; + } + else { + for(int k = 0; k < node_next->num_children(); k++) { + cnt += node_next->get_child(k)->getSubtreeSize(stat); + has_unaligned |= node_next->get_child(k)->is_unaligned; + } + } + } + } + } + cnt += has_unaligned? 1: 0; + } + return cnt; case BVH_STAT_ALIGNED_COUNT: if(!is_unaligned) { cnt = 1; @@ -206,7 +255,7 @@ void InnerNode::print(int depth) const { for(int i = 0; i < depth; i++) printf(" "); - + printf("inner node %p\n", (void*)this); if(children[0]) @@ -219,9 +268,8 @@ void LeafNode::print(int depth) const { for(int i = 0; i < depth; i++) printf(" "); - + printf("leaf node %d to %d\n", lo, hi); } CCL_NAMESPACE_END - diff --git a/intern/cycles/bvh/bvh_node.h b/intern/cycles/bvh/bvh_node.h index 94cf5ab730c2..ed89d52a50a2 100644 --- a/intern/cycles/bvh/bvh_node.h +++ b/intern/cycles/bvh/bvh_node.h @@ -39,6 +39,8 @@ enum BVH_STAT { BVH_STAT_ALIGNED_LEAF_COUNT, BVH_STAT_UNALIGNED_LEAF_COUNT, BVH_STAT_DEPTH, + BVH_STAT_ONODE_COUNT, + BVH_STAT_UNALIGNED_INNER_ONODE_COUNT, }; class BVHParams; diff --git a/intern/cycles/bvh/bvh_sort.cpp b/intern/cycles/bvh/bvh_sort.cpp index b40bf5bb21ba..f4f73ab2f2ff 100644 --- a/intern/cycles/bvh/bvh_sort.cpp +++ b/intern/cycles/bvh/bvh_sort.cpp @@ -201,4 +201,3 @@ void bvh_reference_sort(int start, } CCL_NAMESPACE_END - diff --git a/intern/cycles/device/device.h b/intern/cycles/device/device.h index b856bdd9d01b..2400788c8331 100644 --- a/intern/cycles/device/device.h +++ b/intern/cycles/device/device.h @@ -123,7 +123,7 @@ class DeviceRequestedFeatures { /* Use OpenSubdiv patch evaluation */ bool use_patch_evaluation; - + /* Use Transparent shadows */ bool use_transparent; @@ -294,7 +294,7 @@ class Device { /* open shading language, only for CPU device */ virtual void *osl_memory() { return NULL; } - /* load/compile kernels, must be called before adding tasks */ + /* load/compile kernels, must be called before adding tasks */ virtual bool load_kernels( const DeviceRequestedFeatures& /*requested_features*/) { return true; } @@ -304,7 +304,7 @@ class Device { virtual void task_add(DeviceTask& task) = 0; virtual void task_wait() = 0; virtual void task_cancel() = 0; - + /* opengl drawing */ virtual void draw_pixels(device_memory& mem, int y, int w, int h, int dx, int dy, int width, int height, bool transparent, @@ -362,4 +362,3 @@ class Device { CCL_NAMESPACE_END #endif /* __DEVICE_H__ */ - diff --git a/intern/cycles/device/device_cpu.cpp b/intern/cycles/device/device_cpu.cpp index 6be60f8bbb6e..7c72ab1a0093 100644 --- a/intern/cycles/device/device_cpu.cpp +++ b/intern/cycles/device/device_cpu.cpp @@ -179,8 +179,8 @@ class CPUDevice : public Device KernelFunctions convert_to_byte_kernel; KernelFunctions shader_kernel; - KernelFunctions filter_divide_shadow_kernel; - KernelFunctions filter_get_feature_kernel; + KernelFunctions filter_divide_shadow_kernel; + KernelFunctions filter_get_feature_kernel; KernelFunctions filter_detect_outliers_kernel; KernelFunctions filter_combine_halves_kernel; @@ -459,18 +459,6 @@ class CPUDevice : public Device } }; - bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task) - { - TilesInfo *tiles = (TilesInfo*) task->tiles_mem.host_pointer; - for(int i = 0; i < 9; i++) { - tiles->buffers[i] = buffers[i]; - } - - task->tiles_mem.copy_to_device(); - - return true; - } - bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr, DenoisingTask *task) { @@ -483,9 +471,10 @@ class CPUDevice : public Device int w = align_up(rect.z-rect.x, 4); int h = rect.w-rect.y; - float *blurDifference = (float*) task->nlm_state.temporary_1_ptr; - float *difference = (float*) task->nlm_state.temporary_2_ptr; - float *weightAccum = (float*) task->nlm_state.temporary_3_ptr; + float *temporary_mem = (float*) task->buffer.temporary_mem.device_pointer; + float *blurDifference = temporary_mem; + float *difference = temporary_mem + task->buffer.pass_stride; + float *weightAccum = temporary_mem + 2*task->buffer.pass_stride; memset(weightAccum, 0, sizeof(float)*w*h); memset((float*) out_ptr, 0, sizeof(float)*w*h); @@ -549,8 +538,9 @@ class CPUDevice : public Device mem_zero(task->storage.XtWX); mem_zero(task->storage.XtWY); - float *difference = (float*) task->reconstruction_state.temporary_1_ptr; - float *blurDifference = (float*) task->reconstruction_state.temporary_2_ptr; + float *temporary_mem = (float*) task->buffer.temporary_mem.device_pointer; + float *difference = temporary_mem; + float *blurDifference = temporary_mem + task->buffer.pass_stride; int r = task->radius; for(int i = 0; i < (2*r+1)*(2*r+1); i++) { @@ -626,7 +616,7 @@ class CPUDevice : public Device for(int y = task->rect.y; y < task->rect.w; y++) { for(int x = task->rect.x; x < task->rect.z; x++) { filter_divide_shadow_kernel()(task->render_buffer.samples, - task->tiles, + task->tile_info, x, y, (float*) a_ptr, (float*) b_ptr, @@ -635,7 +625,7 @@ class CPUDevice : public Device (float*) buffer_variance_ptr, &task->rect.x, task->render_buffer.pass_stride, - task->render_buffer.denoising_data_offset); + task->render_buffer.offset); } } return true; @@ -650,7 +640,7 @@ class CPUDevice : public Device for(int y = task->rect.y; y < task->rect.w; y++) { for(int x = task->rect.x; x < task->rect.z; x++) { filter_get_feature_kernel()(task->render_buffer.samples, - task->tiles, + task->tile_info, mean_offset, variance_offset, x, y, @@ -658,7 +648,7 @@ class CPUDevice : public Device (float*) variance_ptr, &task->rect.x, task->render_buffer.pass_stride, - task->render_buffer.denoising_data_offset); + task->render_buffer.offset); } } return true; @@ -711,7 +701,7 @@ class CPUDevice : public Device } } - void denoise(DeviceTask &task, DenoisingTask& denoising, RenderTile &tile) + void denoise(DenoisingTask& denoising, RenderTile &tile) { tile.sample = tile.start_sample + tile.num_samples; @@ -722,23 +712,12 @@ class CPUDevice : public Device denoising.functions.combine_halves = function_bind(&CPUDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising); denoising.functions.get_feature = function_bind(&CPUDevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising); denoising.functions.detect_outliers = function_bind(&CPUDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising); - denoising.functions.set_tiles = function_bind(&CPUDevice::denoising_set_tiles, this, _1, &denoising); denoising.filter_area = make_int4(tile.x, tile.y, tile.w, tile.h); denoising.render_buffer.samples = tile.sample; + denoising.buffer.gpu_temporary_mem = false; - RenderTile rtiles[9]; - rtiles[4] = tile; - task.map_neighbor_tiles(rtiles, this); - denoising.tiles_from_rendertiles(rtiles); - - denoising.init_from_devicetask(task); - - denoising.run_denoising(); - - task.unmap_neighbor_tiles(rtiles, this); - - task.update_progress(&tile, tile.w*tile.h); + denoising.run_denoising(&tile); } void thread_render(DeviceTask& task) @@ -766,7 +745,7 @@ class CPUDevice : public Device } RenderTile tile; - DenoisingTask denoising(this); + DenoisingTask denoising(this, task); while(task.acquire_tile(this, tile)) { if(tile.task == RenderTile::PATH_TRACE) { @@ -779,7 +758,9 @@ class CPUDevice : public Device } } else if(tile.task == RenderTile::DENOISE) { - denoise(task, denoising, tile); + denoise(denoising, tile); + + task.update_progress(&tile, tile.w*tile.h); } task.release_tile(tile); @@ -1047,9 +1028,12 @@ void device_cpu_info(vector& devices) info.num = 0; info.advanced_shading = true; info.bvh_layout_mask = BVH_LAYOUT_BVH2; - if (system_cpu_support_sse2()) { + if(system_cpu_support_sse2()) { info.bvh_layout_mask |= BVH_LAYOUT_BVH4; } + if(system_cpu_support_avx2()) { + info.bvh_layout_mask |= BVH_LAYOUT_BVH8; + } info.has_volume_decoupled = true; info.has_osl = true; info.has_half_images = true; diff --git a/intern/cycles/device/device_cuda.cpp b/intern/cycles/device/device_cuda.cpp index 9d893ee61ad1..da8e49f129f0 100644 --- a/intern/cycles/device/device_cuda.cpp +++ b/intern/cycles/device/device_cuda.cpp @@ -385,7 +385,7 @@ class CUDADevice : public Device VLOG(1) << "Found nvcc " << nvcc << ", CUDA version " << cuda_version << "."; - const int major = cuda_version / 10, minor = cuda_version & 10; + const int major = cuda_version / 10, minor = cuda_version % 10; if(cuda_version == 0) { cuda_error_message("CUDA nvcc compiler version could not be parsed."); return false; @@ -1072,6 +1072,7 @@ class CUDADevice : public Device CUarray_format_enum format; switch(mem.data_type) { case TYPE_UCHAR: format = CU_AD_FORMAT_UNSIGNED_INT8; break; + case TYPE_UINT16: format = CU_AD_FORMAT_UNSIGNED_INT16; break; case TYPE_UINT: format = CU_AD_FORMAT_UNSIGNED_INT32; break; case TYPE_INT: format = CU_AD_FORMAT_SIGNED_INT32; break; case TYPE_FLOAT: format = CU_AD_FORMAT_FLOAT; break; @@ -1251,18 +1252,6 @@ class CUDADevice : public Device } } - bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task) - { - TilesInfo *tiles = (TilesInfo*) task->tiles_mem.host_pointer; - for(int i = 0; i < 9; i++) { - tiles->buffers[i] = buffers[i]; - } - - task->tiles_mem.copy_to_device(); - - return !have_error(); - } - #define CUDA_GET_BLOCKSIZE(func, w, h) \ int threads_per_block; \ cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, func)); \ @@ -1305,23 +1294,19 @@ class CUDADevice : public Device float a = task->nlm_state.a; float k_2 = task->nlm_state.k_2; - int shift_stride = stride*h; + int pass_stride = task->buffer.pass_stride; int num_shifts = (2*r+1)*(2*r+1); - int mem_size = sizeof(float)*shift_stride*num_shifts; int channel_offset = 0; - device_only_memory temporary_mem(this, "Denoising temporary_mem"); - temporary_mem.alloc_to_device(2*mem_size); - if(have_error()) return false; - CUdeviceptr difference = cuda_device_ptr(temporary_mem.device_pointer); - CUdeviceptr blurDifference = difference + mem_size; + CUdeviceptr difference = cuda_device_ptr(task->buffer.temporary_mem.device_pointer); + CUdeviceptr blurDifference = difference + sizeof(float)*pass_stride*num_shifts; + CUdeviceptr weightAccum = difference + 2*sizeof(float)*pass_stride*num_shifts; - CUdeviceptr weightAccum = task->nlm_state.temporary_3_ptr; - cuda_assert(cuMemsetD8(weightAccum, 0, sizeof(float)*shift_stride)); - cuda_assert(cuMemsetD8(out_ptr, 0, sizeof(float)*shift_stride)); + cuda_assert(cuMemsetD8(weightAccum, 0, sizeof(float)*pass_stride)); + cuda_assert(cuMemsetD8(out_ptr, 0, sizeof(float)*pass_stride)); { CUfunction cuNLMCalcDifference, cuNLMBlur, cuNLMCalcWeight, cuNLMUpdateOutput; @@ -1337,10 +1322,10 @@ class CUDADevice : public Device CUDA_GET_BLOCKSIZE_1D(cuNLMCalcDifference, w*h, num_shifts); - void *calc_difference_args[] = {&guide_ptr, &variance_ptr, &difference, &w, &h, &stride, &shift_stride, &r, &channel_offset, &a, &k_2}; - void *blur_args[] = {&difference, &blurDifference, &w, &h, &stride, &shift_stride, &r, &f}; - void *calc_weight_args[] = {&blurDifference, &difference, &w, &h, &stride, &shift_stride, &r, &f}; - void *update_output_args[] = {&blurDifference, &image_ptr, &out_ptr, &weightAccum, &w, &h, &stride, &shift_stride, &r, &f}; + void *calc_difference_args[] = {&guide_ptr, &variance_ptr, &difference, &w, &h, &stride, &pass_stride, &r, &channel_offset, &a, &k_2}; + void *blur_args[] = {&difference, &blurDifference, &w, &h, &stride, &pass_stride, &r, &f}; + void *calc_weight_args[] = {&blurDifference, &difference, &w, &h, &stride, &pass_stride, &r, &f}; + void *update_output_args[] = {&blurDifference, &image_ptr, &out_ptr, &weightAccum, &w, &h, &stride, &pass_stride, &r, &f}; CUDA_LAUNCH_KERNEL_1D(cuNLMCalcDifference, calc_difference_args); CUDA_LAUNCH_KERNEL_1D(cuNLMBlur, blur_args); @@ -1349,8 +1334,6 @@ class CUDADevice : public Device CUDA_LAUNCH_KERNEL_1D(cuNLMUpdateOutput, update_output_args); } - temporary_mem.free(); - { CUfunction cuNLMNormalize; cuda_assert(cuModuleGetFunction(&cuNLMNormalize, cuFilterModule, "kernel_cuda_filter_nlm_normalize")); @@ -1534,7 +1517,7 @@ class CUDADevice : public Device task->rect.w-task->rect.y); void *args[] = {&task->render_buffer.samples, - &task->tiles_mem.device_pointer, + &task->tile_info_mem.device_pointer, &a_ptr, &b_ptr, &sample_variance_ptr, @@ -1542,7 +1525,7 @@ class CUDADevice : public Device &buffer_variance_ptr, &task->rect, &task->render_buffer.pass_stride, - &task->render_buffer.denoising_data_offset}; + &task->render_buffer.offset}; CUDA_LAUNCH_KERNEL(cuFilterDivideShadow, args); cuda_assert(cuCtxSynchronize()); @@ -1568,14 +1551,14 @@ class CUDADevice : public Device task->rect.w-task->rect.y); void *args[] = {&task->render_buffer.samples, - &task->tiles_mem.device_pointer, + &task->tile_info_mem.device_pointer, &mean_offset, &variance_offset, &mean_ptr, &variance_ptr, &task->rect, &task->render_buffer.pass_stride, - &task->render_buffer.denoising_data_offset}; + &task->render_buffer.offset}; CUDA_LAUNCH_KERNEL(cuFilterGetFeature, args); cuda_assert(cuCtxSynchronize()); @@ -1613,7 +1596,7 @@ class CUDADevice : public Device return !have_error(); } - void denoise(RenderTile &rtile, DenoisingTask& denoising, const DeviceTask &task) + void denoise(RenderTile &rtile, DenoisingTask& denoising) { denoising.functions.construct_transform = function_bind(&CUDADevice::denoising_construct_transform, this, &denoising); denoising.functions.reconstruct = function_bind(&CUDADevice::denoising_reconstruct, this, _1, _2, _3, &denoising); @@ -1622,21 +1605,12 @@ class CUDADevice : public Device denoising.functions.combine_halves = function_bind(&CUDADevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising); denoising.functions.get_feature = function_bind(&CUDADevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising); denoising.functions.detect_outliers = function_bind(&CUDADevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising); - denoising.functions.set_tiles = function_bind(&CUDADevice::denoising_set_tiles, this, _1, &denoising); denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h); denoising.render_buffer.samples = rtile.sample; + denoising.buffer.gpu_temporary_mem = true; - RenderTile rtiles[9]; - rtiles[4] = rtile; - task.map_neighbor_tiles(rtiles, this); - denoising.tiles_from_rendertiles(rtiles); - - denoising.init_from_devicetask(task); - - denoising.run_denoising(); - - task.unmap_neighbor_tiles(rtiles, this); + denoising.run_denoising(&rtile); } void path_trace(DeviceTask& task, RenderTile& rtile, device_vector& work_tiles) @@ -2074,7 +2048,7 @@ class CUDADevice : public Device /* keep rendering tiles until done */ RenderTile tile; - DenoisingTask denoising(this); + DenoisingTask denoising(this, *task); while(task->acquire_tile(this, tile)) { if(tile.task == RenderTile::PATH_TRACE) { @@ -2089,7 +2063,7 @@ class CUDADevice : public Device else if(tile.task == RenderTile::DENOISE) { tile.sample = tile.start_sample + tile.num_samples; - denoise(tile, denoising, *task); + denoise(tile, denoising); task->update_progress(&tile, tile.w*tile.h); } diff --git a/intern/cycles/device/device_denoising.cpp b/intern/cycles/device/device_denoising.cpp index 644cf6cd10e8..23c18fa15b2c 100644 --- a/intern/cycles/device/device_denoising.cpp +++ b/intern/cycles/device/device_denoising.cpp @@ -20,28 +20,11 @@ CCL_NAMESPACE_BEGIN -DenoisingTask::DenoisingTask(Device *device) -: tiles_mem(device, "denoising tiles_mem", MEM_READ_WRITE), +DenoisingTask::DenoisingTask(Device *device, const DeviceTask &task) +: tile_info_mem(device, "denoising tile info mem", MEM_READ_WRITE), storage(device), buffer(device), device(device) -{ -} - -DenoisingTask::~DenoisingTask() -{ - storage.XtWX.free(); - storage.XtWY.free(); - storage.transform.free(); - storage.rank.free(); - storage.temporary_1.free(); - storage.temporary_2.free(); - storage.temporary_color.free(); - buffer.mem.free(); - tiles_mem.free(); -} - -void DenoisingTask::init_from_devicetask(const DeviceTask &task) { radius = task.denoising_radius; nlm_k_2 = powf(2.0f, lerp(-5.0f, 3.0f, task.denoising_strength)); @@ -53,182 +36,209 @@ void DenoisingTask::init_from_devicetask(const DeviceTask &task) } render_buffer.pass_stride = task.pass_stride; - render_buffer.denoising_data_offset = task.pass_denoising_data; - render_buffer.denoising_clean_offset = task.pass_denoising_clean; + render_buffer.offset = task.pass_denoising_data; - /* Expand filter_area by radius pixels and clamp the result to the extent of the neighboring tiles */ - rect = rect_from_shape(filter_area.x, filter_area.y, filter_area.z, filter_area.w); - rect = rect_expand(rect, radius); - rect = rect_clip(rect, make_int4(tiles->x[0], tiles->y[0], tiles->x[3], tiles->y[3])); + target_buffer.pass_stride = task.pass_stride; + target_buffer.denoising_clean_offset = task.pass_denoising_clean; + + functions.map_neighbor_tiles = function_bind(task.map_neighbor_tiles, _1, device); + functions.unmap_neighbor_tiles = function_bind(task.unmap_neighbor_tiles, _1, device); } -void DenoisingTask::tiles_from_rendertiles(RenderTile *rtiles) +DenoisingTask::~DenoisingTask() { - tiles = (TilesInfo*) tiles_mem.alloc(sizeof(TilesInfo)/sizeof(int)); + storage.XtWX.free(); + storage.XtWY.free(); + storage.transform.free(); + storage.rank.free(); + buffer.mem.free(); + buffer.temporary_mem.free(); + tile_info_mem.free(); +} + +void DenoisingTask::set_render_buffer(RenderTile *rtiles) +{ + tile_info = (TileInfo*) tile_info_mem.alloc(sizeof(TileInfo)/sizeof(int)); - device_ptr buffers[9]; for(int i = 0; i < 9; i++) { - buffers[i] = rtiles[i].buffer; - tiles->offsets[i] = rtiles[i].offset; - tiles->strides[i] = rtiles[i].stride; + tile_info->offsets[i] = rtiles[i].offset; + tile_info->strides[i] = rtiles[i].stride; + tile_info->buffers[i] = rtiles[i].buffer; } - tiles->x[0] = rtiles[3].x; - tiles->x[1] = rtiles[4].x; - tiles->x[2] = rtiles[5].x; - tiles->x[3] = rtiles[5].x + rtiles[5].w; - tiles->y[0] = rtiles[1].y; - tiles->y[1] = rtiles[4].y; - tiles->y[2] = rtiles[7].y; - tiles->y[3] = rtiles[7].y + rtiles[7].h; - - render_buffer.offset = rtiles[4].offset; - render_buffer.stride = rtiles[4].stride; - render_buffer.ptr = rtiles[4].buffer; - - functions.set_tiles(buffers); + tile_info->x[0] = rtiles[3].x; + tile_info->x[1] = rtiles[4].x; + tile_info->x[2] = rtiles[5].x; + tile_info->x[3] = rtiles[5].x + rtiles[5].w; + tile_info->y[0] = rtiles[1].y; + tile_info->y[1] = rtiles[4].y; + tile_info->y[2] = rtiles[7].y; + tile_info->y[3] = rtiles[7].y + rtiles[7].h; + + target_buffer.offset = rtiles[9].offset; + target_buffer.stride = rtiles[9].stride; + target_buffer.ptr = rtiles[9].buffer; + + tile_info_mem.copy_to_device(); } -bool DenoisingTask::run_denoising() +void DenoisingTask::setup_denoising_buffer() { - /* Allocate denoising buffer. */ + /* Expand filter_area by radius pixels and clamp the result to the extent of the neighboring tiles */ + rect = rect_from_shape(filter_area.x, filter_area.y, filter_area.z, filter_area.w); + rect = rect_expand(rect, radius); + rect = rect_clip(rect, make_int4(tile_info->x[0], tile_info->y[0], tile_info->x[3], tile_info->y[3])); + buffer.passes = 14; buffer.width = rect.z - rect.x; buffer.stride = align_up(buffer.width, 4); buffer.h = rect.w - rect.y; - buffer.pass_stride = align_up(buffer.stride * buffer.h, divide_up(device->mem_sub_ptr_alignment(), sizeof(float))); - buffer.mem.alloc_to_device(buffer.pass_stride * buffer.passes, false); + int alignment_floats = divide_up(device->mem_sub_ptr_alignment(), sizeof(float)); + buffer.pass_stride = align_up(buffer.stride * buffer.h, alignment_floats); + /* Pad the total size by four floats since the SIMD kernels might go a bit over the end. */ + int mem_size = align_up(buffer.pass_stride * buffer.passes + 4, alignment_floats); + buffer.mem.alloc_to_device(mem_size, false); + + /* CPUs process shifts sequentially while GPUs process them in parallel. */ + int num_shifts = 1; + if(buffer.gpu_temporary_mem) { + /* Shadowing prefiltering uses a radius of 6, so allocate at least that much. */ + int max_radius = max(radius, 6); + num_shifts = (2*max_radius + 1) * (2*max_radius + 1); + } + /* Allocate two layers per shift as well as one for the weight accumulation. */ + buffer.temporary_mem.alloc_to_device((2*num_shifts + 1) * buffer.pass_stride); +} +void DenoisingTask::prefilter_shadowing() +{ device_ptr null_ptr = (device_ptr) 0; - /* Prefilter shadow feature. */ - { - device_sub_ptr unfiltered_a (buffer.mem, 0, buffer.pass_stride); - device_sub_ptr unfiltered_b (buffer.mem, 1*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr sample_var (buffer.mem, 2*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr sample_var_var (buffer.mem, 3*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr buffer_var (buffer.mem, 5*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr filtered_var (buffer.mem, 6*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_1(buffer.mem, 7*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_2(buffer.mem, 8*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_3(buffer.mem, 9*buffer.pass_stride, buffer.pass_stride); - - nlm_state.temporary_1_ptr = *nlm_temporary_1; - nlm_state.temporary_2_ptr = *nlm_temporary_2; - nlm_state.temporary_3_ptr = *nlm_temporary_3; - - /* Get the A/B unfiltered passes, the combined sample variance, the estimated variance of the sample variance and the buffer variance. */ - functions.divide_shadow(*unfiltered_a, *unfiltered_b, *sample_var, *sample_var_var, *buffer_var); - - /* Smooth the (generally pretty noisy) buffer variance using the spatial information from the sample variance. */ - nlm_state.set_parameters(6, 3, 4.0f, 1.0f); - functions.non_local_means(*buffer_var, *sample_var, *sample_var_var, *filtered_var); - - /* Reuse memory, the previous data isn't needed anymore. */ - device_ptr filtered_a = *buffer_var, - filtered_b = *sample_var; - /* Use the smoothed variance to filter the two shadow half images using each other for weight calculation. */ - nlm_state.set_parameters(5, 3, 1.0f, 0.25f); - functions.non_local_means(*unfiltered_a, *unfiltered_b, *filtered_var, filtered_a); - functions.non_local_means(*unfiltered_b, *unfiltered_a, *filtered_var, filtered_b); - - device_ptr residual_var = *sample_var_var; - /* Estimate the residual variance between the two filtered halves. */ - functions.combine_halves(filtered_a, filtered_b, null_ptr, residual_var, 2, rect); - - device_ptr final_a = *unfiltered_a, - final_b = *unfiltered_b; - /* Use the residual variance for a second filter pass. */ - nlm_state.set_parameters(4, 2, 1.0f, 0.5f); - functions.non_local_means(filtered_a, filtered_b, residual_var, final_a); - functions.non_local_means(filtered_b, filtered_a, residual_var, final_b); - - /* Combine the two double-filtered halves to a final shadow feature. */ - device_sub_ptr shadow_pass(buffer.mem, 4*buffer.pass_stride, buffer.pass_stride); - functions.combine_halves(final_a, final_b, *shadow_pass, null_ptr, 0, rect); - } + device_sub_ptr unfiltered_a (buffer.mem, 0, buffer.pass_stride); + device_sub_ptr unfiltered_b (buffer.mem, 1*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr sample_var (buffer.mem, 2*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr sample_var_var (buffer.mem, 3*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr buffer_var (buffer.mem, 5*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr filtered_var (buffer.mem, 6*buffer.pass_stride, buffer.pass_stride); + + /* Get the A/B unfiltered passes, the combined sample variance, the estimated variance of the sample variance and the buffer variance. */ + functions.divide_shadow(*unfiltered_a, *unfiltered_b, *sample_var, *sample_var_var, *buffer_var); + + /* Smooth the (generally pretty noisy) buffer variance using the spatial information from the sample variance. */ + nlm_state.set_parameters(6, 3, 4.0f, 1.0f); + functions.non_local_means(*buffer_var, *sample_var, *sample_var_var, *filtered_var); + + /* Reuse memory, the previous data isn't needed anymore. */ + device_ptr filtered_a = *buffer_var, + filtered_b = *sample_var; + /* Use the smoothed variance to filter the two shadow half images using each other for weight calculation. */ + nlm_state.set_parameters(5, 3, 1.0f, 0.25f); + functions.non_local_means(*unfiltered_a, *unfiltered_b, *filtered_var, filtered_a); + functions.non_local_means(*unfiltered_b, *unfiltered_a, *filtered_var, filtered_b); + + device_ptr residual_var = *sample_var_var; + /* Estimate the residual variance between the two filtered halves. */ + functions.combine_halves(filtered_a, filtered_b, null_ptr, residual_var, 2, rect); + + device_ptr final_a = *unfiltered_a, + final_b = *unfiltered_b; + /* Use the residual variance for a second filter pass. */ + nlm_state.set_parameters(4, 2, 1.0f, 0.5f); + functions.non_local_means(filtered_a, filtered_b, residual_var, final_a); + functions.non_local_means(filtered_b, filtered_a, residual_var, final_b); + + /* Combine the two double-filtered halves to a final shadow feature. */ + device_sub_ptr shadow_pass(buffer.mem, 4*buffer.pass_stride, buffer.pass_stride); + functions.combine_halves(final_a, final_b, *shadow_pass, null_ptr, 0, rect); +} - /* Prefilter general features. */ - { - device_sub_ptr unfiltered (buffer.mem, 8*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr variance (buffer.mem, 9*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_1(buffer.mem, 10*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_2(buffer.mem, 11*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr nlm_temporary_3(buffer.mem, 12*buffer.pass_stride, buffer.pass_stride); - - nlm_state.temporary_1_ptr = *nlm_temporary_1; - nlm_state.temporary_2_ptr = *nlm_temporary_2; - nlm_state.temporary_3_ptr = *nlm_temporary_3; - - int mean_from[] = { 0, 1, 2, 12, 6, 7, 8 }; - int variance_from[] = { 3, 4, 5, 13, 9, 10, 11}; - int pass_to[] = { 1, 2, 3, 0, 5, 6, 7}; - for(int pass = 0; pass < 7; pass++) { - device_sub_ptr feature_pass(buffer.mem, pass_to[pass]*buffer.pass_stride, buffer.pass_stride); - /* Get the unfiltered pass and its variance from the RenderBuffers. */ - functions.get_feature(mean_from[pass], variance_from[pass], *unfiltered, *variance); - /* Smooth the pass and store the result in the denoising buffers. */ - nlm_state.set_parameters(2, 2, 1.0f, 0.25f); - functions.non_local_means(*unfiltered, *unfiltered, *variance, *feature_pass); - } +void DenoisingTask::prefilter_features() +{ + device_sub_ptr unfiltered (buffer.mem, 8*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr variance (buffer.mem, 9*buffer.pass_stride, buffer.pass_stride); + + int mean_from[] = { 0, 1, 2, 12, 6, 7, 8 }; + int variance_from[] = { 3, 4, 5, 13, 9, 10, 11}; + int pass_to[] = { 1, 2, 3, 0, 5, 6, 7}; + for(int pass = 0; pass < 7; pass++) { + device_sub_ptr feature_pass(buffer.mem, pass_to[pass]*buffer.pass_stride, buffer.pass_stride); + /* Get the unfiltered pass and its variance from the RenderBuffers. */ + functions.get_feature(mean_from[pass], variance_from[pass], *unfiltered, *variance); + /* Smooth the pass and store the result in the denoising buffers. */ + nlm_state.set_parameters(2, 2, 1.0f, 0.25f); + functions.non_local_means(*unfiltered, *unfiltered, *variance, *feature_pass); } +} - /* Copy color passes. */ - { - int mean_from[] = {20, 21, 22}; - int variance_from[] = {23, 24, 25}; - int mean_to[] = { 8, 9, 10}; - int variance_to[] = {11, 12, 13}; - int num_color_passes = 3; - - storage.temporary_color.alloc_to_device(3*buffer.pass_stride, false); - - for(int pass = 0; pass < num_color_passes; pass++) { - device_sub_ptr color_pass(storage.temporary_color, pass*buffer.pass_stride, buffer.pass_stride); - device_sub_ptr color_var_pass(buffer.mem, variance_to[pass]*buffer.pass_stride, buffer.pass_stride); - functions.get_feature(mean_from[pass], variance_from[pass], *color_pass, *color_var_pass); - } - - { - device_sub_ptr depth_pass (buffer.mem, 0, buffer.pass_stride); - device_sub_ptr color_var_pass(buffer.mem, variance_to[0]*buffer.pass_stride, 3*buffer.pass_stride); - device_sub_ptr output_pass (buffer.mem, mean_to[0]*buffer.pass_stride, 3*buffer.pass_stride); - functions.detect_outliers(storage.temporary_color.device_pointer, *color_var_pass, *depth_pass, *output_pass); - } +void DenoisingTask::prefilter_color() +{ + int mean_from[] = {20, 21, 22}; + int variance_from[] = {23, 24, 25}; + int mean_to[] = { 8, 9, 10}; + int variance_to[] = {11, 12, 13}; + int num_color_passes = 3; + + device_only_memory temporary_color(device, "denoising temporary color"); + temporary_color.alloc_to_device(3*buffer.pass_stride, false); + + for(int pass = 0; pass < num_color_passes; pass++) { + device_sub_ptr color_pass(temporary_color, pass*buffer.pass_stride, buffer.pass_stride); + device_sub_ptr color_var_pass(buffer.mem, variance_to[pass]*buffer.pass_stride, buffer.pass_stride); + functions.get_feature(mean_from[pass], variance_from[pass], *color_pass, *color_var_pass); } + device_sub_ptr depth_pass (buffer.mem, 0, buffer.pass_stride); + device_sub_ptr color_var_pass(buffer.mem, variance_to[0]*buffer.pass_stride, 3*buffer.pass_stride); + device_sub_ptr output_pass (buffer.mem, mean_to[0]*buffer.pass_stride, 3*buffer.pass_stride); + functions.detect_outliers(temporary_color.device_pointer, *color_var_pass, *depth_pass, *output_pass); +} + +void DenoisingTask::construct_transform() +{ storage.w = filter_area.z; storage.h = filter_area.w; + storage.transform.alloc_to_device(storage.w*storage.h*TRANSFORM_SIZE, false); storage.rank.alloc_to_device(storage.w*storage.h, false); functions.construct_transform(); +} - device_only_memory temporary_1(device, "Denoising NLM temporary 1"); - device_only_memory temporary_2(device, "Denoising NLM temporary 2"); - temporary_1.alloc_to_device(buffer.pass_stride, false); - temporary_2.alloc_to_device(buffer.pass_stride, false); - reconstruction_state.temporary_1_ptr = temporary_1.device_pointer; - reconstruction_state.temporary_2_ptr = temporary_2.device_pointer; - +void DenoisingTask::reconstruct() +{ storage.XtWX.alloc_to_device(storage.w*storage.h*XTWX_SIZE, false); storage.XtWY.alloc_to_device(storage.w*storage.h*XTWY_SIZE, false); reconstruction_state.filter_window = rect_from_shape(filter_area.x-rect.x, filter_area.y-rect.y, storage.w, storage.h); - int tile_coordinate_offset = filter_area.y*render_buffer.stride + filter_area.x; - reconstruction_state.buffer_params = make_int4(render_buffer.offset + tile_coordinate_offset, - render_buffer.stride, - render_buffer.pass_stride, - render_buffer.denoising_clean_offset); + int tile_coordinate_offset = filter_area.y*target_buffer.stride + filter_area.x; + reconstruction_state.buffer_params = make_int4(target_buffer.offset + tile_coordinate_offset, + target_buffer.stride, + target_buffer.pass_stride, + target_buffer.denoising_clean_offset); reconstruction_state.source_w = rect.z-rect.x; reconstruction_state.source_h = rect.w-rect.y; - { - device_sub_ptr color_ptr (buffer.mem, 8*buffer.pass_stride, 3*buffer.pass_stride); - device_sub_ptr color_var_ptr(buffer.mem, 11*buffer.pass_stride, 3*buffer.pass_stride); - functions.reconstruct(*color_ptr, *color_var_ptr, render_buffer.ptr); - } + device_sub_ptr color_ptr (buffer.mem, 8*buffer.pass_stride, 3*buffer.pass_stride); + device_sub_ptr color_var_ptr(buffer.mem, 11*buffer.pass_stride, 3*buffer.pass_stride); + functions.reconstruct(*color_ptr, *color_var_ptr, target_buffer.ptr); +} + +void DenoisingTask::run_denoising(RenderTile *tile) +{ + RenderTile rtiles[10]; + rtiles[4] = *tile; + functions.map_neighbor_tiles(rtiles); + set_render_buffer(rtiles); + + setup_denoising_buffer(); + + prefilter_shadowing(); + prefilter_features(); + prefilter_color(); + + construct_transform(); + reconstruct(); - return true; + functions.unmap_neighbor_tiles(rtiles); } CCL_NAMESPACE_END diff --git a/intern/cycles/device/device_denoising.h b/intern/cycles/device/device_denoising.h index 77a82d0ad041..7474f71ff782 100644 --- a/intern/cycles/device/device_denoising.h +++ b/intern/cycles/device/device_denoising.h @@ -32,20 +32,24 @@ class DenoisingTask { float nlm_k_2; float pca_threshold; - /* Pointer and parameters of the RenderBuffers. */ + /* Parameters of the RenderBuffers. */ struct RenderBuffers { - int denoising_data_offset; - int denoising_clean_offset; + int offset; int pass_stride; + int samples; + } render_buffer; + + /* Pointer and parameters of the target buffer. */ + struct TargetBuffer { int offset; int stride; + int pass_stride; + int denoising_clean_offset; device_ptr ptr; - int samples; - } render_buffer; + } target_buffer; - TilesInfo *tiles; - device_vector tiles_mem; - void tiles_from_rendertiles(RenderTile *rtiles); + TileInfo *tile_info; + device_vector tile_info_mem; int4 rect; int4 filter_area; @@ -85,15 +89,13 @@ class DenoisingTask { device_ptr depth_ptr, device_ptr output_ptr )> detect_outliers; - function set_tiles; + function map_neighbor_tiles; + function unmap_neighbor_tiles; } functions; /* Stores state of the current Reconstruction operation, * which is accessed by the device in order to perform the operation. */ struct ReconstructionState { - device_ptr temporary_1_ptr; /* There two images are used as temporary storage. */ - device_ptr temporary_2_ptr; - int4 filter_window; int4 buffer_params; @@ -104,10 +106,6 @@ class DenoisingTask { /* Stores state of the current NLM operation, * which is accessed by the device in order to perform the operation. */ struct NLMState { - device_ptr temporary_1_ptr; /* There three images are used as temporary storage. */ - device_ptr temporary_2_ptr; - device_ptr temporary_3_ptr; - int r; /* Search radius of the filter. */ int f; /* Patch size of the filter. */ float a; /* Variance compensation factor in the MSE estimation. */ @@ -121,9 +119,6 @@ class DenoisingTask { device_only_memory rank; device_only_memory XtWX; device_only_memory XtWY; - device_only_memory temporary_1; - device_only_memory temporary_2; - device_only_memory temporary_color; int w; int h; @@ -131,19 +126,14 @@ class DenoisingTask { : transform(device, "denoising transform"), rank(device, "denoising rank"), XtWX(device, "denoising XtWX"), - XtWY(device, "denoising XtWY"), - temporary_1(device, "denoising NLM temporary 1"), - temporary_2(device, "denoising NLM temporary 2"), - temporary_color(device, "denoising temporary color") + XtWY(device, "denoising XtWY") {} } storage; - DenoisingTask(Device *device); + DenoisingTask(Device *device, const DeviceTask &task); ~DenoisingTask(); - void init_from_devicetask(const DeviceTask &task); - - bool run_denoising(); + void run_denoising(RenderTile *tile); struct DenoiseBuffers { int pass_stride; @@ -152,14 +142,26 @@ class DenoisingTask { int h; int width; device_only_memory mem; + device_only_memory temporary_mem; + + bool gpu_temporary_mem; DenoiseBuffers(Device *device) - : mem(device, "denoising pixel buffer") + : mem(device, "denoising pixel buffer"), + temporary_mem(device, "denoising temporary mem") {} } buffer; protected: Device *device; + + void set_render_buffer(RenderTile *rtiles); + void setup_denoising_buffer(); + void prefilter_shadowing(); + void prefilter_features(); + void prefilter_color(); + void construct_transform(); + void reconstruct(); }; CCL_NAMESPACE_END diff --git a/intern/cycles/device/device_intern.h b/intern/cycles/device/device_intern.h index de487649045a..941be448101d 100644 --- a/intern/cycles/device/device_intern.h +++ b/intern/cycles/device/device_intern.h @@ -41,4 +41,3 @@ string device_cuda_capabilities(void); CCL_NAMESPACE_END #endif /* __DEVICE_INTERN_H__ */ - diff --git a/intern/cycles/device/device_memory.cpp b/intern/cycles/device/device_memory.cpp index c6248fcf88b6..a8d29896553d 100644 --- a/intern/cycles/device/device_memory.cpp +++ b/intern/cycles/device/device_memory.cpp @@ -104,6 +104,26 @@ void device_memory::device_zero() } } +void device_memory::swap_device(Device *new_device, + size_t new_device_size, + device_ptr new_device_ptr) +{ + original_device = device; + original_device_size = device_size; + original_device_ptr = device_pointer; + + device = new_device; + device_size = new_device_size; + device_pointer = new_device_ptr; +} + +void device_memory::restore_device() +{ + device = original_device; + device_size = original_device_size; + device_pointer = original_device_ptr; +} + /* Device Sub Ptr */ device_sub_ptr::device_sub_ptr(device_memory& mem, int offset, int size) @@ -118,4 +138,3 @@ device_sub_ptr::~device_sub_ptr() } CCL_NAMESPACE_END - diff --git a/intern/cycles/device/device_memory.h b/intern/cycles/device/device_memory.h index d8fe41e78bb8..2b4835c9c658 100644 --- a/intern/cycles/device/device_memory.h +++ b/intern/cycles/device/device_memory.h @@ -43,6 +43,7 @@ enum MemoryType { enum DataType { TYPE_UNKNOWN, TYPE_UCHAR, + TYPE_UINT16, TYPE_UINT, TYPE_INT, TYPE_FLOAT, @@ -50,13 +51,14 @@ enum DataType { TYPE_UINT64, }; -static inline size_t datatype_size(DataType datatype) +static inline size_t datatype_size(DataType datatype) { switch(datatype) { case TYPE_UNKNOWN: return 1; case TYPE_UCHAR: return sizeof(uchar); case TYPE_FLOAT: return sizeof(float); case TYPE_UINT: return sizeof(uint); + case TYPE_UINT16: return sizeof(uint16_t); case TYPE_INT: return sizeof(int); case TYPE_HALF: return sizeof(half); case TYPE_UINT64: return sizeof(uint64_t); @@ -156,6 +158,16 @@ template<> struct device_type_traits { static const int num_elements = 1; }; +template<> struct device_type_traits { + static const DataType data_type = TYPE_UINT16; + static const int num_elements = 4; +}; + +template<> struct device_type_traits { + static const DataType data_type = TYPE_UINT16; + static const int num_elements = 1; +}; + template<> struct device_type_traits { static const DataType data_type = TYPE_HALF; static const int num_elements = 4; @@ -200,6 +212,9 @@ class device_memory virtual ~device_memory(); + void swap_device(Device *new_device, size_t new_device_size, device_ptr new_device_ptr); + void restore_device(); + protected: friend class CUDADevice; @@ -222,6 +237,10 @@ class device_memory void device_copy_to(); void device_copy_from(int y, int w, int h, int elem); void device_zero(); + + device_ptr original_device_ptr; + size_t original_device_size; + Device *original_device; }; /* Device Only Memory @@ -478,4 +497,3 @@ class device_sub_ptr CCL_NAMESPACE_END #endif /* __DEVICE_MEMORY_H__ */ - diff --git a/intern/cycles/device/device_multi.cpp b/intern/cycles/device/device_multi.cpp index 3a4c08b6eb26..f1bd3fd13e1b 100644 --- a/intern/cycles/device/device_multi.cpp +++ b/intern/cycles/device/device_multi.cpp @@ -282,26 +282,27 @@ class MultiDevice : public Device mem.copy_from_device(0, mem.data_size, 1); } - Device *original_device = mem.device; - device_ptr original_ptr = mem.device_pointer; - size_t original_size = mem.device_size; - - mem.device = sub_device; - mem.device_pointer = 0; - mem.device_size = 0; + mem.swap_device(sub_device, 0, 0); mem.copy_to_device(); tiles[i].buffer = mem.device_pointer; + tiles[i].device_size = mem.device_size; - mem.device = original_device; - mem.device_pointer = original_ptr; - mem.device_size = original_size; + mem.restore_device(); } } } void unmap_neighbor_tiles(Device * sub_device, RenderTile * tiles) { + /* Copy denoised result back to the host. */ + device_vector &mem = tiles[9].buffers->buffer; + mem.swap_device(sub_device, tiles[9].device_size, tiles[9].buffer); + mem.copy_from_device(0, mem.data_size, 1); + mem.restore_device(); + /* Copy denoised result to the original device. */ + mem.copy_to_device(); + for(int i = 0; i < 9; i++) { if(!tiles[i].buffers) { continue; @@ -309,28 +310,9 @@ class MultiDevice : public Device device_vector &mem = tiles[i].buffers->buffer; if(mem.device != sub_device) { - Device *original_device = mem.device; - device_ptr original_ptr = mem.device_pointer; - size_t original_size = mem.device_size; - - mem.device = sub_device; - mem.device_pointer = tiles[i].buffer; - - /* Copy denoised tile to the host. */ - if(i == 4) { - mem.copy_from_device(0, mem.data_size, 1); - } - + mem.swap_device(sub_device, tiles[i].device_size, tiles[i].buffer); sub_device->mem_free(mem); - - mem.device = original_device; - mem.device_pointer = original_ptr; - mem.device_size = original_size; - - /* Copy denoised tile to the original device. */ - if(i == 4) { - mem.copy_to_device(); - } + mem.restore_device(); } } } @@ -394,4 +376,3 @@ Device *device_multi_create(DeviceInfo& info, Stats &stats, bool background) } CCL_NAMESPACE_END - diff --git a/intern/cycles/device/device_network.cpp b/intern/cycles/device/device_network.cpp index 5ad4405366ee..204e405421d8 100644 --- a/intern/cycles/device/device_network.cpp +++ b/intern/cycles/device/device_network.cpp @@ -797,5 +797,3 @@ void Device::server_run() CCL_NAMESPACE_END #endif - - diff --git a/intern/cycles/device/device_network.h b/intern/cycles/device/device_network.h index b734ba2bda93..96e0de742dbe 100644 --- a/intern/cycles/device/device_network.h +++ b/intern/cycles/device/device_network.h @@ -179,7 +179,7 @@ class RPCSend { boost::asio::write(socket, boost::asio::buffer(archive_str), boost::asio::transfer_all(), error); - + if(error.value()) error_func->network_error(error.message()); @@ -193,7 +193,7 @@ class RPCSend { boost::asio::write(socket, boost::asio::buffer(buffer, size), boost::asio::transfer_all(), error); - + if(error.value()) error_func->network_error(error.message()); } @@ -467,7 +467,7 @@ class ServerDiscovery { /* buffer and endpoint for receiving messages */ char receive_buffer[256]; boost::asio::ip::udp::endpoint receive_endpoint; - + // os, version, devices, status, host name, group name, ip as far as fields go struct ServerInfo { string cycles_version; @@ -489,4 +489,3 @@ CCL_NAMESPACE_END #endif #endif /* __DEVICE_NETWORK_H__ */ - diff --git a/intern/cycles/device/device_opencl.cpp b/intern/cycles/device/device_opencl.cpp index 9d61bbdae5db..be0f8f45399a 100644 --- a/intern/cycles/device/device_opencl.cpp +++ b/intern/cycles/device/device_opencl.cpp @@ -23,6 +23,7 @@ #include "util/util_foreach.h" #include "util/util_logging.h" #include "util/util_set.h" +#include "util/util_string.h" CCL_NAMESPACE_BEGIN @@ -137,6 +138,10 @@ void device_opencl_info(vector& devices) info.has_volume_decoupled = false; info.bvh_layout_mask = BVH_LAYOUT_BVH2; info.id = id; + + /* Check OpenCL extensions */ + info.has_half_images = platform_device.device_extensions.find("cl_khr_fp16") != string::npos; + devices.push_back(info); num_devices++; } @@ -162,11 +167,14 @@ string device_opencl_capabilities(void) platform_ids.resize(num_platforms); opencl_assert(clGetPlatformIDs(num_platforms, &platform_ids[0], NULL)); -#define APPEND_STRING_INFO(func, id, name, what) \ + typedef char cl_string[1024]; + +#define APPEND_INFO(func, id, name, what, type) \ do { \ - char data[1024] = "\0"; \ + type data; \ + memset(&data, 0, sizeof(data)); \ opencl_assert(func(id, what, sizeof(data), &data, NULL)); \ - result += string_printf("%s: %s\n", name, data); \ + result += string_printf("%s: %s\n", name, to_string(data).c_str()); \ } while(false) #define APPEND_STRING_EXTENSION_INFO(func, id, name, what) \ do { \ @@ -178,10 +186,10 @@ string device_opencl_capabilities(void) } \ } \ } while(false) -#define APPEND_PLATFORM_STRING_INFO(id, name, what) \ - APPEND_STRING_INFO(clGetPlatformInfo, id, "\tPlatform " name, what) -#define APPEND_DEVICE_STRING_INFO(id, name, what) \ - APPEND_STRING_INFO(clGetDeviceInfo, id, "\t\t\tDevice " name, what) +#define APPEND_PLATFORM_INFO(id, name, what, type) \ + APPEND_INFO(clGetPlatformInfo, id, "\tPlatform " name, what, type) +#define APPEND_DEVICE_INFO(id, name, what, type) \ + APPEND_INFO(clGetDeviceInfo, id, "\t\t\tDevice " name, what, type) #define APPEND_DEVICE_STRING_EXTENSION_INFO(id, name, what) \ APPEND_STRING_EXTENSION_INFO(clGetDeviceInfo, id, "\t\t\tDevice " name, what) @@ -191,11 +199,11 @@ string device_opencl_capabilities(void) result += string_printf("Platform #%u\n", platform); - APPEND_PLATFORM_STRING_INFO(platform_id, "Name", CL_PLATFORM_NAME); - APPEND_PLATFORM_STRING_INFO(platform_id, "Vendor", CL_PLATFORM_VENDOR); - APPEND_PLATFORM_STRING_INFO(platform_id, "Version", CL_PLATFORM_VERSION); - APPEND_PLATFORM_STRING_INFO(platform_id, "Profile", CL_PLATFORM_PROFILE); - APPEND_PLATFORM_STRING_INFO(platform_id, "Extensions", CL_PLATFORM_EXTENSIONS); + APPEND_PLATFORM_INFO(platform_id, "Name", CL_PLATFORM_NAME, cl_string); + APPEND_PLATFORM_INFO(platform_id, "Vendor", CL_PLATFORM_VENDOR, cl_string); + APPEND_PLATFORM_INFO(platform_id, "Version", CL_PLATFORM_VERSION, cl_string); + APPEND_PLATFORM_INFO(platform_id, "Profile", CL_PLATFORM_PROFILE, cl_string); + APPEND_PLATFORM_INFO(platform_id, "Extensions", CL_PLATFORM_EXTENSIONS, cl_string); cl_uint num_devices = 0; opencl_assert(clGetDeviceIDs(platform_ids[platform], @@ -216,13 +224,16 @@ string device_opencl_capabilities(void) result += string_printf("\t\tDevice: #%u\n", device); - APPEND_DEVICE_STRING_INFO(device_id, "Name", CL_DEVICE_NAME); + APPEND_DEVICE_INFO(device_id, "Name", CL_DEVICE_NAME, cl_string); APPEND_DEVICE_STRING_EXTENSION_INFO(device_id, "Board Name", CL_DEVICE_BOARD_NAME_AMD); - APPEND_DEVICE_STRING_INFO(device_id, "Vendor", CL_DEVICE_VENDOR); - APPEND_DEVICE_STRING_INFO(device_id, "OpenCL C Version", CL_DEVICE_OPENCL_C_VERSION); - APPEND_DEVICE_STRING_INFO(device_id, "Profile", CL_DEVICE_PROFILE); - APPEND_DEVICE_STRING_INFO(device_id, "Version", CL_DEVICE_VERSION); - APPEND_DEVICE_STRING_INFO(device_id, "Extensions", CL_DEVICE_EXTENSIONS); + APPEND_DEVICE_INFO(device_id, "Vendor", CL_DEVICE_VENDOR, cl_string); + APPEND_DEVICE_INFO(device_id, "OpenCL C Version", CL_DEVICE_OPENCL_C_VERSION, cl_string); + APPEND_DEVICE_INFO(device_id, "Profile", CL_DEVICE_PROFILE, cl_string); + APPEND_DEVICE_INFO(device_id, "Version", CL_DEVICE_VERSION, cl_string); + APPEND_DEVICE_INFO(device_id, "Extensions", CL_DEVICE_EXTENSIONS, cl_string); + APPEND_DEVICE_INFO(device_id, "Max clock frequency (MHz)", CL_DEVICE_MAX_CLOCK_FREQUENCY, cl_uint); + APPEND_DEVICE_INFO(device_id, "Max compute units", CL_DEVICE_MAX_COMPUTE_UNITS, cl_uint); + APPEND_DEVICE_INFO(device_id, "Max work group size", CL_DEVICE_MAX_WORK_GROUP_SIZE, size_t); } } diff --git a/intern/cycles/device/device_split_kernel.cpp b/intern/cycles/device/device_split_kernel.cpp index 74135a1f3c87..efaae8c84f49 100644 --- a/intern/cycles/device/device_split_kernel.cpp +++ b/intern/cycles/device/device_split_kernel.cpp @@ -261,7 +261,7 @@ bool DeviceSplitKernel::path_trace(DeviceTask *task, ENQUEUE_SPLIT_KERNEL(buffer_update, global_size, local_size); if(task->get_cancel() && cancel_time == DBL_MAX) { - /* Wait up to twice as many seconds for current samples to finish + /* Wait up to twice as many seconds for current samples to finish * to avoid artifacts in render result from ending too soon. */ cancel_time = time_dt() + 2.0 * time_multiplier; @@ -322,5 +322,3 @@ bool DeviceSplitKernel::path_trace(DeviceTask *task, } CCL_NAMESPACE_END - - diff --git a/intern/cycles/device/device_split_kernel.h b/intern/cycles/device/device_split_kernel.h index 2ec0261e8470..26ddce5bb228 100644 --- a/intern/cycles/device/device_split_kernel.h +++ b/intern/cycles/device/device_split_kernel.h @@ -131,6 +131,3 @@ class DeviceSplitKernel { CCL_NAMESPACE_END #endif /* __DEVICE_SPLIT_KERNEL_H__ */ - - - diff --git a/intern/cycles/device/device_task.cpp b/intern/cycles/device/device_task.cpp index 3c7d24fb5b79..8310863886c1 100644 --- a/intern/cycles/device/device_task.cpp +++ b/intern/cycles/device/device_task.cpp @@ -126,4 +126,3 @@ void DeviceTask::update_progress(RenderTile *rtile, int pixel_samples) } CCL_NAMESPACE_END - diff --git a/intern/cycles/device/device_task.h b/intern/cycles/device/device_task.h index b9658eb978fb..ec87aa8c5600 100644 --- a/intern/cycles/device/device_task.h +++ b/intern/cycles/device/device_task.h @@ -86,4 +86,3 @@ class DeviceTask : public Task { CCL_NAMESPACE_END #endif /* __DEVICE_TASK_H__ */ - diff --git a/intern/cycles/device/opencl/memory_manager.cpp b/intern/cycles/device/opencl/memory_manager.cpp index 75c9de65035a..485a656cb83b 100644 --- a/intern/cycles/device/opencl/memory_manager.cpp +++ b/intern/cycles/device/opencl/memory_manager.cpp @@ -254,4 +254,3 @@ void MemoryManager::set_kernel_arg_buffers(cl_kernel kernel, cl_uint *narg) CCL_NAMESPACE_END #endif /* WITH_OPENCL */ - diff --git a/intern/cycles/device/opencl/memory_manager.h b/intern/cycles/device/opencl/memory_manager.h index b3d861275f06..b49bd32dab63 100644 --- a/intern/cycles/device/opencl/memory_manager.h +++ b/intern/cycles/device/opencl/memory_manager.h @@ -104,4 +104,3 @@ class MemoryManager { }; CCL_NAMESPACE_END - diff --git a/intern/cycles/device/opencl/opencl.h b/intern/cycles/device/opencl/opencl.h index 85ef14ee29ad..6c73d10a376f 100644 --- a/intern/cycles/device/opencl/opencl.h +++ b/intern/cycles/device/opencl/opencl.h @@ -59,19 +59,22 @@ struct OpenCLPlatformDevice { cl_device_id device_id, cl_device_type device_type, const string& device_name, - const string& hardware_id) + const string& hardware_id, + const string& device_extensions) : platform_id(platform_id), platform_name(platform_name), device_id(device_id), device_type(device_type), device_name(device_name), - hardware_id(hardware_id) {} + hardware_id(hardware_id), + device_extensions(device_extensions) {} cl_platform_id platform_id; string platform_name; cl_device_id device_id; cl_device_type device_type; string device_name; string hardware_id; + string device_extensions; }; /* Contains all static OpenCL helper functions. */ @@ -130,6 +133,12 @@ class OpenCLInfo static string get_device_name(cl_device_id device_id); + static bool get_device_extensions(cl_device_id device_id, + string *device_extensions, + cl_int* error = NULL); + + static string get_device_extensions(cl_device_id device_id); + static bool get_device_type(cl_device_id device_id, cl_device_type *device_type, cl_int* error = NULL); @@ -262,7 +271,7 @@ class OpenCLDeviceBase : public Device class OpenCLProgram { public: - OpenCLProgram() : loaded(false), device(NULL) {} + OpenCLProgram() : loaded(false), program(NULL), device(NULL) {} OpenCLProgram(OpenCLDeviceBase *device, const string& program_name, const string& kernel_name, @@ -362,7 +371,7 @@ class OpenCLDeviceBase : public Device void film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half); void shader(DeviceTask& task); - void denoise(RenderTile& tile, DenoisingTask& denoising, const DeviceTask& task); + void denoise(RenderTile& tile, DenoisingTask& denoising); class OpenCLDeviceTask : public DeviceTask { public: @@ -436,8 +445,6 @@ class OpenCLDeviceBase : public Device device_ptr depth_ptr, device_ptr output_ptr, DenoisingTask *task); - bool denoising_set_tiles(device_ptr *buffers, - DenoisingTask *task); device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int size); void mem_free_sub_ptr(device_ptr ptr); diff --git a/intern/cycles/device/opencl/opencl_base.cpp b/intern/cycles/device/opencl/opencl_base.cpp index bfa2702ad621..69a2bd7adcb9 100644 --- a/intern/cycles/device/opencl/opencl_base.cpp +++ b/intern/cycles/device/opencl/opencl_base.cpp @@ -246,7 +246,6 @@ bool OpenCLDeviceBase::load_kernels(const DeviceRequestedFeatures& requested_fea denoising_program.add_kernel(ustring("filter_nlm_normalize")); denoising_program.add_kernel(ustring("filter_nlm_construct_gramian")); denoising_program.add_kernel(ustring("filter_finalize")); - denoising_program.add_kernel(ustring("filter_set_tiles")); vector programs; programs.push_back(&base_program); @@ -739,7 +738,6 @@ bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr, device_ptr out_ptr, DenoisingTask *task) { - int stride = task->buffer.stride; int w = task->buffer.width; int h = task->buffer.h; @@ -748,24 +746,23 @@ bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr, float a = task->nlm_state.a; float k_2 = task->nlm_state.k_2; - int shift_stride = stride*h; + int pass_stride = task->buffer.pass_stride; int num_shifts = (2*r+1)*(2*r+1); - int mem_size = sizeof(float)*shift_stride*num_shifts; - cl_mem weightAccum = CL_MEM_PTR(task->nlm_state.temporary_3_ptr); - - cl_mem difference = clCreateBuffer(cxContext, CL_MEM_READ_WRITE, mem_size, NULL, &ciErr); - opencl_assert_err(ciErr, "clCreateBuffer denoising_non_local_means"); - cl_mem blurDifference = clCreateBuffer(cxContext, CL_MEM_READ_WRITE, mem_size, NULL, &ciErr); - opencl_assert_err(ciErr, "clCreateBuffer denoising_non_local_means"); + device_sub_ptr difference(task->buffer.temporary_mem, 0, pass_stride*num_shifts); + device_sub_ptr blurDifference(task->buffer.temporary_mem, pass_stride*num_shifts, pass_stride*num_shifts); + device_sub_ptr weightAccum(task->buffer.temporary_mem, 2*pass_stride*num_shifts, pass_stride); + cl_mem weightAccum_mem = CL_MEM_PTR(*weightAccum); + cl_mem difference_mem = CL_MEM_PTR(*difference); + cl_mem blurDifference_mem = CL_MEM_PTR(*blurDifference); cl_mem image_mem = CL_MEM_PTR(image_ptr); cl_mem guide_mem = CL_MEM_PTR(guide_ptr); cl_mem variance_mem = CL_MEM_PTR(variance_ptr); cl_mem out_mem = CL_MEM_PTR(out_ptr); - mem_zero_kernel(task->nlm_state.temporary_3_ptr, sizeof(float)*w*h); - mem_zero_kernel(out_ptr, sizeof(float)*w*h); + mem_zero_kernel(*difference, sizeof(float)*pass_stride); + mem_zero_kernel(out_ptr, sizeof(float)*pass_stride); cl_kernel ckNLMCalcDifference = denoising_program(ustring("filter_nlm_calc_difference")); cl_kernel ckNLMBlur = denoising_program(ustring("filter_nlm_blur")); @@ -776,29 +773,29 @@ bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr, kernel_set_args(ckNLMCalcDifference, 0, guide_mem, variance_mem, - difference, + difference_mem, w, h, stride, - shift_stride, + pass_stride, r, 0, a, k_2); kernel_set_args(ckNLMBlur, 0, - difference, - blurDifference, + difference_mem, + blurDifference_mem, w, h, stride, - shift_stride, + pass_stride, r, f); kernel_set_args(ckNLMCalcWeight, 0, - blurDifference, - difference, + blurDifference_mem, + difference_mem, w, h, stride, - shift_stride, + pass_stride, r, f); kernel_set_args(ckNLMUpdateOutput, 0, - blurDifference, + blurDifference_mem, image_mem, out_mem, - weightAccum, + weightAccum_mem, w, h, stride, - shift_stride, + pass_stride, r, f); enqueue_kernel(ckNLMCalcDifference, w*h, num_shifts, true); @@ -807,11 +804,8 @@ bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr, enqueue_kernel(ckNLMBlur, w*h, num_shifts, true); enqueue_kernel(ckNLMUpdateOutput, w*h, num_shifts, true); - opencl_assert(clReleaseMemObject(difference)); - opencl_assert(clReleaseMemObject(blurDifference)); - kernel_set_args(ckNLMNormalize, 0, - out_mem, weightAccum, w, h, stride); + out_mem, weightAccum_mem, w, h, stride); enqueue_kernel(ckNLMNormalize, w, h); return true; @@ -977,13 +971,20 @@ bool OpenCLDeviceBase::denoising_divide_shadow(device_ptr a_ptr, cl_mem sv_variance_mem = CL_MEM_PTR(sv_variance_ptr); cl_mem buffer_variance_mem = CL_MEM_PTR(buffer_variance_ptr); - cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer); + cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer); cl_kernel ckFilterDivideShadow = denoising_program(ustring("filter_divide_shadow")); - kernel_set_args(ckFilterDivideShadow, 0, - task->render_buffer.samples, - tiles_mem, + int arg_ofs = kernel_set_args(ckFilterDivideShadow, 0, + task->render_buffer.samples, + tile_info_mem); + cl_mem buffers[9]; + for(int i = 0; i < 9; i++) { + buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]); + arg_ofs += kernel_set_args(ckFilterDivideShadow, arg_ofs, + buffers[i]); + } + kernel_set_args(ckFilterDivideShadow, arg_ofs, a_mem, b_mem, sample_variance_mem, @@ -991,7 +992,7 @@ bool OpenCLDeviceBase::denoising_divide_shadow(device_ptr a_ptr, buffer_variance_mem, task->rect, task->render_buffer.pass_stride, - task->render_buffer.denoising_data_offset); + task->render_buffer.offset); enqueue_kernel(ckFilterDivideShadow, task->rect.z-task->rect.x, task->rect.w-task->rect.y); @@ -1008,20 +1009,27 @@ bool OpenCLDeviceBase::denoising_get_feature(int mean_offset, cl_mem mean_mem = CL_MEM_PTR(mean_ptr); cl_mem variance_mem = CL_MEM_PTR(variance_ptr); - cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer); + cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer); cl_kernel ckFilterGetFeature = denoising_program(ustring("filter_get_feature")); - kernel_set_args(ckFilterGetFeature, 0, - task->render_buffer.samples, - tiles_mem, + int arg_ofs = kernel_set_args(ckFilterGetFeature, 0, + task->render_buffer.samples, + tile_info_mem); + cl_mem buffers[9]; + for(int i = 0; i < 9; i++) { + buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]); + arg_ofs += kernel_set_args(ckFilterGetFeature, arg_ofs, + buffers[i]); + } + kernel_set_args(ckFilterGetFeature, arg_ofs, mean_offset, variance_offset, mean_mem, variance_mem, task->rect, task->render_buffer.pass_stride, - task->render_buffer.denoising_data_offset); + task->render_buffer.offset); enqueue_kernel(ckFilterGetFeature, task->rect.z-task->rect.x, task->rect.w-task->rect.y); @@ -1056,29 +1064,8 @@ bool OpenCLDeviceBase::denoising_detect_outliers(device_ptr image_ptr, return true; } -bool OpenCLDeviceBase::denoising_set_tiles(device_ptr *buffers, - DenoisingTask *task) -{ - task->tiles_mem.copy_to_device(); - - cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer); - - cl_kernel ckFilterSetTiles = denoising_program(ustring("filter_set_tiles")); - - kernel_set_args(ckFilterSetTiles, 0, tiles_mem); - for(int i = 0; i < 9; i++) { - cl_mem buffer_mem = CL_MEM_PTR(buffers[i]); - kernel_set_args(ckFilterSetTiles, i+1, buffer_mem); - } - - enqueue_kernel(ckFilterSetTiles, 1, 1); - - return true; -} - -void OpenCLDeviceBase::denoise(RenderTile &rtile, DenoisingTask& denoising, const DeviceTask &task) +void OpenCLDeviceBase::denoise(RenderTile &rtile, DenoisingTask& denoising) { - denoising.functions.set_tiles = function_bind(&OpenCLDeviceBase::denoising_set_tiles, this, _1, &denoising); denoising.functions.construct_transform = function_bind(&OpenCLDeviceBase::denoising_construct_transform, this, &denoising); denoising.functions.reconstruct = function_bind(&OpenCLDeviceBase::denoising_reconstruct, this, _1, _2, _3, &denoising); denoising.functions.divide_shadow = function_bind(&OpenCLDeviceBase::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising); @@ -1089,17 +1076,9 @@ void OpenCLDeviceBase::denoise(RenderTile &rtile, DenoisingTask& denoising, cons denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h); denoising.render_buffer.samples = rtile.sample; + denoising.buffer.gpu_temporary_mem = true; - RenderTile rtiles[9]; - rtiles[4] = rtile; - task.map_neighbor_tiles(rtiles, this); - denoising.tiles_from_rendertiles(rtiles); - - denoising.init_from_devicetask(task); - - denoising.run_denoising(); - - task.unmap_neighbor_tiles(rtiles, this); + denoising.run_denoising(&rtile); } void OpenCLDeviceBase::shader(DeviceTask& task) diff --git a/intern/cycles/device/opencl/opencl_mega.cpp b/intern/cycles/device/opencl/opencl_mega.cpp index ef39cfb5f7db..e004c0b44f48 100644 --- a/intern/cycles/device/opencl/opencl_mega.cpp +++ b/intern/cycles/device/opencl/opencl_mega.cpp @@ -107,7 +107,7 @@ class OpenCLDeviceMegaKernel : public OpenCLDeviceBase } else if(task->type == DeviceTask::RENDER) { RenderTile tile; - DenoisingTask denoising(this); + DenoisingTask denoising(this, *task); /* Keep rendering tiles until done. */ while(task->acquire_tile(this, tile)) { @@ -141,7 +141,7 @@ class OpenCLDeviceMegaKernel : public OpenCLDeviceBase } else if(tile.task == RenderTile::DENOISE) { tile.sample = tile.start_sample + tile.num_samples; - denoise(tile, denoising, *task); + denoise(tile, denoising); task->update_progress(&tile, tile.w*tile.h); } diff --git a/intern/cycles/device/opencl/opencl_split.cpp b/intern/cycles/device/opencl/opencl_split.cpp index 51d3c7bb10f5..66a4aa7e891b 100644 --- a/intern/cycles/device/opencl/opencl_split.cpp +++ b/intern/cycles/device/opencl/opencl_split.cpp @@ -129,7 +129,7 @@ class OpenCLDeviceSplitKernel : public OpenCLDeviceBase } else if(task->type == DeviceTask::RENDER) { RenderTile tile; - DenoisingTask denoising(this); + DenoisingTask denoising(this, *task); /* Allocate buffer for kernel globals */ device_only_memory kgbuffer(this, "kernel_globals"); @@ -159,7 +159,7 @@ class OpenCLDeviceSplitKernel : public OpenCLDeviceBase } else if(tile.task == RenderTile::DENOISE) { tile.sample = tile.start_sample + tile.num_samples; - denoise(tile, denoising, *task); + denoise(tile, denoising); task->update_progress(&tile, tile.w*tile.h); } diff --git a/intern/cycles/device/opencl/opencl_util.cpp b/intern/cycles/device/opencl/opencl_util.cpp index 78ed401bff53..895e4149a3ac 100644 --- a/intern/cycles/device/opencl/opencl_util.cpp +++ b/intern/cycles/device/opencl/opencl_util.cpp @@ -831,13 +831,15 @@ void OpenCLInfo::get_usable_devices(vector *usable_devices FIRST_VLOG(2) << "Adding new device " << readable_device_name << "."; string hardware_id = get_hardware_id(platform_name, device_id); + string device_extensions = get_device_extensions(device_id); usable_devices->push_back(OpenCLPlatformDevice( platform_id, platform_name, device_id, device_type, readable_device_name, - hardware_id)); + hardware_id, + device_extensions)); } else { FIRST_VLOG(2) << "Ignoring device " << device_name @@ -1047,6 +1049,40 @@ string OpenCLInfo::get_device_name(cl_device_id device_id) return device_name; } +bool OpenCLInfo::get_device_extensions(cl_device_id device_id, + string *device_extensions, + cl_int* error) +{ + char buffer[1024]; + cl_int err; + if((err = clGetDeviceInfo(device_id, + CL_DEVICE_EXTENSIONS, + sizeof(buffer), + &buffer, + NULL)) != CL_SUCCESS) + { + if(error != NULL) { + *error = err; + } + *device_extensions = ""; + return false; + } + if(error != NULL) { + *error = CL_SUCCESS; + } + *device_extensions = buffer; + return true; +} + +string OpenCLInfo::get_device_extensions(cl_device_id device_id) +{ + string device_extensions; + if(!get_device_extensions(device_id, &device_extensions)) { + return ""; + } + return device_extensions; +} + bool OpenCLInfo::get_device_type(cl_device_id device_id, cl_device_type *device_type, cl_int* error) @@ -1100,6 +1136,21 @@ string OpenCLInfo::get_readable_device_name(cl_device_id device_id) name = get_device_name(device_id); } + /* Special exception for AMD Vega, need to be able to tell + * Vega 56 from 64 apart. + */ + if(name == "Radeon RX Vega") { + cl_int max_compute_units = 0; + if(clGetDeviceInfo(device_id, + CL_DEVICE_MAX_COMPUTE_UNITS, + sizeof(max_compute_units), + &max_compute_units, + NULL) == CL_SUCCESS) + { + name += " " + to_string(max_compute_units); + } + } + /* Distinguish from our native CPU device. */ if(get_device_type(device_id) & CL_DEVICE_TYPE_CPU) { name += " (OpenCL)"; diff --git a/intern/cycles/doc/license/Apache_2.0.txt b/intern/cycles/doc/license/Apache_2.0.txt index 6b0b1270ff0c..d64569567334 100644 --- a/intern/cycles/doc/license/Apache_2.0.txt +++ b/intern/cycles/doc/license/Apache_2.0.txt @@ -200,4 +200,3 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - diff --git a/intern/cycles/doc/license/ILM.txt b/intern/cycles/doc/license/ILM.txt index 0e24aa562038..8b68abc954df 100644 --- a/intern/cycles/doc/license/ILM.txt +++ b/intern/cycles/doc/license/ILM.txt @@ -13,7 +13,7 @@ met: distribution. * Neither the name of Industrial Light & Magic nor the names of its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. + from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -26,4 +26,3 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/intern/cycles/doc/license/NVidia.txt b/intern/cycles/doc/license/NVidia.txt index 4fa55d3d2bc0..42c165e11d20 100644 --- a/intern/cycles/doc/license/NVidia.txt +++ b/intern/cycles/doc/license/NVidia.txt @@ -33,4 +33,3 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - diff --git a/intern/cycles/doc/license/OSL.txt b/intern/cycles/doc/license/OSL.txt index 1ffeb58291e6..e716b5c5e10e 100644 --- a/intern/cycles/doc/license/OSL.txt +++ b/intern/cycles/doc/license/OSL.txt @@ -25,4 +25,3 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/intern/cycles/doc/license/Sobol.txt b/intern/cycles/doc/license/Sobol.txt index 4ad42d22fb19..0bce8349fe51 100644 --- a/intern/cycles/doc/license/Sobol.txt +++ b/intern/cycles/doc/license/Sobol.txt @@ -26,4 +26,3 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/intern/cycles/doc/license/readme.txt b/intern/cycles/doc/license/readme.txt index 4c56c90a0f19..cc5476e35118 100644 --- a/intern/cycles/doc/license/readme.txt +++ b/intern/cycles/doc/license/readme.txt @@ -13,4 +13,3 @@ MIT license Boost License * Boost and OpenCL dynamic loading - diff --git a/intern/cycles/graph/CMakeLists.txt b/intern/cycles/graph/CMakeLists.txt index 168ca0210e7d..0ce56c2b2e62 100644 --- a/intern/cycles/graph/CMakeLists.txt +++ b/intern/cycles/graph/CMakeLists.txt @@ -20,4 +20,3 @@ include_directories(${INC}) include_directories(SYSTEM ${INC_SYS}) cycles_add_library(cycles_graph ${SRC} ${SRC_HEADERS}) - diff --git a/intern/cycles/graph/node.cpp b/intern/cycles/graph/node.cpp index b16c6af5d0e4..19fe0a168eaa 100644 --- a/intern/cycles/graph/node.cpp +++ b/intern/cycles/graph/node.cpp @@ -425,36 +425,40 @@ bool Node::equals(const Node& other) const /* Hash */ +namespace { + template -static void value_hash(const Node *node, const SocketType& socket, MD5Hash& md5) +void value_hash(const Node *node, const SocketType& socket, MD5Hash& md5) { md5.append(((uint8_t*)node) + socket.struct_offset, socket.size()); } -static void float3_hash(const Node *node, const SocketType& socket, MD5Hash& md5) +void float3_hash(const Node *node, const SocketType& socket, MD5Hash& md5) { /* Don't compare 4th element used for padding. */ md5.append(((uint8_t*)node) + socket.struct_offset, sizeof(float) * 3); } template -static void array_hash(const Node *node, const SocketType& socket, MD5Hash& md5) +void array_hash(const Node *node, const SocketType& socket, MD5Hash& md5) { const array& a = *(const array*)(((char*)node) + socket.struct_offset); - for (size_t i = 0; i < a.size(); i++) { + for(size_t i = 0; i < a.size(); i++) { md5.append((uint8_t*)&a[i], sizeof(T)); } } -static void float3_array_hash(const Node *node, const SocketType& socket, MD5Hash& md5) +void float3_array_hash(const Node *node, const SocketType& socket, MD5Hash& md5) { /* Don't compare 4th element used for padding. */ const array& a = *(const array*)(((char*)node) + socket.struct_offset); - for (size_t i = 0; i < a.size(); i++) { + for(size_t i = 0; i < a.size(); i++) { md5.append((uint8_t*)&a[i], sizeof(float) * 3); } } +} // namespace + void Node::hash(MD5Hash& md5) { md5.append(type->name.string()); @@ -495,5 +499,77 @@ void Node::hash(MD5Hash& md5) } } -CCL_NAMESPACE_END +namespace { + +template +size_t array_size_in_bytes(const Node *node, const SocketType& socket) +{ + const array& a = *(const array*)(((char*)node) + socket.struct_offset); + return a.size() * sizeof(T); +} +} // namespace + +size_t Node::get_total_size_in_bytes() const +{ + size_t total_size = 0; + foreach(const SocketType& socket, type->inputs) { + switch(socket.type) { + case SocketType::BOOLEAN: + case SocketType::FLOAT: + case SocketType::INT: + case SocketType::UINT: + case SocketType::COLOR: + case SocketType::VECTOR: + case SocketType::POINT: + case SocketType::NORMAL: + case SocketType::POINT2: + case SocketType::CLOSURE: + case SocketType::STRING: + case SocketType::ENUM: + case SocketType::TRANSFORM: + case SocketType::NODE: + total_size += socket.size(); + break; + + case SocketType::BOOLEAN_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::FLOAT_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::INT_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::COLOR_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::VECTOR_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::POINT_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::NORMAL_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::POINT2_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::STRING_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::TRANSFORM_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + case SocketType::NODE_ARRAY: + total_size += array_size_in_bytes(this, socket); + break; + + case SocketType::UNDEFINED: break; + } + } + return total_size; +} + +CCL_NAMESPACE_END diff --git a/intern/cycles/graph/node.h b/intern/cycles/graph/node.h index d198c38be32a..11695a8631de 100644 --- a/intern/cycles/graph/node.h +++ b/intern/cycles/graph/node.h @@ -92,9 +92,11 @@ struct Node /* compute hash of node and its socket values */ void hash(MD5Hash& md5); + /* Get total size of this node. */ + size_t get_total_size_in_bytes() const; + ustring name; const NodeType *type; }; CCL_NAMESPACE_END - diff --git a/intern/cycles/graph/node_enum.h b/intern/cycles/graph/node_enum.h index 4e40c294f4f0..9de776ddb55d 100644 --- a/intern/cycles/graph/node_enum.h +++ b/intern/cycles/graph/node_enum.h @@ -45,4 +45,3 @@ struct NodeEnum { }; CCL_NAMESPACE_END - diff --git a/intern/cycles/graph/node_type.cpp b/intern/cycles/graph/node_type.cpp index 37aae211e93e..e045777e9694 100644 --- a/intern/cycles/graph/node_type.cpp +++ b/intern/cycles/graph/node_type.cpp @@ -134,7 +134,7 @@ NodeType::~NodeType() void NodeType::register_input(ustring name, ustring ui_name, SocketType::Type type, int struct_offset, const void *default_value, const NodeEnum *enum_values, - const NodeType **node_type, int flags, int extra_flags) + const NodeType **node_type, int flags, int extra_flags) { SocketType socket; socket.name = name; @@ -217,4 +217,3 @@ const NodeType *NodeType::find(ustring name) } CCL_NAMESPACE_END - diff --git a/intern/cycles/graph/node_type.h b/intern/cycles/graph/node_type.h index 15d34a79bb84..1d565794b27a 100644 --- a/intern/cycles/graph/node_type.h +++ b/intern/cycles/graph/node_type.h @@ -114,9 +114,9 @@ struct NodeType void register_input(ustring name, ustring ui_name, SocketType::Type type, int struct_offset, const void *default_value, - const NodeEnum *enum_values = NULL, - const NodeType **node_type = NULL, - int flags = 0, int extra_flags = 0); + const NodeEnum *enum_values = NULL, + const NodeType **node_type = NULL, + int flags = 0, int extra_flags = 0); void register_output(ustring name, ustring ui_name, SocketType::Type type); const SocketType *find_input(ustring name) const; @@ -263,4 +263,3 @@ const NodeType *structname::register_type() { type->register_output(ustring(#name), ustring(ui_name), SocketType::ENUM); } CCL_NAMESPACE_END - diff --git a/intern/cycles/graph/node_xml.cpp b/intern/cycles/graph/node_xml.cpp index f4599e22d40f..b7a28b427e51 100644 --- a/intern/cycles/graph/node_xml.cpp +++ b/intern/cycles/graph/node_xml.cpp @@ -458,4 +458,3 @@ xml_node xml_write_node(Node *node, xml_node xml_root) } CCL_NAMESPACE_END - diff --git a/intern/cycles/graph/node_xml.h b/intern/cycles/graph/node_xml.h index b648c9666c1a..5fecf40f96ce 100644 --- a/intern/cycles/graph/node_xml.h +++ b/intern/cycles/graph/node_xml.h @@ -32,4 +32,3 @@ void xml_read_node(XMLReader& reader, Node *node, xml_node xml_node); xml_node xml_write_node(Node *node, xml_node xml_root); CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/CMakeLists.txt b/intern/cycles/kernel/CMakeLists.txt index c2688cd71f75..c6e92c6d89de 100644 --- a/intern/cycles/kernel/CMakeLists.txt +++ b/intern/cycles/kernel/CMakeLists.txt @@ -76,6 +76,12 @@ set(SRC_BVH_HEADERS bvh/qbvh_traversal.h bvh/qbvh_volume.h bvh/qbvh_volume_all.h + bvh/obvh_nodes.h + bvh/obvh_shadow_all.h + bvh/obvh_local.h + bvh/obvh_traversal.h + bvh/obvh_volume.h + bvh/obvh_volume_all.h ) set(SRC_HEADERS @@ -156,6 +162,7 @@ set(SRC_CLOSURE_HEADERS closure/volume.h closure/bsdf_principled_diffuse.h closure/bsdf_principled_sheen.h + closure/bsdf_hair_principled.h ) set(SRC_SVM_HEADERS @@ -269,6 +276,8 @@ set(SRC_UTIL_HEADERS ../util/util_types_float3_impl.h ../util/util_types_float4.h ../util/util_types_float4_impl.h + ../util/util_types_float8.h + ../util/util_types_float8_impl.h ../util/util_types_int2.h ../util/util_types_int2_impl.h ../util/util_types_int3.h @@ -287,6 +296,7 @@ set(SRC_UTIL_HEADERS ../util/util_types_uint3_impl.h ../util/util_types_uint4.h ../util/util_types_uint4_impl.h + ../util/util_types_ushort4.h ../util/util_types_vector3.h ../util/util_types_vector3_impl.h ) @@ -355,8 +365,14 @@ if(WITH_CYCLES_CUDA_BINARIES) ) set(cuda_cubins) - macro(CYCLES_CUDA_KERNEL_ADD arch name flags sources experimental) + macro(CYCLES_CUDA_KERNEL_ADD arch prev_arch name flags sources experimental) set(cuda_cubin ${name}_${arch}.cubin) + + set(kernel_sources ${sources}) + if(NOT ${prev_arch} STREQUAL "none") + set(kernel_sources ${kernel_sources} ${name}_${prev_arch}.cubin) + endif() + set(cuda_kernel_src "/kernels/cuda/${name}.cu") set(cuda_flags @@ -400,7 +416,7 @@ if(WITH_CYCLES_CUDA_BINARIES) ${cuda_flags} -v -cuda-toolkit-dir "${CUDA_TOOLKIT_ROOT_DIR}" - DEPENDS ${sources} cycles_cubin_cc) + DEPENDS ${kernel_sources} cycles_cubin_cc) else() add_custom_command( OUTPUT ${cuda_cubin} @@ -411,7 +427,7 @@ if(WITH_CYCLES_CUDA_BINARIES) ${CMAKE_CURRENT_SOURCE_DIR}${cuda_kernel_src} --ptxas-options="-v" ${cuda_flags} - DEPENDS ${sources}) + DEPENDS ${kernel_sources}) endif() delayed_install("${CMAKE_CURRENT_BINARY_DIR}" "${cuda_cubin}" ${CYCLES_INSTALL_PATH}/lib) list(APPEND cuda_cubins ${cuda_cubin}) @@ -419,18 +435,23 @@ if(WITH_CYCLES_CUDA_BINARIES) unset(cuda_debug_flags) endmacro() + set(prev_arch "none") foreach(arch ${CYCLES_CUDA_BINARIES_ARCH}) if(${arch} MATCHES "sm_2.") message(STATUS "CUDA binaries for ${arch} are no longer supported, skipped.") else() # Compile regular kernel - CYCLES_CUDA_KERNEL_ADD(${arch} filter "" "${cuda_filter_sources}" FALSE) - CYCLES_CUDA_KERNEL_ADD(${arch} kernel "" "${cuda_sources}" FALSE) - endif() + CYCLES_CUDA_KERNEL_ADD(${arch} ${prev_arch} filter "" "${cuda_filter_sources}" FALSE) + CYCLES_CUDA_KERNEL_ADD(${arch} ${prev_arch} kernel "" "${cuda_sources}" FALSE) - if(WITH_CYCLES_CUDA_SPLIT_KERNEL_BINARIES) - # Compile split kernel - CYCLES_CUDA_KERNEL_ADD(${arch} kernel_split "-D __SPLIT__" ${cuda_sources} FALSE) + if(WITH_CYCLES_CUDA_SPLIT_KERNEL_BINARIES) + # Compile split kernel + CYCLES_CUDA_KERNEL_ADD(${arch} ${prev_arch} kernel_split "-D __SPLIT__" "${cuda_sources}" FALSE) + endif() + + if(WITH_CYCLES_CUDA_BUILD_SERIAL) + set(prev_arch ${arch}) + endif() endif() endforeach() @@ -520,4 +541,3 @@ delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_SVM_HEADERS}" ${CYCLES_INSTAL delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_GEOM_HEADERS}" ${CYCLES_INSTALL_PATH}/source/kernel/geom) delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_UTIL_HEADERS}" ${CYCLES_INSTALL_PATH}/source/util) delayed_install(${CMAKE_CURRENT_SOURCE_DIR} "${SRC_SPLIT_HEADERS}" ${CYCLES_INSTALL_PATH}/source/kernel/split) - diff --git a/intern/cycles/kernel/bvh/bvh.h b/intern/cycles/kernel/bvh/bvh.h index de1503e55647..2ad55d041bfc 100644 --- a/intern/cycles/kernel/bvh/bvh.h +++ b/intern/cycles/kernel/bvh/bvh.h @@ -32,6 +32,9 @@ CCL_NAMESPACE_BEGIN /* Common QBVH functions. */ #ifdef __QBVH__ # include "kernel/bvh/qbvh_nodes.h" +#ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_nodes.h" +#endif #endif /* Regular BVH traversal */ diff --git a/intern/cycles/kernel/bvh/bvh_local.h b/intern/cycles/kernel/bvh/bvh_local.h index 6356c197dd1c..2b02f4527bb7 100644 --- a/intern/cycles/kernel/bvh/bvh_local.h +++ b/intern/cycles/kernel/bvh/bvh_local.h @@ -19,6 +19,9 @@ #ifdef __QBVH__ # include "kernel/bvh/qbvh_local.h" +# ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_local.h" +# endif #endif #if BVH_FEATURE(BVH_HAIR) @@ -70,10 +73,9 @@ bool BVH_FUNCTION_FULL_NAME(BVH)(KernelGlobals *kg, int object = OBJECT_NONE; float isect_t = ray->t; - if(local_isect) { + if(local_isect != NULL) { local_isect->num_hits = 0; } - kernel_assert((local_isect == NULL) == (max_hits == 0)); const int object_flag = kernel_tex_fetch(__object_flag, local_object); @@ -254,6 +256,15 @@ ccl_device_inline bool BVH_FUNCTION_NAME(KernelGlobals *kg, int max_hits) { switch(kernel_data.bvh.bvh_layout) { +#ifdef __KERNEL_AVX2__ + case BVH_LAYOUT_BVH8: + return BVH_FUNCTION_FULL_NAME(OBVH)(kg, + ray, + local_isect, + local_object, + lcg_state, + max_hits); +#endif #ifdef __QBVH__ case BVH_LAYOUT_BVH4: return BVH_FUNCTION_FULL_NAME(QBVH)(kg, diff --git a/intern/cycles/kernel/bvh/bvh_shadow_all.h b/intern/cycles/kernel/bvh/bvh_shadow_all.h index cfc567ff9ca4..d525b29fd94b 100644 --- a/intern/cycles/kernel/bvh/bvh_shadow_all.h +++ b/intern/cycles/kernel/bvh/bvh_shadow_all.h @@ -19,6 +19,9 @@ #ifdef __QBVH__ # include "kernel/bvh/qbvh_shadow_all.h" +#ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_shadow_all.h" +#endif #endif #if BVH_FEATURE(BVH_HAIR) @@ -396,6 +399,15 @@ ccl_device_inline bool BVH_FUNCTION_NAME(KernelGlobals *kg, uint *num_hits) { switch(kernel_data.bvh.bvh_layout) { +#ifdef __KERNEL_AVX2__ + case BVH_LAYOUT_BVH8: + return BVH_FUNCTION_FULL_NAME(OBVH)(kg, + ray, + isect_array, + visibility, + max_hits, + num_hits); +#endif #ifdef __QBVH__ case BVH_LAYOUT_BVH4: return BVH_FUNCTION_FULL_NAME(QBVH)(kg, diff --git a/intern/cycles/kernel/bvh/bvh_traversal.h b/intern/cycles/kernel/bvh/bvh_traversal.h index 551625eae784..e95d2408201b 100644 --- a/intern/cycles/kernel/bvh/bvh_traversal.h +++ b/intern/cycles/kernel/bvh/bvh_traversal.h @@ -20,6 +20,9 @@ #ifdef __QBVH__ # include "kernel/bvh/qbvh_traversal.h" #endif +#ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_traversal.h" +#endif #if BVH_FEATURE(BVH_HAIR) # define NODE_INTERSECT bvh_node_intersect @@ -427,6 +430,19 @@ ccl_device_inline bool BVH_FUNCTION_NAME(KernelGlobals *kg, ) { switch(kernel_data.bvh.bvh_layout) { +#ifdef __KERNEL_AVX2__ + case BVH_LAYOUT_BVH8: + return BVH_FUNCTION_FULL_NAME(OBVH)(kg, + ray, + isect, + visibility +# if BVH_FEATURE(BVH_HAIR_MINIMUM_WIDTH) + , lcg_state, + difl, + extmax +# endif + ); +#endif #ifdef __QBVH__ case BVH_LAYOUT_BVH4: return BVH_FUNCTION_FULL_NAME(QBVH)(kg, diff --git a/intern/cycles/kernel/bvh/bvh_types.h b/intern/cycles/kernel/bvh/bvh_types.h index ead424aaaafc..4ca0dc2225e5 100644 --- a/intern/cycles/kernel/bvh/bvh_types.h +++ b/intern/cycles/kernel/bvh/bvh_types.h @@ -32,7 +32,7 @@ CCL_NAMESPACE_BEGIN /* 64 object BVH + 64 mesh BVH + 64 object node splitting */ #define BVH_STACK_SIZE 192 #define BVH_QSTACK_SIZE 384 - +#define BVH_OSTACK_SIZE 768 /* BVH intersection function variations */ #define BVH_INSTANCING 1 diff --git a/intern/cycles/kernel/bvh/bvh_volume.h b/intern/cycles/kernel/bvh/bvh_volume.h index ce5fc7be33d2..7d03855cb8fb 100644 --- a/intern/cycles/kernel/bvh/bvh_volume.h +++ b/intern/cycles/kernel/bvh/bvh_volume.h @@ -19,6 +19,9 @@ #ifdef __QBVH__ # include "kernel/bvh/qbvh_volume.h" +#ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_volume.h" +#endif #endif #if BVH_FEATURE(BVH_HAIR) @@ -310,6 +313,13 @@ ccl_device_inline bool BVH_FUNCTION_NAME(KernelGlobals *kg, const uint visibility) { switch(kernel_data.bvh.bvh_layout) { +#ifdef __KERNEL_AVX2__ + case BVH_LAYOUT_BVH8: + return BVH_FUNCTION_FULL_NAME(OBVH)(kg, + ray, + isect, + visibility); +#endif #ifdef __QBVH__ case BVH_LAYOUT_BVH4: return BVH_FUNCTION_FULL_NAME(QBVH)(kg, diff --git a/intern/cycles/kernel/bvh/bvh_volume_all.h b/intern/cycles/kernel/bvh/bvh_volume_all.h index f2379efc6560..3d9b598914f4 100644 --- a/intern/cycles/kernel/bvh/bvh_volume_all.h +++ b/intern/cycles/kernel/bvh/bvh_volume_all.h @@ -19,6 +19,9 @@ #ifdef __QBVH__ # include "kernel/bvh/qbvh_volume_all.h" +#ifdef __KERNEL_AVX2__ +# include "kernel/bvh/obvh_volume_all.h" +#endif #endif #if BVH_FEATURE(BVH_HAIR) @@ -212,14 +215,16 @@ uint BVH_FUNCTION_FULL_NAME(BVH)(KernelGlobals *kg, isect_array->t = isect_t; if(num_hits == max_hits) { #if BVH_FEATURE(BVH_INSTANCING) + if(object != OBJECT_NONE) { # if BVH_FEATURE(BVH_MOTION) - float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); # else - Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); - float t_fac = 1.0f / len(transform_direction(&itfm, dir)); + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); # endif - for(int i = 0; i < num_hits_in_instance; i++) { - (isect_array-i-1)->t *= t_fac; + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } } #endif /* BVH_FEATURE(BVH_INSTANCING) */ return num_hits; @@ -257,14 +262,16 @@ uint BVH_FUNCTION_FULL_NAME(BVH)(KernelGlobals *kg, isect_array->t = isect_t; if(num_hits == max_hits) { # if BVH_FEATURE(BVH_INSTANCING) + if(object != OBJECT_NONE) { # if BVH_FEATURE(BVH_MOTION) - float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); # else - Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); - float t_fac = 1.0f / len(transform_direction(&itfm, dir)); + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); # endif - for(int i = 0; i < num_hits_in_instance; i++) { - (isect_array-i-1)->t *= t_fac; + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } } # endif /* BVH_FEATURE(BVH_INSTANCING) */ return num_hits; @@ -382,6 +389,14 @@ ccl_device_inline uint BVH_FUNCTION_NAME(KernelGlobals *kg, const uint visibility) { switch(kernel_data.bvh.bvh_layout) { +#ifdef __KERNEL_AVX2__ + case BVH_LAYOUT_BVH8: + return BVH_FUNCTION_FULL_NAME(OBVH)(kg, + ray, + isect_array, + max_hits, + visibility); +#endif #ifdef __QBVH__ case BVH_LAYOUT_BVH4: return BVH_FUNCTION_FULL_NAME(QBVH)(kg, diff --git a/intern/cycles/kernel/bvh/obvh_local.h b/intern/cycles/kernel/bvh/obvh_local.h new file mode 100644 index 000000000000..92143193a6a4 --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_local.h @@ -0,0 +1,412 @@ +/* + * Copyright 2011-2013 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This is a template BVH traversal function for subsurface scattering, where + * various features can be enabled/disabled. This way we can compile optimized + * versions for each case without new features slowing things down. + * + * BVH_MOTION: motion blur rendering + * + */ + +#if BVH_FEATURE(BVH_HAIR) +# define NODE_INTERSECT obvh_node_intersect +#else +# define NODE_INTERSECT obvh_aligned_node_intersect +#endif + +ccl_device bool BVH_FUNCTION_FULL_NAME(OBVH)(KernelGlobals *kg, + const Ray *ray, + LocalIntersection *local_isect, + int local_object, + uint *lcg_state, + int max_hits) +{ + /* Traversal stack in CUDA thread-local memory. */ + OBVHStackItem traversal_stack[BVH_OSTACK_SIZE]; + traversal_stack[0].addr = ENTRYPOINT_SENTINEL; + + /* Traversal variables in registers. */ + int stack_ptr = 0; + int node_addr = kernel_tex_fetch(__object_node, local_object); + + /* Ray parameters in registers. */ + float3 P = ray->P; + float3 dir = bvh_clamp_direction(ray->D); + float3 idir = bvh_inverse_direction(dir); + int object = OBJECT_NONE; + float isect_t = ray->t; + + if(local_isect != NULL) { + local_isect->num_hits = 0; + } + kernel_assert((local_isect == NULL) == (max_hits == 0)); + + const int object_flag = kernel_tex_fetch(__object_flag, local_object); + if(!(object_flag & SD_OBJECT_TRANSFORM_APPLIED)) { +#if BVH_FEATURE(BVH_MOTION) + Transform ob_itfm; + isect_t = bvh_instance_motion_push(kg, + local_object, + ray, + &P, + &dir, + &idir, + isect_t, + &ob_itfm); +#else + isect_t = bvh_instance_push(kg, local_object, ray, &P, &dir, &idir, isect_t); +#endif + object = local_object; + } + +#ifndef __KERNEL_SSE41__ + if(!isfinite(P.x)) { + return false; + } +#endif + + avxf tnear(0.0f), tfar(isect_t); +#if BVH_FEATURE(BVH_HAIR) + avx3f dir4(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +#endif + avx3f idir4(avxf(idir.x), avxf(idir.y), avxf(idir.z)); + +#ifdef __KERNEL_AVX2__ + float3 P_idir = P*idir; + avx3f P_idir4(P_idir.x, P_idir.y, P_idir.z); +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + avx3f org4(avxf(P.x), avxf(P.y), avxf(P.z)); +#endif + + /* Offsets to select the side that becomes the lower or upper bound. */ + int near_x, near_y, near_z; + int far_x, far_y, far_z; + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + + /* Traversal loop. */ + do { + do { + /* Traverse internal nodes. */ + while(node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { + avxf dist; + int child_mask = NODE_INTERSECT(kg, + tnear, + tfar, +#ifdef __KERNEL_AVX2__ + P_idir4, +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4, +#endif +#if BVH_FEATURE(BVH_HAIR) + dir4, +#endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + &dist); + + if(child_mask != 0) { + float4 inodes = kernel_tex_fetch(__bvh_nodes, node_addr+0); + avxf cnodes; +#if BVH_FEATURE(BVH_HAIR) + if(__float_as_uint(inodes.x) & PATH_RAY_NODE_UNALIGNED) { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+26); + } + else +#endif + { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+14); + } + + /* One child is hit, continue with that child. */ + int r = __bscf(child_mask); + if(child_mask == 0) { + node_addr = __float_as_int(cnodes[r]); + continue; + } + + /* Two children are hit, push far child, and continue with + * closer child. + */ + int c0 = __float_as_int(cnodes[r]); + float d0 = ((float*)&dist)[r]; + r = __bscf(child_mask); + int c1 = __float_as_int(cnodes[r]); + float d1 = ((float*)&dist)[r]; + if(child_mask == 0) { + if(d1 < d0) { + node_addr = c1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + continue; + } + else { + node_addr = c0; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + continue; + } + } + + /* Here starts the slow path for 3 or 4 hit children. We push + * all nodes onto the stack to sort them there. + */ + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + + /* Three children are hit, push all onto stack and sort 3 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c2 = __float_as_int(cnodes[r]); + float d2 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Four children are hit, push all onto stack and sort 4 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c3 = __float_as_int(cnodes[r]); + float d3 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + + /* Five children are hit, push all onto stack and sort 5 + * stack items, continue with closest child + */ + r = __bscf(child_mask); + int c4 = __float_as_int(cnodes[r]); + float d4 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + /* Six children are hit, push all onto stack and sort 6 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c5 = __float_as_int(cnodes[r]); + float d5 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + + /* Seven children are hit, push all onto stack and sort 7 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c6 = __float_as_int(cnodes[r]); + float d6 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + /* Eight children are hit, push all onto stack and sort 8 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c7 = __float_as_int(cnodes[r]); + float d7 = ((float*)&dist)[r]; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c7; + traversal_stack[stack_ptr].dist = d7; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6], + &traversal_stack[stack_ptr - 7]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + + /* If node is leaf, fetch triangle list. */ + if(node_addr < 0) { + float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr-1)); + int prim_addr = __float_as_int(leaf.x); + + int prim_addr2 = __float_as_int(leaf.y); + const uint type = __float_as_int(leaf.w); + + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + + /* Primitive intersection. */ + switch(type & PRIMITIVE_ALL) { + case PRIMITIVE_TRIANGLE: { + /* Intersect ray against primitive, */ + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + if(triangle_intersect_local(kg, + local_isect, + P, + dir, + object, + local_object, + prim_addr, + isect_t, + lcg_state, + max_hits)) + { + return true; + } + } + break; + } +#if BVH_FEATURE(BVH_MOTION) + case PRIMITIVE_MOTION_TRIANGLE: { + /* Intersect ray against primitive. */ + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + if(motion_triangle_intersect_local(kg, + local_isect, + P, + dir, + ray->time, + object, + local_object, + prim_addr, + isect_t, + lcg_state, + max_hits)) + { + return true; + } + } + break; + } +#endif + default: + break; + } + } + } while(node_addr != ENTRYPOINT_SENTINEL); + } while(node_addr != ENTRYPOINT_SENTINEL); + return false; +} + +#undef NODE_INTERSECT diff --git a/intern/cycles/kernel/bvh/obvh_nodes.h b/intern/cycles/kernel/bvh/obvh_nodes.h new file mode 100644 index 000000000000..93f35f6dffb6 --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_nodes.h @@ -0,0 +1,532 @@ +/* + * Copyright 2011-2014, Blender Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Aligned nodes intersection AVX code is adopted from Embree, + */ + +struct OBVHStackItem { + int addr; + float dist; +}; + +ccl_device_inline void obvh_near_far_idx_calc(const float3& idir, + int *ccl_restrict near_x, + int *ccl_restrict near_y, + int *ccl_restrict near_z, + int *ccl_restrict far_x, + int *ccl_restrict far_y, + int *ccl_restrict far_z) + +{ +#ifdef __KERNEL_SSE__ + *near_x = 0; *far_x = 1; + *near_y = 2; *far_y = 3; + *near_z = 4; *far_z = 5; + + const size_t mask = movemask(ssef(idir.m128)); + + const int mask_x = mask & 1; + const int mask_y = (mask & 2) >> 1; + const int mask_z = (mask & 4) >> 2; + + *near_x += mask_x; *far_x -= mask_x; + *near_y += mask_y; *far_y -= mask_y; + *near_z += mask_z; *far_z -= mask_z; +#else + if(idir.x >= 0.0f) { *near_x = 0; *far_x = 1; } else { *near_x = 1; *far_x = 0; } + if(idir.y >= 0.0f) { *near_y = 2; *far_y = 3; } else { *near_y = 3; *far_y = 2; } + if(idir.z >= 0.0f) { *near_z = 4; *far_z = 5; } else { *near_z = 5; *far_z = 4; } +#endif +} + +ccl_device_inline void obvh_item_swap(OBVHStackItem *ccl_restrict a, + OBVHStackItem *ccl_restrict b) +{ + OBVHStackItem tmp = *a; + *a = *b; + *b = tmp; +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3) +{ + if(s2->dist < s1->dist) { obvh_item_swap(s2, s1); } + if(s3->dist < s2->dist) { obvh_item_swap(s3, s2); } + if(s2->dist < s1->dist) { obvh_item_swap(s2, s1); } +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3, + OBVHStackItem *ccl_restrict s4) +{ + if(s2->dist < s1->dist) { obvh_item_swap(s2, s1); } + if(s4->dist < s3->dist) { obvh_item_swap(s4, s3); } + if(s3->dist < s1->dist) { obvh_item_swap(s3, s1); } + if(s4->dist < s2->dist) { obvh_item_swap(s4, s2); } + if(s3->dist < s2->dist) { obvh_item_swap(s3, s2); } +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3, + OBVHStackItem *ccl_restrict s4, + OBVHStackItem *ccl_restrict s5) +{ + obvh_stack_sort(s1, s2, s3, s4); + if(s5->dist < s4->dist) { + obvh_item_swap(s4, s5); + if(s4->dist < s3->dist) { + obvh_item_swap(s3, s4); + if(s3->dist < s2->dist) { + obvh_item_swap(s2, s3); + if(s2->dist < s1->dist) { + obvh_item_swap(s1, s2); + } + } + } + } +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3, + OBVHStackItem *ccl_restrict s4, + OBVHStackItem *ccl_restrict s5, + OBVHStackItem *ccl_restrict s6) +{ + obvh_stack_sort(s1, s2, s3, s4, s5); + if(s6->dist < s5->dist) { + obvh_item_swap(s5, s6); + if(s5->dist < s4->dist) { + obvh_item_swap(s4, s5); + if(s4->dist < s3->dist) { + obvh_item_swap(s3, s4); + if(s3->dist < s2->dist) { + obvh_item_swap(s2, s3); + if(s2->dist < s1->dist) { + obvh_item_swap(s1, s2); + } + } + } + } + } +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3, + OBVHStackItem *ccl_restrict s4, + OBVHStackItem *ccl_restrict s5, + OBVHStackItem *ccl_restrict s6, + OBVHStackItem *ccl_restrict s7) +{ + obvh_stack_sort(s1, s2, s3, s4, s5, s6); + if(s7->dist < s6->dist) { + obvh_item_swap(s6, s7); + if(s6->dist < s5->dist) { + obvh_item_swap(s5, s6); + if(s5->dist < s4->dist) { + obvh_item_swap(s4, s5); + if(s4->dist < s3->dist) { + obvh_item_swap(s3, s4); + if(s3->dist < s2->dist) { + obvh_item_swap(s2, s3); + if(s2->dist < s1->dist) { + obvh_item_swap(s1, s2); + } + } + } + } + } + } +} + +ccl_device_inline void obvh_stack_sort(OBVHStackItem *ccl_restrict s1, + OBVHStackItem *ccl_restrict s2, + OBVHStackItem *ccl_restrict s3, + OBVHStackItem *ccl_restrict s4, + OBVHStackItem *ccl_restrict s5, + OBVHStackItem *ccl_restrict s6, + OBVHStackItem *ccl_restrict s7, + OBVHStackItem *ccl_restrict s8) +{ + obvh_stack_sort(s1, s2, s3, s4, s5, s6, s7); + if(s8->dist < s7->dist) { + obvh_item_swap(s7, s8); + if(s7->dist < s6->dist) { + obvh_item_swap(s6, s7); + if(s6->dist < s5->dist) { + obvh_item_swap(s5, s6); + if(s5->dist < s4->dist) { + obvh_item_swap(s4, s5); + if(s4->dist < s3->dist) { + obvh_item_swap(s3, s4); + if(s3->dist < s2->dist) { + obvh_item_swap(s2, s3); + if(s2->dist < s1->dist) { + obvh_item_swap(s1, s2); + } + } + } + } + } + } + } +} + +/* Axis-aligned nodes intersection */ + +ccl_device_inline int obvh_aligned_node_intersect(KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& org_idir, +#else + const avx3f& org, +#endif + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + avxf *ccl_restrict dist) +{ + const int offset = node_addr + 2; +#ifdef __KERNEL_AVX2__ + const avxf tnear_x = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+near_x*2), idir.x, org_idir.x); + const avxf tnear_y = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+near_y*2), idir.y, org_idir.y); + const avxf tnear_z = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+near_z*2), idir.z, org_idir.z); + const avxf tfar_x = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+far_x*2), idir.x, org_idir.x); + const avxf tfar_y = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+far_y*2), idir.y, org_idir.y); + const avxf tfar_z = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset+far_z*2), idir.z, org_idir.z); + + const avxf tnear = max4(tnear_x, tnear_y, tnear_z, isect_near); + const avxf tfar = min4(tfar_x, tfar_y, tfar_z, isect_far); + const avxb vmask = tnear <= tfar; + int mask = (int)movemask(vmask); + *dist = tnear; + return mask; +#else + return 0; +#endif +} + +ccl_device_inline int obvh_aligned_node_intersect_robust( + KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& P_idir, +#else + const avx3f& P, +#endif + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + const float difl, + avxf *ccl_restrict dist) +{ + const int offset = node_addr + 2; +#ifdef __KERNEL_AVX2__ + const avxf tnear_x = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + near_x * 2), idir.x, P_idir.x); + const avxf tfar_x = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + far_x * 2), idir.x, P_idir.x); + const avxf tnear_y = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + near_y * 2), idir.y, P_idir.y); + const avxf tfar_y = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + far_y * 2), idir.y, P_idir.y); + const avxf tnear_z = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + near_z * 2), idir.z, P_idir.z); + const avxf tfar_z = msub(kernel_tex_fetch_avxf(__bvh_nodes, offset + far_z * 2), idir.z, P_idir.z); + + const float round_down = 1.0f - difl; + const float round_up = 1.0f + difl; + const avxf tnear = max4(tnear_x, tnear_y, tnear_z, isect_near); + const avxf tfar = min4(tfar_x, tfar_y, tfar_z, isect_far); + const avxb vmask = round_down*tnear <= round_up*tfar; + int mask = (int)movemask(vmask); + *dist = tnear; + return mask; +#else + return 0; +#endif +} + +/* Unaligned nodes intersection */ + +ccl_device_inline int obvh_unaligned_node_intersect( + KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& org_idir, +#endif + const avx3f& org, + const avx3f& dir, + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + avxf *ccl_restrict dist) +{ + const int offset = node_addr; + const avxf tfm_x_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+2); + const avxf tfm_x_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+4); + const avxf tfm_x_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+6); + + const avxf tfm_y_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+8); + const avxf tfm_y_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+10); + const avxf tfm_y_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+12); + + const avxf tfm_z_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+14); + const avxf tfm_z_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+16); + const avxf tfm_z_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+18); + + const avxf tfm_t_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+20); + const avxf tfm_t_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+22); + const avxf tfm_t_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+24); + + const avxf aligned_dir_x = dir.x*tfm_x_x + dir.y*tfm_x_y + dir.z*tfm_x_z, + aligned_dir_y = dir.x*tfm_y_x + dir.y*tfm_y_y + dir.z*tfm_y_z, + aligned_dir_z = dir.x*tfm_z_x + dir.y*tfm_z_y + dir.z*tfm_z_z; + + const avxf aligned_P_x = org.x*tfm_x_x + org.y*tfm_x_y + org.z*tfm_x_z + tfm_t_x, + aligned_P_y = org.x*tfm_y_x + org.y*tfm_y_y + org.z*tfm_y_z + tfm_t_y, + aligned_P_z = org.x*tfm_z_x + org.y*tfm_z_y + org.z*tfm_z_z + tfm_t_z; + + const avxf neg_one(-1.0f); + const avxf nrdir_x = neg_one / aligned_dir_x, + nrdir_y = neg_one / aligned_dir_y, + nrdir_z = neg_one / aligned_dir_z; + + const avxf tlower_x = aligned_P_x * nrdir_x, + tlower_y = aligned_P_y * nrdir_y, + tlower_z = aligned_P_z * nrdir_z; + + const avxf tupper_x = tlower_x - nrdir_x, + tupper_y = tlower_y - nrdir_y, + tupper_z = tlower_z - nrdir_z; + + const avxf tnear_x = min(tlower_x, tupper_x); + const avxf tnear_y = min(tlower_y, tupper_y); + const avxf tnear_z = min(tlower_z, tupper_z); + const avxf tfar_x = max(tlower_x, tupper_x); + const avxf tfar_y = max(tlower_y, tupper_y); + const avxf tfar_z = max(tlower_z, tupper_z); + const avxf tnear = max4(isect_near, tnear_x, tnear_y, tnear_z); + const avxf tfar = min4(isect_far, tfar_x, tfar_y, tfar_z); + const avxb vmask = tnear <= tfar; + *dist = tnear; + return movemask(vmask); +} + +ccl_device_inline int obvh_unaligned_node_intersect_robust( + KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& P_idir, +#endif + const avx3f& P, + const avx3f& dir, + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + const float difl, + avxf *ccl_restrict dist) +{ + const int offset = node_addr; + const avxf tfm_x_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+2); + const avxf tfm_x_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+4); + const avxf tfm_x_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+6); + + const avxf tfm_y_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+8); + const avxf tfm_y_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+10); + const avxf tfm_y_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+12); + + const avxf tfm_z_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+14); + const avxf tfm_z_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+16); + const avxf tfm_z_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+18); + + const avxf tfm_t_x = kernel_tex_fetch_avxf(__bvh_nodes, offset+20); + const avxf tfm_t_y = kernel_tex_fetch_avxf(__bvh_nodes, offset+22); + const avxf tfm_t_z = kernel_tex_fetch_avxf(__bvh_nodes, offset+24); + + const avxf aligned_dir_x = dir.x*tfm_x_x + dir.y*tfm_x_y + dir.z*tfm_x_z, + aligned_dir_y = dir.x*tfm_y_x + dir.y*tfm_y_y + dir.z*tfm_y_z, + aligned_dir_z = dir.x*tfm_z_x + dir.y*tfm_z_y + dir.z*tfm_z_z; + + const avxf aligned_P_x = P.x*tfm_x_x + P.y*tfm_x_y + P.z*tfm_x_z + tfm_t_x, + aligned_P_y = P.x*tfm_y_x + P.y*tfm_y_y + P.z*tfm_y_z + tfm_t_y, + aligned_P_z = P.x*tfm_z_x + P.y*tfm_z_y + P.z*tfm_z_z + tfm_t_z; + + const avxf neg_one(-1.0f); + const avxf nrdir_x = neg_one / aligned_dir_x, + nrdir_y = neg_one / aligned_dir_y, + nrdir_z = neg_one / aligned_dir_z; + + const avxf tlower_x = aligned_P_x * nrdir_x, + tlower_y = aligned_P_y * nrdir_y, + tlower_z = aligned_P_z * nrdir_z; + + const avxf tupper_x = tlower_x - nrdir_x, + tupper_y = tlower_y - nrdir_y, + tupper_z = tlower_z - nrdir_z; + + const float round_down = 1.0f - difl; + const float round_up = 1.0f + difl; + + const avxf tnear_x = min(tlower_x, tupper_x); + const avxf tnear_y = min(tlower_y, tupper_y); + const avxf tnear_z = min(tlower_z, tupper_z); + const avxf tfar_x = max(tlower_x, tupper_x); + const avxf tfar_y = max(tlower_y, tupper_y); + const avxf tfar_z = max(tlower_z, tupper_z); + + const avxf tnear = max4(isect_near, tnear_x, tnear_y, tnear_z); + const avxf tfar = min4(isect_far, tfar_x, tfar_y, tfar_z); + const avxb vmask = round_down*tnear <= round_up*tfar; + *dist = tnear; + return movemask(vmask); +} + +/* Intersectors wrappers. + * + * They'll check node type and call appropriate intersection code. + */ + +ccl_device_inline int obvh_node_intersect( + KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& org_idir, +#endif + const avx3f& org, + const avx3f& dir, + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + avxf *ccl_restrict dist) +{ + const int offset = node_addr; + const float4 node = kernel_tex_fetch(__bvh_nodes, offset); + if(__float_as_uint(node.x) & PATH_RAY_NODE_UNALIGNED) { + return obvh_unaligned_node_intersect(kg, + isect_near, + isect_far, +#ifdef __KERNEL_AVX2__ + org_idir, +#endif + org, + dir, + idir, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + dist); + } + else { + return obvh_aligned_node_intersect(kg, + isect_near, + isect_far, +#ifdef __KERNEL_AVX2__ + org_idir, +#else + org, +#endif + idir, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + dist); + } +} + +ccl_device_inline int obvh_node_intersect_robust( + KernelGlobals *ccl_restrict kg, + const avxf& isect_near, + const avxf& isect_far, +#ifdef __KERNEL_AVX2__ + const avx3f& P_idir, +#endif + const avx3f& P, + const avx3f& dir, + const avx3f& idir, + const int near_x, + const int near_y, + const int near_z, + const int far_x, + const int far_y, + const int far_z, + const int node_addr, + const float difl, + avxf *ccl_restrict dist) +{ + const int offset = node_addr; + const float4 node = kernel_tex_fetch(__bvh_nodes, offset); + if(__float_as_uint(node.x) & PATH_RAY_NODE_UNALIGNED) { + return obvh_unaligned_node_intersect_robust(kg, + isect_near, + isect_far, +#ifdef __KERNEL_AVX2__ + P_idir, +#endif + P, + dir, + idir, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + difl, + dist); + } + else { + return obvh_aligned_node_intersect_robust(kg, + isect_near, + isect_far, +#ifdef __KERNEL_AVX2__ + P_idir, +#else + P, +#endif + idir, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + difl, + dist); + } +} diff --git a/intern/cycles/kernel/bvh/obvh_shadow_all.h b/intern/cycles/kernel/bvh/obvh_shadow_all.h new file mode 100644 index 000000000000..3e8770651275 --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_shadow_all.h @@ -0,0 +1,687 @@ +/* + * Copyright 2011-2013 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This is a template BVH traversal function, where various features can be + * enabled/disabled. This way we can compile optimized versions for each case + * without new features slowing things down. + * + * BVH_INSTANCING: object instancing + * BVH_HAIR: hair curve rendering + * BVH_MOTION: motion blur rendering + * + */ + +#if BVH_FEATURE(BVH_HAIR) +# define NODE_INTERSECT obvh_node_intersect +#else +# define NODE_INTERSECT obvh_aligned_node_intersect +#endif + +ccl_device bool BVH_FUNCTION_FULL_NAME(OBVH)(KernelGlobals *kg, + const Ray *ray, + Intersection *isect_array, + const int skip_object, + const uint max_hits, + uint *num_hits) +{ + /* TODO(sergey): + * - Test if pushing distance on the stack helps. + * - Likely and unlikely for if() statements. + * - Test restrict attribute for pointers. + */ + + /* Traversal stack in CUDA thread-local memory. */ + OBVHStackItem traversal_stack[BVH_OSTACK_SIZE]; + traversal_stack[0].addr = ENTRYPOINT_SENTINEL; + + /* Traversal variables in registers. */ + int stack_ptr = 0; + int node_addr = kernel_data.bvh.root; + + /* Ray parameters in registers. */ + const float tmax = ray->t; + float3 P = ray->P; + float3 dir = bvh_clamp_direction(ray->D); + float3 idir = bvh_inverse_direction(dir); + int object = OBJECT_NONE; + float isect_t = tmax; + +#if BVH_FEATURE(BVH_MOTION) + Transform ob_itfm; +#endif + + *num_hits = 0; + isect_array->t = tmax; + +#ifndef __KERNEL_SSE41__ + if(!isfinite(P.x)) { + return false; + } +#endif + +#if BVH_FEATURE(BVH_INSTANCING) + int num_hits_in_instance = 0; +#endif + + avxf tnear(0.0f), tfar(isect_t); +#if BVH_FEATURE(BVH_HAIR) + avx3f dir4(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +#endif + avx3f idir4(avxf(idir.x), avxf(idir.y), avxf(idir.z)); + +#ifdef __KERNEL_AVX2__ + float3 P_idir = P*idir; + avx3f P_idir4(P_idir.x, P_idir.y, P_idir.z); +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + avx3f org4(avxf(P.x), avxf(P.y), avxf(P.z)); +#endif + + /* Offsets to select the side that becomes the lower or upper bound. */ + int near_x, near_y, near_z; + int far_x, far_y, far_z; + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + + /* Traversal loop. */ + do { + do { + /* Traverse internal nodes. */ + while(node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { + float4 inodes = kernel_tex_fetch(__bvh_nodes, node_addr+0); + (void)inodes; + + if(false +#ifdef __VISIBILITY_FLAG__ + || ((__float_as_uint(inodes.x) & PATH_RAY_SHADOW) == 0) +#endif +#if BVH_FEATURE(BVH_MOTION) + || UNLIKELY(ray->time < inodes.y) + || UNLIKELY(ray->time > inodes.z) +#endif + ) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + avxf dist; + int child_mask = NODE_INTERSECT(kg, + tnear, + tfar, +#ifdef __KERNEL_AVX2__ + P_idir4, +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) +//#if !defined(__KERNEL_AVX2__) + org4, +#endif +#if BVH_FEATURE(BVH_HAIR) + dir4, +#endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + &dist); + + if(child_mask != 0) { + avxf cnodes; +#if BVH_FEATURE(BVH_HAIR) + if(__float_as_uint(inodes.x) & PATH_RAY_NODE_UNALIGNED) { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+26); + } + else +#endif + { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+14); + } + + /* One child is hit, continue with that child. */ + int r = __bscf(child_mask); + if(child_mask == 0) { + node_addr = __float_as_int(cnodes[r]); + continue; + } + + /* Two children are hit, push far child, and continue with + * closer child. + */ + int c0 = __float_as_int(cnodes[r]); + float d0 = ((float*)&dist)[r]; + r = __bscf(child_mask); + int c1 = __float_as_int(cnodes[r]); + float d1 = ((float*)&dist)[r]; + if(child_mask == 0) { + if(d1 < d0) { + node_addr = c1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + continue; + } + else { + node_addr = c0; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + continue; + } + } + + /* Here starts the slow path for 3 or 4 hit children. We push + * all nodes onto the stack to sort them there. + */ + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + + /* Three children are hit, push all onto stack and sort 3 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c2 = __float_as_int(cnodes[r]); + float d2 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Four children are hit, push all onto stack and sort 4 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c3 = __float_as_int(cnodes[r]); + float d3 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + + /* Five children are hit, push all onto stack and sort 5 + * stack items, continue with closest child + */ + r = __bscf(child_mask); + int c4 = __float_as_int(cnodes[r]); + float d4 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Six children are hit, push all onto stack and sort 6 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c5 = __float_as_int(cnodes[r]); + float d5 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + + /* Seven children are hit, push all onto stack and sort 7 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c6 = __float_as_int(cnodes[r]); + float d6 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Eight children are hit, push all onto stack and sort 8 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c7 = __float_as_int(cnodes[r]); + float d7 = ((float*)&dist)[r]; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c7; + traversal_stack[stack_ptr].dist = d7; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6], + &traversal_stack[stack_ptr - 7]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + + /* If node is leaf, fetch triangle list. */ + if(node_addr < 0) { + float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr-1)); +#ifdef __VISIBILITY_FLAG__ + if((__float_as_uint(leaf.z) & PATH_RAY_SHADOW) == 0) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } +#endif + + int prim_addr = __float_as_int(leaf.x); + +#if BVH_FEATURE(BVH_INSTANCING) + if(prim_addr >= 0) { +#endif + int prim_addr2 = __float_as_int(leaf.y); + const uint type = __float_as_int(leaf.w); + const uint p_type = type & PRIMITIVE_ALL; + + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + + /* Primitive intersection. */ + if(p_type == PRIMITIVE_TRIANGLE) { + int prim_count = prim_addr2 - prim_addr; + if(prim_count < 3) { + while(prim_addr < prim_addr2) { + kernel_assert((kernel_tex_fetch(__prim_type, prim_addr) & PRIMITIVE_ALL) == p_type); + int hit = triangle_intersect(kg, + isect_array, + P, + dir, + PATH_RAY_SHADOW, + object, + prim_addr); + /* Shadow ray early termination. */ + if(hit) { + /* detect if this surface has a shader with transparent shadows */ + + /* todo: optimize so primitive visibility flag indicates if + * the primitive has a transparent shadow shader? */ + int prim = kernel_tex_fetch(__prim_index, isect_array->prim); + int shader = 0; + +#ifdef __HAIR__ + if(kernel_tex_fetch(__prim_type, isect_array->prim) & PRIMITIVE_ALL_TRIANGLE) +#endif + { + shader = kernel_tex_fetch(__tri_shader, prim); + } +#ifdef __HAIR__ + else { + float4 str = kernel_tex_fetch(__curves, prim); + shader = __float_as_int(str.z); + } +#endif + int flag = kernel_tex_fetch(__shaders, (shader & SHADER_MASK)).flags; + + /* if no transparent shadows, all light is blocked */ + if(!(flag & SD_HAS_TRANSPARENT_SHADOW)) { + return true; + } + /* if maximum number of hits reached, block all light */ + else if(*num_hits == max_hits) { + return true; + } + + /* move on to next entry in intersections array */ + isect_array++; + (*num_hits)++; +#if BVH_FEATURE(BVH_INSTANCING) + num_hits_in_instance++; +#endif + + isect_array->t = isect_t; + } + + prim_addr++; + } //while + } else { + kernel_assert((kernel_tex_fetch(__prim_type, (prim_addr)) & PRIMITIVE_ALL) == p_type); + +#if BVH_FEATURE(BVH_INSTANCING) + int* nhiptr = &num_hits_in_instance; +#else + int nhi= 0; + int *nhiptr = &nhi; +#endif + + int result = triangle_intersect8(kg, + &isect_array, + P, + dir, + PATH_RAY_SHADOW, + object, + prim_addr, + prim_count, + num_hits, + max_hits, + nhiptr, + isect_t); + if(result == 2) { + return true; + } + } // prim_count + } // PRIMITIVE_TRIANGLE + else { + while(prim_addr < prim_addr2) { + kernel_assert((kernel_tex_fetch(__prim_type, prim_addr) & PRIMITIVE_ALL) == p_type); + +#ifdef __SHADOW_TRICKS__ + uint tri_object = (object == OBJECT_NONE) + ? kernel_tex_fetch(__prim_object, prim_addr) + : object; + if(tri_object == skip_object) { + ++prim_addr; + continue; + } +#endif + + bool hit; + + /* todo: specialized intersect functions which don't fill in + * isect unless needed and check SD_HAS_TRANSPARENT_SHADOW? + * might give a few % performance improvement */ + + switch(p_type) { + +#if BVH_FEATURE(BVH_MOTION) + case PRIMITIVE_MOTION_TRIANGLE: { + hit = motion_triangle_intersect(kg, + isect_array, + P, + dir, + ray->time, + PATH_RAY_SHADOW, + object, + prim_addr); + break; + } +#endif +#if BVH_FEATURE(BVH_HAIR) + case PRIMITIVE_CURVE: + case PRIMITIVE_MOTION_CURVE: { + const uint curve_type = kernel_tex_fetch(__prim_type, prim_addr); + if(kernel_data.curve.curveflags & CURVE_KN_INTERPOLATE) { + hit = cardinal_curve_intersect(kg, + isect_array, + P, + dir, + PATH_RAY_SHADOW, + object, + prim_addr, + ray->time, + curve_type, + NULL, + 0, 0); + } + else { + hit = curve_intersect(kg, + isect_array, + P, + dir, + PATH_RAY_SHADOW, + object, + prim_addr, + ray->time, + curve_type, + NULL, + 0, 0); + } + break; + } +#endif + default: { + hit = false; + break; + } + } + + /* Shadow ray early termination. */ + if(hit) { + /* detect if this surface has a shader with transparent shadows */ + + /* todo: optimize so primitive visibility flag indicates if + * the primitive has a transparent shadow shader? */ + int prim = kernel_tex_fetch(__prim_index, isect_array->prim); + int shader = 0; + +#ifdef __HAIR__ + if(kernel_tex_fetch(__prim_type, isect_array->prim) & PRIMITIVE_ALL_TRIANGLE) +#endif + { + shader = kernel_tex_fetch(__tri_shader, prim); + } +#ifdef __HAIR__ + else { + float4 str = kernel_tex_fetch(__curves, prim); + shader = __float_as_int(str.z); + } +#endif + int flag = kernel_tex_fetch(__shaders, (shader & SHADER_MASK)).flags; + + /* if no transparent shadows, all light is blocked */ + if(!(flag & SD_HAS_TRANSPARENT_SHADOW)) { + return true; + } + /* if maximum number of hits reached, block all light */ + else if(*num_hits == max_hits) { + return true; + } + + /* move on to next entry in intersections array */ + isect_array++; + (*num_hits)++; +#if BVH_FEATURE(BVH_INSTANCING) + num_hits_in_instance++; +#endif + + isect_array->t = isect_t; + } + + prim_addr++; + }//while prim + } + } +#if BVH_FEATURE(BVH_INSTANCING) + else { + /* Instance push. */ + object = kernel_tex_fetch(__prim_object, -prim_addr-1); + +# if BVH_FEATURE(BVH_MOTION) + isect_t = bvh_instance_motion_push(kg, object, ray, &P, &dir, &idir, isect_t, &ob_itfm); +# else + isect_t = bvh_instance_push(kg, object, ray, &P, &dir, &idir, isect_t); +# endif + + num_hits_in_instance = 0; + isect_array->t = isect_t; + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect_t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = ENTRYPOINT_SENTINEL; + + node_addr = kernel_tex_fetch(__object_node, object); + + } + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + +#if BVH_FEATURE(BVH_INSTANCING) + if(stack_ptr >= 0) { + kernel_assert(object != OBJECT_NONE); + + /* Instance pop. */ + if(num_hits_in_instance) { + float t_fac; +# if BVH_FEATURE(BVH_MOTION) + bvh_instance_motion_pop_factor(kg, object, ray, &P, &dir, &idir, &t_fac, &ob_itfm); +# else + bvh_instance_pop_factor(kg, object, ray, &P, &dir, &idir, &t_fac); +# endif + /* Scale isect->t to adjust for instancing. */ + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } + } + else { +# if BVH_FEATURE(BVH_MOTION) + bvh_instance_motion_pop(kg, object, ray, &P, &dir, &idir, FLT_MAX, &ob_itfm); +# else + bvh_instance_pop(kg, object, ray, &P, &dir, &idir, FLT_MAX); +# endif + } + + isect_t = tmax; + isect_array->t = isect_t; + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect_t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + + return false; +} + +#undef NODE_INTERSECT diff --git a/intern/cycles/kernel/bvh/obvh_traversal.h b/intern/cycles/kernel/bvh/obvh_traversal.h new file mode 100644 index 000000000000..2021d8e1143b --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_traversal.h @@ -0,0 +1,642 @@ +/* + * Copyright 2011-2013 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This is a template BVH traversal function, where various features can be + * enabled/disabled. This way we can compile optimized versions for each case + * without new features slowing things down. + * + * BVH_INSTANCING: object instancing + * BVH_HAIR: hair curve rendering + * BVH_HAIR_MINIMUM_WIDTH: hair curve rendering with minimum width + * BVH_MOTION: motion blur rendering + * + */ + +#if BVH_FEATURE(BVH_HAIR) +# define NODE_INTERSECT obvh_node_intersect +# define NODE_INTERSECT_ROBUST obvh_node_intersect_robust +#else +# define NODE_INTERSECT obvh_aligned_node_intersect +# define NODE_INTERSECT_ROBUST obvh_aligned_node_intersect_robust +#endif + +ccl_device bool BVH_FUNCTION_FULL_NAME(OBVH)(KernelGlobals *kg, + const Ray *ray, + Intersection *isect, + const uint visibility +#if BVH_FEATURE(BVH_HAIR_MINIMUM_WIDTH) + ,uint *lcg_state, + float difl, + float extmax +#endif + ) +{ + /* Traversal stack in CUDA thread-local memory. */ + OBVHStackItem traversal_stack[BVH_OSTACK_SIZE]; + traversal_stack[0].addr = ENTRYPOINT_SENTINEL; + traversal_stack[0].dist = -FLT_MAX; + + /* Traversal variables in registers. */ + int stack_ptr = 0; + int node_addr = kernel_data.bvh.root; + float node_dist = -FLT_MAX; + + /* Ray parameters in registers. */ + float3 P = ray->P; + float3 dir = bvh_clamp_direction(ray->D); + float3 idir = bvh_inverse_direction(dir); + int object = OBJECT_NONE; + +#if BVH_FEATURE(BVH_MOTION) + Transform ob_itfm; +#endif + +#ifndef __KERNEL_SSE41__ + if(!isfinite(P.x)) { + return false; + } +#endif + + isect->t = ray->t; + isect->u = 0.0f; + isect->v = 0.0f; + isect->prim = PRIM_NONE; + isect->object = OBJECT_NONE; + + BVH_DEBUG_INIT(); + avxf tnear(0.0f), tfar(ray->t); +#if BVH_FEATURE(BVH_HAIR) + avx3f dir4(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +#endif + avx3f idir4(avxf(idir.x), avxf(idir.y), avxf(idir.z)); + +#ifdef __KERNEL_AVX2__ + float3 P_idir = P*idir; + avx3f P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + avx3f org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +#endif + + /* Offsets to select the side that becomes the lower or upper bound. */ + int near_x, near_y, near_z; + int far_x, far_y, far_z; + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + /* Traversal loop. */ + do { + do { + /* Traverse internal nodes. */ + while(node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { + float4 inodes = kernel_tex_fetch(__bvh_nodes, node_addr+0); + (void)inodes; + + if(UNLIKELY(node_dist > isect->t) +#if BVH_FEATURE(BVH_MOTION) + || UNLIKELY(ray->time < inodes.y) + || UNLIKELY(ray->time > inodes.z) +#endif +#ifdef __VISIBILITY_FLAG__ + || (__float_as_uint(inodes.x) & visibility) == 0 +#endif + ) + { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + int child_mask; + avxf dist; + + BVH_DEBUG_NEXT_NODE(); + +#if BVH_FEATURE(BVH_HAIR_MINIMUM_WIDTH) + if(difl != 0.0f) { + /* NOTE: We extend all the child BB instead of fetching + * and checking visibility flags for each of the, + * + * Need to test if doing opposite would be any faster. + */ + child_mask = NODE_INTERSECT_ROBUST(kg, + tnear, + tfar, +# ifdef __KERNEL_AVX2__ + P_idir4, +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4, +# endif +# if BVH_FEATURE(BVH_HAIR) + dir4, +# endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + difl, + &dist); + } + else +#endif /* BVH_HAIR_MINIMUM_WIDTH */ + { + child_mask = NODE_INTERSECT(kg, + tnear, + tfar, +#ifdef __KERNEL_AVX2__ + P_idir4, +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4, +#endif +#if BVH_FEATURE(BVH_HAIR) + dir4, +#endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + &dist); + } + + if(child_mask != 0) { + avxf cnodes; + /* TODO(sergey): Investigate whether moving cnodes upwards + * gives a speedup (will be different cache pattern but will + * avoid extra check here), + */ +#if BVH_FEATURE(BVH_HAIR) + if(__float_as_uint(inodes.x) & PATH_RAY_NODE_UNALIGNED) { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+26); + } + else +#endif + { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+14); + } + + /* One child is hit, continue with that child. */ + int r = __bscf(child_mask); + float d0 = ((float*)&dist)[r]; + if(child_mask == 0) { + node_addr = __float_as_int(cnodes[r]); + node_dist = d0; + continue; + } + + /* Two children are hit, push far child, and continue with + * closer child. + */ + int c0 = __float_as_int(cnodes[r]); + r = __bscf(child_mask); + int c1 = __float_as_int(cnodes[r]); + float d1 = ((float*)&dist)[r]; + if(child_mask == 0) { + if(d1 < d0) { + node_addr = c1; + node_dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + continue; + } + else { + node_addr = c0; + node_dist = d0; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + continue; + } + } + + /* Here starts the slow path for 3 or 4 hit children. We push + * all nodes onto the stack to sort them there. + */ + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + + /* Three children are hit, push all onto stack and sort 3 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c2 = __float_as_int(cnodes[r]); + float d2 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + /* Four children are hit, push all onto stack and sort 4 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c3 = __float_as_int(cnodes[r]); + float d3 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + + /* Five children are hit, push all onto stack and sort 5 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c4 = __float_as_int(cnodes[r]); + float d4 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + /* Six children are hit, push all onto stack and sort 6 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c5 = __float_as_int(cnodes[r]); + float d5 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + + /* Seven children are hit, push all onto stack and sort 7 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c6 = __float_as_int(cnodes[r]); + float d6 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + /* Eight children are hit, push all onto stack and sort 8 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c7 = __float_as_int(cnodes[r]); + float d7 = ((float*)&dist)[r]; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c7; + traversal_stack[stack_ptr].dist = d7; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6], + &traversal_stack[stack_ptr - 7]); + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + + + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + } + + /* If node is leaf, fetch triangle list. */ + if(node_addr < 0) { + float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr-1)); + +#ifdef __VISIBILITY_FLAG__ + if(UNLIKELY((node_dist > isect->t) || + ((__float_as_uint(leaf.z) & visibility) == 0))) +#else + if(UNLIKELY((node_dist > isect->t))) +#endif + { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + continue; + } + int prim_addr = __float_as_int(leaf.x); + +#if BVH_FEATURE(BVH_INSTANCING) + if(prim_addr >= 0) { +#endif + int prim_addr2 = __float_as_int(leaf.y); + const uint type = __float_as_int(leaf.w); + + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + + /* Primitive intersection. */ + switch(type & PRIMITIVE_ALL) { + case PRIMITIVE_TRIANGLE: { + int prim_count = prim_addr2 - prim_addr; + if(prim_count < 3) { + for(; prim_addr < prim_addr2; prim_addr++) { + BVH_DEBUG_NEXT_INTERSECTION(); + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + if(triangle_intersect(kg, + isect, + P, + dir, + visibility, + object, + prim_addr)) + { + tfar = avxf(isect->t); + /* Shadow ray early termination. */ + if(visibility == PATH_RAY_SHADOW_OPAQUE) { + return true; + } + } + }//for + } + else { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + if(triangle_intersect8(kg, + &isect, + P, + dir, + visibility, + object, + prim_addr, + prim_count, + 0, + 0, + NULL, + 0.0f)) + { + tfar = avxf(isect->t); + if(visibility == PATH_RAY_SHADOW_OPAQUE) { + return true; + } + } + }//prim count + break; + } +#if BVH_FEATURE(BVH_MOTION) + case PRIMITIVE_MOTION_TRIANGLE: { + for(; prim_addr < prim_addr2; prim_addr++) { + BVH_DEBUG_NEXT_INTERSECTION(); + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + if(motion_triangle_intersect(kg, + isect, + P, + dir, + ray->time, + visibility, + object, + prim_addr)) + { + tfar = avxf(isect->t); + /* Shadow ray early termination. */ + if(visibility == PATH_RAY_SHADOW_OPAQUE) { + return true; + } + } + } + break; + } +#endif /* BVH_FEATURE(BVH_MOTION) */ +#if BVH_FEATURE(BVH_HAIR) + case PRIMITIVE_CURVE: + case PRIMITIVE_MOTION_CURVE: { + for(; prim_addr < prim_addr2; prim_addr++) { + BVH_DEBUG_NEXT_INTERSECTION(); + const uint curve_type = kernel_tex_fetch(__prim_type, prim_addr); + kernel_assert((curve_type & PRIMITIVE_ALL) == (type & PRIMITIVE_ALL)); + bool hit; + if(kernel_data.curve.curveflags & CURVE_KN_INTERPOLATE) { + hit = cardinal_curve_intersect(kg, + isect, + P, + dir, + visibility, + object, + prim_addr, + ray->time, + curve_type, + lcg_state, + difl, + extmax); + } + else { + hit = curve_intersect(kg, + isect, + P, + dir, + visibility, + object, + prim_addr, + ray->time, + curve_type, + lcg_state, + difl, + extmax); + } + if(hit) { + tfar = avxf(isect->t); + /* Shadow ray early termination. */ + if(visibility == PATH_RAY_SHADOW_OPAQUE) { + return true; + } + } + } + break; + } +#endif /* BVH_FEATURE(BVH_HAIR) */ + } + } +#if BVH_FEATURE(BVH_INSTANCING) + else { + /* Instance push. */ + object = kernel_tex_fetch(__prim_object, -prim_addr-1); + +# if BVH_FEATURE(BVH_MOTION) + qbvh_instance_motion_push(kg, object, ray, &P, &dir, &idir, &isect->t, &node_dist, &ob_itfm); +# else + qbvh_instance_push(kg, object, ray, &P, &dir, &idir, &isect->t, &node_dist); +# endif + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect->t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = ENTRYPOINT_SENTINEL; + traversal_stack[stack_ptr].dist = -FLT_MAX; + + node_addr = kernel_tex_fetch(__object_node, object); + + BVH_DEBUG_NEXT_INSTANCE(); + } + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + +#if BVH_FEATURE(BVH_INSTANCING) + if(stack_ptr >= 0) { + kernel_assert(object != OBJECT_NONE); + + /* Instance pop. */ +# if BVH_FEATURE(BVH_MOTION) + isect->t = bvh_instance_motion_pop(kg, object, ray, &P, &dir, &idir, isect->t, &ob_itfm); +# else + isect->t = bvh_instance_pop(kg, object, ray, &P, &dir, &idir, isect->t); +# endif + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect->t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + node_dist = traversal_stack[stack_ptr].dist; + --stack_ptr; + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + + return (isect->prim != PRIM_NONE); +} + +#undef NODE_INTERSECT +#undef NODE_INTERSECT_ROBUST diff --git a/intern/cycles/kernel/bvh/obvh_volume.h b/intern/cycles/kernel/bvh/obvh_volume.h new file mode 100644 index 000000000000..da9ddbd4f242 --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_volume.h @@ -0,0 +1,483 @@ +/* + * Copyright 2011-2013 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This is a template BVH traversal function for volumes, where + * various features can be enabled/disabled. This way we can compile optimized + * versions for each case without new features slowing things down. + * + * BVH_INSTANCING: object instancing + * BVH_MOTION: motion blur rendering + * + */ + +#if BVH_FEATURE(BVH_HAIR) +# define NODE_INTERSECT obvh_node_intersect +#else +# define NODE_INTERSECT obvh_aligned_node_intersect +#endif + +ccl_device bool BVH_FUNCTION_FULL_NAME(OBVH)(KernelGlobals *kg, + const Ray *ray, + Intersection *isect, + const uint visibility) +{ + /* Traversal stack in CUDA thread-local memory. */ + OBVHStackItem traversal_stack[BVH_OSTACK_SIZE]; + traversal_stack[0].addr = ENTRYPOINT_SENTINEL; + + /* Traversal variables in registers. */ + int stack_ptr = 0; + int node_addr = kernel_data.bvh.root; + + /* Ray parameters in registers. */ + float3 P = ray->P; + float3 dir = bvh_clamp_direction(ray->D); + float3 idir = bvh_inverse_direction(dir); + int object = OBJECT_NONE; + +#if BVH_FEATURE(BVH_MOTION) + Transform ob_itfm; +#endif + +#ifndef __KERNEL_SSE41__ + if(!isfinite(P.x)) { + return false; + } +#endif + + isect->t = ray->t; + isect->u = 0.0f; + isect->v = 0.0f; + isect->prim = PRIM_NONE; + isect->object = OBJECT_NONE; + + avxf tnear(0.0f), tfar(ray->t); +#if BVH_FEATURE(BVH_HAIR) + avx3f dir4(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +#endif + avx3f idir4(avxf(idir.x), avxf(idir.y), avxf(idir.z)); + +#ifdef __KERNEL_AVX2__ + float3 P_idir = P*idir; + avx3f P_idir4(P_idir.x, P_idir.y, P_idir.z); +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + avx3f org4(avxf(P.x), avxf(P.y), avxf(P.z)); +#endif + + /* Offsets to select the side that becomes the lower or upper bound. */ + int near_x, near_y, near_z; + int far_x, far_y, far_z; + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + + /* Traversal loop. */ + do { + do { + /* Traverse internal nodes. */ + while(node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { + float4 inodes = kernel_tex_fetch(__bvh_nodes, node_addr+0); + +#ifdef __VISIBILITY_FLAG__ + if((__float_as_uint(inodes.x) & visibility) == 0) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } +#endif + + avxf dist; + int child_mask = NODE_INTERSECT(kg, + tnear, + tfar, +#ifdef __KERNEL_AVX2__ + P_idir4, +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4, +#endif +#if BVH_FEATURE(BVH_HAIR) + dir4, +#endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + &dist); + + if(child_mask != 0) { + avxf cnodes; +#if BVH_FEATURE(BVH_HAIR) + if(__float_as_uint(inodes.x) & PATH_RAY_NODE_UNALIGNED) { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+26); + } + else +#endif + { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+14); + } + + /* One child is hit, continue with that child. */ + int r = __bscf(child_mask); + if(child_mask == 0) { + node_addr = __float_as_int(cnodes[r]); + continue; + } + + /* Two children are hit, push far child, and continue with + * closer child. + */ + int c0 = __float_as_int(cnodes[r]); + float d0 = ((float*)&dist)[r]; + r = __bscf(child_mask); + int c1 = __float_as_int(cnodes[r]); + float d1 = ((float*)&dist)[r]; + if(child_mask == 0) { + if(d1 < d0) { + node_addr = c1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + continue; + } + else { + node_addr = c0; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + continue; + } + } + + /* Here starts the slow path for 3 or 4 hit children. We push + * all nodes onto the stack to sort them there. + */ + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + + /* Three children are hit, push all onto stack and sort 3 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c2 = __float_as_int(cnodes[r]); + float d2 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Four children are hit, push all onto stack and sort 4 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c3 = __float_as_int(cnodes[r]); + float d3 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + + /* Five children are hit, push all onto stack and sort 5 + * stack items, continue with closest child + */ + r = __bscf(child_mask); + int c4 = __float_as_int(cnodes[r]); + float d4 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Six children are hit, push all onto stack and sort 6 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c5 = __float_as_int(cnodes[r]); + float d5 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + + /* Seven children are hit, push all onto stack and sort 7 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c6 = __float_as_int(cnodes[r]); + float d6 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Eight children are hit, push all onto stack and sort 8 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c7 = __float_as_int(cnodes[r]); + float d7 = ((float*)&dist)[r]; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c7; + traversal_stack[stack_ptr].dist = d7; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6], + &traversal_stack[stack_ptr - 7]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + + /* If node is leaf, fetch triangle list. */ + if(node_addr < 0) { + float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr-1)); + + if((__float_as_uint(leaf.z) & visibility) == 0) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + int prim_addr = __float_as_int(leaf.x); + +#if BVH_FEATURE(BVH_INSTANCING) + if(prim_addr >= 0) { +#endif + int prim_addr2 = __float_as_int(leaf.y); + const uint type = __float_as_int(leaf.w); + const uint p_type = type & PRIMITIVE_ALL; + + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + + /* Primitive intersection. */ + switch(p_type) { + case PRIMITIVE_TRIANGLE: { + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + /* Only primitives from volume object. */ + uint tri_object = (object == OBJECT_NONE)? kernel_tex_fetch(__prim_object, prim_addr): object; + int object_flag = kernel_tex_fetch(__object_flag, tri_object); + if((object_flag & SD_OBJECT_HAS_VOLUME) == 0) { + continue; + } + /* Intersect ray against primitive. */ + triangle_intersect(kg, isect, P, dir, visibility, object, prim_addr); + } + break; + } +#if BVH_FEATURE(BVH_MOTION) + case PRIMITIVE_MOTION_TRIANGLE: { + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + /* Only primitives from volume object. */ + uint tri_object = (object == OBJECT_NONE)? kernel_tex_fetch(__prim_object, prim_addr): object; + int object_flag = kernel_tex_fetch(__object_flag, tri_object); + if((object_flag & SD_OBJECT_HAS_VOLUME) == 0) { + continue; + } + /* Intersect ray against primitive. */ + motion_triangle_intersect(kg, isect, P, dir, ray->time, visibility, object, prim_addr); + } + break; + } +#endif + } + } +#if BVH_FEATURE(BVH_INSTANCING) + else { + /* Instance push. */ + object = kernel_tex_fetch(__prim_object, -prim_addr-1); + int object_flag = kernel_tex_fetch(__object_flag, object); + if(object_flag & SD_OBJECT_HAS_VOLUME) { +# if BVH_FEATURE(BVH_MOTION) + isect->t = bvh_instance_motion_push(kg, object, ray, &P, &dir, &idir, isect->t, &ob_itfm); +# else + isect->t = bvh_instance_push(kg, object, ray, &P, &dir, &idir, isect->t); +# endif + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect->t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = ENTRYPOINT_SENTINEL; + + node_addr = kernel_tex_fetch(__object_node, object); + } + else { + /* Pop. */ + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + } + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + +#if BVH_FEATURE(BVH_INSTANCING) + if(stack_ptr >= 0) { + kernel_assert(object != OBJECT_NONE); + + /* Instance pop. */ +# if BVH_FEATURE(BVH_MOTION) + isect->t = bvh_instance_motion_pop(kg, object, ray, &P, &dir, &idir, isect->t, &ob_itfm); +# else + isect->t = bvh_instance_pop(kg, object, ray, &P, &dir, &idir, isect->t); +# endif + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect->t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + + return (isect->prim != PRIM_NONE); +} + +#undef NODE_INTERSECT diff --git a/intern/cycles/kernel/bvh/obvh_volume_all.h b/intern/cycles/kernel/bvh/obvh_volume_all.h new file mode 100644 index 000000000000..a88573e6f860 --- /dev/null +++ b/intern/cycles/kernel/bvh/obvh_volume_all.h @@ -0,0 +1,554 @@ +/* + * Copyright 2011-2013 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This is a template BVH traversal function for volumes, where + * various features can be enabled/disabled. This way we can compile optimized + * versions for each case without new features slowing things down. + * + * BVH_INSTANCING: object instancing + * BVH_MOTION: motion blur rendering + * + */ + +#if BVH_FEATURE(BVH_HAIR) +# define NODE_INTERSECT obvh_node_intersect +#else +# define NODE_INTERSECT obvh_aligned_node_intersect +#endif + +ccl_device uint BVH_FUNCTION_FULL_NAME(OBVH)(KernelGlobals *kg, + const Ray *ray, + Intersection *isect_array, + const uint max_hits, + const uint visibility) +{ + /* Traversal stack in CUDA thread-local memory. */ + OBVHStackItem traversal_stack[BVH_OSTACK_SIZE]; + traversal_stack[0].addr = ENTRYPOINT_SENTINEL; + + /* Traversal variables in registers. */ + int stack_ptr = 0; + int node_addr = kernel_data.bvh.root; + + /* Ray parameters in registers. */ + const float tmax = ray->t; + float3 P = ray->P; + float3 dir = bvh_clamp_direction(ray->D); + float3 idir = bvh_inverse_direction(dir); + int object = OBJECT_NONE; + float isect_t = tmax; + +#if BVH_FEATURE(BVH_MOTION) + Transform ob_itfm; +#endif + + uint num_hits = 0; + isect_array->t = tmax; + +#ifndef __KERNEL_SSE41__ + if(!isfinite(P.x)) { + return 0; + } +#endif + +#if BVH_FEATURE(BVH_INSTANCING) + int num_hits_in_instance = 0; +#endif + + avxf tnear(0.0f), tfar(isect_t); +#if BVH_FEATURE(BVH_HAIR) + avx3f dir4(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +#endif + avx3f idir4(avxf(idir.x), avxf(idir.y), avxf(idir.z)); + +#ifdef __KERNEL_AVX2__ + float3 P_idir = P*idir; + avx3f P_idir4(P_idir.x, P_idir.y, P_idir.z); +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + avx3f org4(avxf(P.x), avxf(P.y), avxf(P.z)); +#endif + + /* Offsets to select the side that becomes the lower or upper bound. */ + int near_x, near_y, near_z; + int far_x, far_y, far_z; + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + + /* Traversal loop. */ + do { + do { + /* Traverse internal nodes. */ + while(node_addr >= 0 && node_addr != ENTRYPOINT_SENTINEL) { + float4 inodes = kernel_tex_fetch(__bvh_nodes, node_addr+0); + +#ifdef __VISIBILITY_FLAG__ + if((__float_as_uint(inodes.x) & visibility) == 0) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } +#endif + + avxf dist; + int child_mask = NODE_INTERSECT(kg, + tnear, + tfar, +#ifdef __KERNEL_AVX2__ + P_idir4, +#endif +#if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4, +#endif +#if BVH_FEATURE(BVH_HAIR) + dir4, +#endif + idir4, + near_x, near_y, near_z, + far_x, far_y, far_z, + node_addr, + &dist); + + if(child_mask != 0) { + avxf cnodes; +#if BVH_FEATURE(BVH_HAIR) + if(__float_as_uint(inodes.x) & PATH_RAY_NODE_UNALIGNED) { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+26); + } + else +#endif + { + cnodes = kernel_tex_fetch_avxf(__bvh_nodes, node_addr+14); + } + + /* One child is hit, continue with that child. */ + int r = __bscf(child_mask); + if(child_mask == 0) { + node_addr = __float_as_int(cnodes[r]); + continue; + } + + /* Two children are hit, push far child, and continue with + * closer child. + */ + int c0 = __float_as_int(cnodes[r]); + float d0 = ((float*)&dist)[r]; + r = __bscf(child_mask); + int c1 = __float_as_int(cnodes[r]); + float d1 = ((float*)&dist)[r]; + if(child_mask == 0) { + if(d1 < d0) { + node_addr = c1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + continue; + } + else { + node_addr = c0; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + continue; + } + } + + /* Here starts the slow path for 3 or 4 hit children. We push + * all nodes onto the stack to sort them there. + */ + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c1; + traversal_stack[stack_ptr].dist = d1; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c0; + traversal_stack[stack_ptr].dist = d0; + + /* Three children are hit, push all onto stack and sort 3 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c2 = __float_as_int(cnodes[r]); + float d2 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Four children are hit, push all onto stack and sort 4 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c3 = __float_as_int(cnodes[r]); + float d3 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c3; + traversal_stack[stack_ptr].dist = d3; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c2; + traversal_stack[stack_ptr].dist = d2; + + /* Five children are hit, push all onto stack and sort 5 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c4 = __float_as_int(cnodes[r]); + float d4 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Six children are hit, push all onto stack and sort 6 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c5 = __float_as_int(cnodes[r]); + float d5 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c5; + traversal_stack[stack_ptr].dist = d5; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c4; + traversal_stack[stack_ptr].dist = d4; + + /* Seven children are hit, push all onto stack and sort 7 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c6 = __float_as_int(cnodes[r]); + float d6 = ((float*)&dist)[r]; + if(child_mask == 0) { + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + /* Eight children are hit, push all onto stack and sort 8 + * stack items, continue with closest child. + */ + r = __bscf(child_mask); + int c7 = __float_as_int(cnodes[r]); + float d7 = ((float*)&dist)[r]; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c7; + traversal_stack[stack_ptr].dist = d7; + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = c6; + traversal_stack[stack_ptr].dist = d6; + obvh_stack_sort(&traversal_stack[stack_ptr], + &traversal_stack[stack_ptr - 1], + &traversal_stack[stack_ptr - 2], + &traversal_stack[stack_ptr - 3], + &traversal_stack[stack_ptr - 4], + &traversal_stack[stack_ptr - 5], + &traversal_stack[stack_ptr - 6], + &traversal_stack[stack_ptr - 7]); + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + + /* If node is leaf, fetch triangle list. */ + if(node_addr < 0) { + float4 leaf = kernel_tex_fetch(__bvh_leaf_nodes, (-node_addr-1)); + + if((__float_as_uint(leaf.z) & visibility) == 0) { + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + continue; + } + + int prim_addr = __float_as_int(leaf.x); + +#if BVH_FEATURE(BVH_INSTANCING) + if(prim_addr >= 0) { +#endif + int prim_addr2 = __float_as_int(leaf.y); + const uint type = __float_as_int(leaf.w); + const uint p_type = type & PRIMITIVE_ALL; + bool hit; + + /* Pop. */ + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + + /* Primitive intersection. */ + switch(p_type) { + case PRIMITIVE_TRIANGLE: { + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + /* Only primitives from volume object. */ + uint tri_object = (object == OBJECT_NONE)? kernel_tex_fetch(__prim_object, prim_addr): object; + int object_flag = kernel_tex_fetch(__object_flag, tri_object); + if((object_flag & SD_OBJECT_HAS_VOLUME) == 0) { + continue; + } + /* Intersect ray against primitive. */ + hit = triangle_intersect(kg, isect_array, P, dir, visibility, object, prim_addr); + if(hit) { + /* Move on to next entry in intersections array. */ + isect_array++; + num_hits++; +#if BVH_FEATURE(BVH_INSTANCING) + num_hits_in_instance++; +#endif + isect_array->t = isect_t; + if(num_hits == max_hits) { +#if BVH_FEATURE(BVH_INSTANCING) +# if BVH_FEATURE(BVH_MOTION) + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); +# else + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); +# endif + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } +#endif /* BVH_FEATURE(BVH_INSTANCING) */ + return num_hits; + } + } + } + break; + } +#if BVH_FEATURE(BVH_MOTION) + case PRIMITIVE_MOTION_TRIANGLE: { + for(; prim_addr < prim_addr2; prim_addr++) { + kernel_assert(kernel_tex_fetch(__prim_type, prim_addr) == type); + /* Only primitives from volume object. */ + uint tri_object = (object == OBJECT_NONE)? kernel_tex_fetch(__prim_object, prim_addr): object; + int object_flag = kernel_tex_fetch(__object_flag, tri_object); + if((object_flag & SD_OBJECT_HAS_VOLUME) == 0) { + continue; + } + /* Intersect ray against primitive. */ + hit = motion_triangle_intersect(kg, isect_array, P, dir, ray->time, visibility, object, prim_addr); + if(hit) { + /* Move on to next entry in intersections array. */ + isect_array++; + num_hits++; +# if BVH_FEATURE(BVH_INSTANCING) + num_hits_in_instance++; +# endif + isect_array->t = isect_t; + if(num_hits == max_hits) { +# if BVH_FEATURE(BVH_INSTANCING) +# if BVH_FEATURE(BVH_MOTION) + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); +# else + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); +# endif + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } +# endif /* BVH_FEATURE(BVH_INSTANCING) */ + return num_hits; + } + } + } + break; + } +#endif + } + } +#if BVH_FEATURE(BVH_INSTANCING) + else { + /* Instance push. */ + object = kernel_tex_fetch(__prim_object, -prim_addr-1); + int object_flag = kernel_tex_fetch(__object_flag, object); + if(object_flag & SD_OBJECT_HAS_VOLUME) { +# if BVH_FEATURE(BVH_MOTION) + isect_t = bvh_instance_motion_push(kg, object, ray, &P, &dir, &idir, isect_t, &ob_itfm); +# else + isect_t = bvh_instance_push(kg, object, ray, &P, &dir, &idir, isect_t); +# endif + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect_t); + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + num_hits_in_instance = 0; + isect_array->t = isect_t; + + ++stack_ptr; + kernel_assert(stack_ptr < BVH_OSTACK_SIZE); + traversal_stack[stack_ptr].addr = ENTRYPOINT_SENTINEL; + + node_addr = kernel_tex_fetch(__object_node, object); + } + else { + /* Pop. */ + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } + } + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + +#if BVH_FEATURE(BVH_INSTANCING) + if(stack_ptr >= 0) { + kernel_assert(object != OBJECT_NONE); + + /* Instance pop. */ + if(num_hits_in_instance) { + float t_fac; +# if BVH_FEATURE(BVH_MOTION) + bvh_instance_motion_pop_factor(kg, object, ray, &P, &dir, &idir, &t_fac, &ob_itfm); +# else + bvh_instance_pop_factor(kg, object, ray, &P, &dir, &idir, &t_fac); +# endif + /* Scale isect->t to adjust for instancing. */ + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } + } + else { +# if BVH_FEATURE(BVH_MOTION) + bvh_instance_motion_pop(kg, object, ray, &P, &dir, &idir, FLT_MAX, &ob_itfm); +# else + bvh_instance_pop(kg, object, ray, &P, &dir, &idir, FLT_MAX); +# endif + } + + isect_t = tmax; + isect_array->t = isect_t; + + obvh_near_far_idx_calc(idir, + &near_x, &near_y, &near_z, + &far_x, &far_y, &far_z); + tfar = avxf(isect_t); +# if BVH_FEATURE(BVH_HAIR) + dir4 = avx3f(avxf(dir.x), avxf(dir.y), avxf(dir.z)); +# endif + idir4 = avx3f(avxf(idir.x), avxf(idir.y), avxf(idir.z)); +# ifdef __KERNEL_AVX2__ + P_idir = P*idir; + P_idir4 = avx3f(P_idir.x, P_idir.y, P_idir.z); +# endif +# if BVH_FEATURE(BVH_HAIR) || !defined(__KERNEL_AVX2__) + org4 = avx3f(avxf(P.x), avxf(P.y), avxf(P.z)); +# endif + + object = OBJECT_NONE; + node_addr = traversal_stack[stack_ptr].addr; + --stack_ptr; + } +#endif /* FEATURE(BVH_INSTANCING) */ + } while(node_addr != ENTRYPOINT_SENTINEL); + + return num_hits; +} + +#undef NODE_INTERSECT diff --git a/intern/cycles/kernel/bvh/qbvh_local.h b/intern/cycles/kernel/bvh/qbvh_local.h index 0dc0575556c1..ee3827de3098 100644 --- a/intern/cycles/kernel/bvh/qbvh_local.h +++ b/intern/cycles/kernel/bvh/qbvh_local.h @@ -59,10 +59,9 @@ ccl_device bool BVH_FUNCTION_FULL_NAME(QBVH)(KernelGlobals *kg, int object = OBJECT_NONE; float isect_t = ray->t; - if(local_isect) { + if(local_isect != NULL) { local_isect->num_hits = 0; } - kernel_assert((local_isect == NULL) == (max_hits == 0)); const int object_flag = kernel_tex_fetch(__object_flag, local_object); diff --git a/intern/cycles/kernel/bvh/qbvh_nodes.h b/intern/cycles/kernel/bvh/qbvh_nodes.h index 3036efd41986..2e622af17589 100644 --- a/intern/cycles/kernel/bvh/qbvh_nodes.h +++ b/intern/cycles/kernel/bvh/qbvh_nodes.h @@ -85,7 +85,8 @@ ccl_device_inline void qbvh_stack_sort(QBVHStackItem *ccl_restrict s1, /* Axis-aligned nodes intersection */ -ccl_device_inline int qbvh_aligned_node_intersect(KernelGlobals *ccl_restrict kg, +//ccl_device_inline int qbvh_aligned_node_intersect(KernelGlobals *ccl_restrict kg, +static int qbvh_aligned_node_intersect(KernelGlobals *ccl_restrict kg, const ssef& isect_near, const ssef& isect_far, #ifdef __KERNEL_AVX2__ diff --git a/intern/cycles/kernel/bvh/qbvh_volume_all.h b/intern/cycles/kernel/bvh/qbvh_volume_all.h index ac5f58a9a518..1e454e4d36b3 100644 --- a/intern/cycles/kernel/bvh/qbvh_volume_all.h +++ b/intern/cycles/kernel/bvh/qbvh_volume_all.h @@ -279,14 +279,16 @@ ccl_device uint BVH_FUNCTION_FULL_NAME(QBVH)(KernelGlobals *kg, isect_array->t = isect_t; if(num_hits == max_hits) { #if BVH_FEATURE(BVH_INSTANCING) + if(object != OBJECT_NONE) { # if BVH_FEATURE(BVH_MOTION) - float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); # else - Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); - float t_fac = 1.0f / len(transform_direction(&itfm, dir)); + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); # endif - for(int i = 0; i < num_hits_in_instance; i++) { - (isect_array-i-1)->t *= t_fac; + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } } #endif /* BVH_FEATURE(BVH_INSTANCING) */ return num_hits; @@ -317,14 +319,16 @@ ccl_device uint BVH_FUNCTION_FULL_NAME(QBVH)(KernelGlobals *kg, isect_array->t = isect_t; if(num_hits == max_hits) { # if BVH_FEATURE(BVH_INSTANCING) + if(object != OBJECT_NONE) { # if BVH_FEATURE(BVH_MOTION) - float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); + float t_fac = 1.0f / len(transform_direction(&ob_itfm, dir)); # else - Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); - float t_fac = 1.0f / len(transform_direction(&itfm, dir)); + Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM); + float t_fac = 1.0f / len(transform_direction(&itfm, dir)); # endif - for(int i = 0; i < num_hits_in_instance; i++) { - (isect_array-i-1)->t *= t_fac; + for(int i = 0; i < num_hits_in_instance; i++) { + (isect_array-i-1)->t *= t_fac; + } } # endif /* BVH_FEATURE(BVH_INSTANCING) */ return num_hits; diff --git a/intern/cycles/kernel/closure/bsdf.h b/intern/cycles/kernel/closure/bsdf.h index d8ff69ca2417..3a9629ea9d74 100644 --- a/intern/cycles/kernel/closure/bsdf.h +++ b/intern/cycles/kernel/closure/bsdf.h @@ -27,6 +27,7 @@ #include "kernel/closure/bsdf_ashikhmin_shirley.h" #include "kernel/closure/bsdf_toon.h" #include "kernel/closure/bsdf_hair.h" +#include "kernel/closure/bsdf_hair_principled.h" #include "kernel/closure/bsdf_principled_diffuse.h" #include "kernel/closure/bsdf_principled_sheen.h" #include "kernel/closure/bssrdf.h" @@ -72,15 +73,15 @@ ccl_device_inline float bsdf_get_roughness_squared(const ShaderClosure *sc) return bsdf_get_specular_roughness_squared(sc); } -ccl_device_forceinline int bsdf_sample(KernelGlobals *kg, - ShaderData *sd, - const ShaderClosure *sc, - float randu, - float randv, - float3 *eval, - float3 *omega_in, - differential3 *domega_in, - float *pdf) +ccl_device_inline int bsdf_sample(KernelGlobals *kg, + ShaderData *sd, + const ShaderClosure *sc, + float randu, + float randv, + float3 *eval, + float3 *omega_in, + differential3 *domega_in, + float *pdf) { int label; @@ -171,6 +172,10 @@ ccl_device_forceinline int bsdf_sample(KernelGlobals *kg, label = bsdf_hair_transmission_sample(sc, sd->Ng, sd->I, sd->dI.dx, sd->dI.dy, randu, randv, eval, omega_in, &domega_in->dx, &domega_in->dy, pdf); break; + case CLOSURE_BSDF_HAIR_PRINCIPLED_ID: + label = bsdf_principled_hair_sample(kg, sc, sd, randu, randv, + eval, omega_in, &domega_in->dx, &domega_in->dy, pdf); + break; #ifdef __PRINCIPLED__ case CLOSURE_BSDF_PRINCIPLED_DIFFUSE_ID: case CLOSURE_BSDF_BSSRDF_PRINCIPLED_ID: @@ -210,7 +215,7 @@ ccl_device_forceinline int bsdf_sample(KernelGlobals *kg, #ifndef __KERNEL_CUDA__ ccl_device #else -ccl_device_forceinline +ccl_device_inline #endif float3 bsdf_eval(KernelGlobals *kg, ShaderData *sd, @@ -284,6 +289,9 @@ float3 bsdf_eval(KernelGlobals *kg, case CLOSURE_BSDF_GLOSSY_TOON_ID: eval = bsdf_glossy_toon_eval_reflect(sc, sd->I, omega_in, pdf); break; + case CLOSURE_BSDF_HAIR_PRINCIPLED_ID: + eval = bsdf_principled_hair_eval(kg, sd, sc, omega_in, pdf); + break; case CLOSURE_BSDF_HAIR_REFLECTION_ID: eval = bsdf_hair_reflection_eval_reflect(sc, sd->I, omega_in, pdf); break; @@ -366,6 +374,9 @@ float3 bsdf_eval(KernelGlobals *kg, case CLOSURE_BSDF_GLOSSY_TOON_ID: eval = bsdf_glossy_toon_eval_transmit(sc, sd->I, omega_in, pdf); break; + case CLOSURE_BSDF_HAIR_PRINCIPLED_ID: + eval = bsdf_principled_hair_eval(kg, sd, sc, omega_in, pdf); + break; case CLOSURE_BSDF_HAIR_REFLECTION_ID: eval = bsdf_hair_reflection_eval_transmit(sc, sd->I, omega_in, pdf); break; @@ -424,6 +435,9 @@ ccl_device void bsdf_blur(KernelGlobals *kg, ShaderClosure *sc, float roughness) case CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ANISO_ID: bsdf_ashikhmin_shirley_blur(sc, roughness); break; + case CLOSURE_BSDF_HAIR_PRINCIPLED_ID: + bsdf_principled_hair_blur(sc, roughness); + break; default: break; } @@ -486,4 +500,3 @@ ccl_device bool bsdf_merge(ShaderClosure *a, ShaderClosure *b) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/closure/bsdf_ashikhmin_shirley.h b/intern/cycles/kernel/closure/bsdf_ashikhmin_shirley.h index b6c896c754ba..ff238b7a8349 100644 --- a/intern/cycles/kernel/closure/bsdf_ashikhmin_shirley.h +++ b/intern/cycles/kernel/closure/bsdf_ashikhmin_shirley.h @@ -117,7 +117,7 @@ ccl_device_forceinline float3 bsdf_ashikhmin_shirley_eval_reflect( lobe = 1.0f; } float norm = sqrtf((n_x + 1.0f)*(n_y + 1.0f)) / (8.0f * M_PI_F); - + out = NdotO * norm * lobe * pump; *pdf = norm * lobe / HdotI; } diff --git a/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h b/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h index a5ba2cb29725..b0bdea723b98 100644 --- a/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h +++ b/intern/cycles/kernel/closure/bsdf_ashikhmin_velvet.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -46,7 +46,7 @@ ccl_device int bsdf_ashikhmin_velvet_setup(VelvetBsdf *bsdf) { float sigma = fmaxf(bsdf->sigma, 0.01f); bsdf->invsigma2 = 1.0f/(sigma * sigma); - + bsdf->type = CLOSURE_BSDF_ASHIKHMIN_VELVET_ID; return SD_BSDF|SD_BSDF_HAS_EVAL; @@ -159,4 +159,3 @@ ccl_device int bsdf_ashikhmin_velvet_sample(const ShaderClosure *sc, float3 Ng, CCL_NAMESPACE_END #endif /* __BSDF_ASHIKHMIN_VELVET_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_diffuse.h b/intern/cycles/kernel/closure/bsdf_diffuse.h index ec6f1f209963..ee6d4cdf2df5 100644 --- a/intern/cycles/kernel/closure/bsdf_diffuse.h +++ b/intern/cycles/kernel/closure/bsdf_diffuse.h @@ -88,7 +88,7 @@ ccl_device int bsdf_diffuse_sample(const ShaderClosure *sc, float3 Ng, float3 I, } else *pdf = 0.0f; - + return LABEL_REFLECT|LABEL_DIFFUSE; } @@ -140,4 +140,3 @@ ccl_device int bsdf_translucent_sample(const ShaderClosure *sc, float3 Ng, float CCL_NAMESPACE_END #endif /* __BSDF_DIFFUSE_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_diffuse_ramp.h b/intern/cycles/kernel/closure/bsdf_diffuse_ramp.h index 24f40af46a3a..35bb2fdf0e8e 100644 --- a/intern/cycles/kernel/closure/bsdf_diffuse_ramp.h +++ b/intern/cycles/kernel/closure/bsdf_diffuse_ramp.h @@ -46,7 +46,7 @@ typedef ccl_addr_space struct DiffuseRampBsdf { ccl_device float3 bsdf_diffuse_ramp_get_color(const float3 colors[8], float pos) { int MAXCOLORS = 8; - + float npos = pos * (float)(MAXCOLORS - 1); int ipos = float_to_int(npos); if(ipos < 0) @@ -99,7 +99,7 @@ ccl_device int bsdf_diffuse_ramp_sample(const ShaderClosure *sc, float3 Ng, floa } else *pdf = 0.0f; - + return LABEL_REFLECT|LABEL_DIFFUSE; } diff --git a/intern/cycles/kernel/closure/bsdf_hair.h b/intern/cycles/kernel/closure/bsdf_hair.h index daaa26dc6ade..7b44a23f05bc 100644 --- a/intern/cycles/kernel/closure/bsdf_hair.h +++ b/intern/cycles/kernel/closure/bsdf_hair.h @@ -278,4 +278,3 @@ ccl_device int bsdf_hair_transmission_sample(const ShaderClosure *sc, float3 Ng, CCL_NAMESPACE_END #endif /* __BSDF_HAIR_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_hair_principled.h b/intern/cycles/kernel/closure/bsdf_hair_principled.h new file mode 100644 index 000000000000..b3b56be39ff3 --- /dev/null +++ b/intern/cycles/kernel/closure/bsdf_hair_principled.h @@ -0,0 +1,502 @@ +/* + * Copyright 2018 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef __KERNEL_CPU__ +#include +#endif + +#include "kernel/kernel_color.h" + +#ifndef __BSDF_HAIR_PRINCIPLED_H__ +#define __BSDF_HAIR_PRINCIPLED_H__ + +CCL_NAMESPACE_BEGIN + +typedef ccl_addr_space struct PrincipledHairExtra { + /* Geometry data. */ + float4 geom; +} PrincipledHairExtra; + +typedef ccl_addr_space struct PrincipledHairBSDF { + SHADER_CLOSURE_BASE; + + /* Absorption coefficient. */ + float3 sigma; + /* Variance of the underlying logistic distribution. */ + float v; + /* Scale factor of the underlying logistic distribution. */ + float s; + /* Cuticle tilt angle. */ + float alpha; + /* IOR. */ + float eta; + /* Effective variance for the diffuse bounce only. */ + float m0_roughness; + + /* Extra closure. */ + PrincipledHairExtra *extra; +} PrincipledHairBSDF; + +static_assert(sizeof(ShaderClosure) >= sizeof(PrincipledHairBSDF), "PrincipledHairBSDF is too large!"); +static_assert(sizeof(ShaderClosure) >= sizeof(PrincipledHairExtra), "PrincipledHairExtra is too large!"); + +ccl_device_inline float cos_from_sin(const float s) +{ + return safe_sqrtf(1.0f - s*s); +} + +/* Gives the change in direction in the normal plane for the given angles and p-th-order scattering. */ +ccl_device_inline float delta_phi(int p, float gamma_o, float gamma_t) +{ + return 2.0f * p * gamma_t - 2.0f * gamma_o + p * M_PI_F; +} + +/* Remaps the given angle to [-pi, pi]. */ +ccl_device_inline float wrap_angle(float a) +{ + while(a > M_PI_F) { + a -= M_2PI_F; + } + while(a < -M_PI_F) { + a += M_2PI_F; + } + return a; +} + +/* Logistic distribution function. */ +ccl_device_inline float logistic(float x, float s) +{ + float v = expf(-fabsf(x)/s); + return v / (s * sqr(1.0f + v)); +} + +/* Logistic cumulative density function. */ +ccl_device_inline float logistic_cdf(float x, float s) +{ + float arg = -x/s; + /* expf() overflows if arg >= 89.0. */ + if(arg > 88.0f) { + return 0.0f; + } + else { + return 1.0f / (1.0f + expf(arg)); + } +} + +/* Numerical approximation to the Bessel function of the first kind. */ +ccl_device_inline float bessel_I0(float x) +{ + x = sqr(x); + float val = 1.0f + 0.25f*x; + float pow_x_2i = sqr(x); + uint64_t i_fac_2 = 1; + int pow_4_i = 16; + for(int i = 2; i < 10; i++) { + i_fac_2 *= i*i; + float newval = val + pow_x_2i / (pow_4_i * i_fac_2); + if(val == newval) { + return val; + } + val = newval; + pow_x_2i *= x; + pow_4_i *= 4; + } + return val; +} + +/* Logarithm of the Bessel function of the first kind. */ +ccl_device_inline float log_bessel_I0(float x) +{ + if(x > 12.0f) { + /* log(1/x) == -log(x) iff x > 0. + * This is only used with positive cosines */ + return x + 0.5f * (1.f / (8.0f * x) - M_LN_2PI_F - logf(x)); + } + else { + return logf(bessel_I0(x)); + } +} + +/* Logistic distribution limited to the interval [-pi, pi]. */ +ccl_device_inline float trimmed_logistic(float x, float s) +{ + /* The logistic distribution is symmetric and centered around zero, + * so logistic_cdf(x, s) = 1 - logistic_cdf(-x, s). + * Therefore, logistic_cdf(x, s)-logistic_cdf(-x, s) = 1 - 2*logistic_cdf(-x, s) */ + float scaling_fac = 1.0f - 2.0f*logistic_cdf(-M_PI_F, s); + float val = logistic(x, s); + return safe_divide(val, scaling_fac); +} + +/* Sampling function for the trimmed logistic function. */ +ccl_device_inline float sample_trimmed_logistic(float u, float s) +{ + float cdf_minuspi = logistic_cdf(-M_PI_F, s); + float x = -s*logf(1.0f / (u*(1.0f - 2.0f*cdf_minuspi) + cdf_minuspi) - 1.0f); + return clamp(x, -M_PI_F, M_PI_F); +} + +/* Azimuthal scattering function Np. */ +ccl_device_inline float azimuthal_scattering(float phi, + int p, + float s, + float gamma_o, + float gamma_t) +{ + float phi_o = wrap_angle(phi - delta_phi(p, gamma_o, gamma_t)); + float val = trimmed_logistic(phi_o, s); + return val; +} + +/* Longitudinal scattering function Mp. */ +ccl_device_inline float longitudinal_scattering(float sin_theta_i, + float cos_theta_i, + float sin_theta_o, + float cos_theta_o, + float v) +{ + float inv_v = 1.0f/v; + float cos_arg = cos_theta_i * cos_theta_o * inv_v; + float sin_arg = sin_theta_i * sin_theta_o * inv_v; + if(v <= 0.1f) { + float i0 = log_bessel_I0(cos_arg); + float val = expf(i0 - sin_arg - inv_v + 0.6931f + logf(0.5f*inv_v)); + return val; + } + else { + float i0 = bessel_I0(cos_arg); + float val = (expf(-sin_arg) * i0) / (sinhf(inv_v) * 2.0f * v); + return val; + } +} + +/* Combine the three values using their luminances. */ +ccl_device_inline float4 combine_with_energy(KernelGlobals *kg, float3 c) +{ + return make_float4(c.x, c.y, c.z, linear_rgb_to_gray(kg, c)); +} + +#ifdef __HAIR__ +/* Set up the hair closure. */ +ccl_device int bsdf_principled_hair_setup(ShaderData *sd, PrincipledHairBSDF *bsdf) +{ + bsdf->type = CLOSURE_BSDF_HAIR_PRINCIPLED_ID; + bsdf->v = clamp(bsdf->v, 0.001f, 1.0f); + bsdf->s = clamp(bsdf->s, 0.001f, 1.0f); + /* Apply Primary Reflection Roughness modifier. */ + bsdf->m0_roughness = clamp(bsdf->m0_roughness*bsdf->v, 0.001f, 1.0f); + + /* Map from roughness_u and roughness_v to variance and scale factor. */ + bsdf->v = sqr(0.726f*bsdf->v + 0.812f*sqr(bsdf->v) + 3.700f*pow20(bsdf->v)); + bsdf->s = (0.265f*bsdf->s + 1.194f*sqr(bsdf->s) + 5.372f*pow22(bsdf->s))*M_SQRT_PI_8_F; + bsdf->m0_roughness = sqr(0.726f*bsdf->m0_roughness + 0.812f*sqr(bsdf->m0_roughness) + 3.700f*pow20(bsdf->m0_roughness)); + + /* Compute local frame, aligned to curve tangent and ray direction. */ + float3 X = safe_normalize(sd->dPdu); + float3 Y = safe_normalize(cross(X, sd->I)); + float3 Z = safe_normalize(cross(X, Y)); + /* TODO: the solution below works where sd->Ng is the normal + * pointing from the center of the curve to the shading point. + * It doesn't work for triangles, see https://developer.blender.org/T43625 */ + + /* h -1..0..1 means the rays goes from grazing the hair, to hitting it at + * the center, to grazing the other edge. This is the sine of the angle + * between sd->Ng and Z, as seen from the tangent X. */ + + /* TODO: we convert this value to a cosine later and discard the sign, so + * we could probably save some operations. */ + float h = dot(cross(sd->Ng, X), Z); + + kernel_assert(fabsf(h) < 1.0f + 1e-4f); + kernel_assert(isfinite3_safe(Y)); + kernel_assert(isfinite_safe(h)); + + bsdf->extra->geom = make_float4(Y.x, Y.y, Y.z, h); + + return SD_BSDF|SD_BSDF_HAS_EVAL|SD_BSDF_NEEDS_LCG; +} + +#endif /* __HAIR__ */ + +/* Given the Fresnel term and transmittance, generate the attenuation terms for each bounce. */ +ccl_device_inline void hair_attenuation(KernelGlobals *kg, + float f, + float3 T, + float4 *Ap) +{ + /* Primary specular (R). */ + Ap[0] = make_float4(f, f, f, f); + + /* Transmission (TT). */ + float3 col = sqr(1.0f - f) * T; + Ap[1] = combine_with_energy(kg, col); + + /* Secondary specular (TRT). */ + col *= T*f; + Ap[2] = combine_with_energy(kg, col); + + /* Residual component (TRRT+). */ + col *= safe_divide_color(T*f, make_float3(1.0f, 1.0f, 1.0f) - T*f); + Ap[3] = combine_with_energy(kg, col); + + /* Normalize sampling weights. */ + float totweight = Ap[0].w + Ap[1].w + Ap[2].w + Ap[3].w; + float fac = safe_divide(1.0f, totweight); + + Ap[0].w *= fac; + Ap[1].w *= fac; + Ap[2].w *= fac; + Ap[3].w *= fac; +} + +/* Given the tilt angle, generate the rotated theta_i for the different bounces. */ +ccl_device_inline void hair_alpha_angles(float sin_theta_i, + float cos_theta_i, + float alpha, + float *angles) +{ + float sin_1alpha = sinf(alpha); + float cos_1alpha = cos_from_sin(sin_1alpha); + float sin_2alpha = 2.0f*sin_1alpha*cos_1alpha; + float cos_2alpha = sqr(cos_1alpha) - sqr(sin_1alpha); + float sin_4alpha = 2.0f*sin_2alpha*cos_2alpha; + float cos_4alpha = sqr(cos_2alpha) - sqr(sin_2alpha); + + angles[0] = sin_theta_i*cos_2alpha + cos_theta_i*sin_2alpha; + angles[1] = fabsf(cos_theta_i*cos_2alpha - sin_theta_i*sin_2alpha); + angles[2] = sin_theta_i*cos_1alpha - cos_theta_i*sin_1alpha; + angles[3] = fabsf(cos_theta_i*cos_1alpha + sin_theta_i*sin_1alpha); + angles[4] = sin_theta_i*cos_4alpha - cos_theta_i*sin_4alpha; + angles[5] = fabsf(cos_theta_i*cos_4alpha + sin_theta_i*sin_4alpha); +} + +/* Evaluation function for our shader. */ +ccl_device float3 bsdf_principled_hair_eval(KernelGlobals *kg, + const ShaderData *sd, + const ShaderClosure *sc, + const float3 omega_in, + float *pdf) +{ + kernel_assert(isfinite3_safe(sd->P) && isfinite_safe(sd->ray_length)); + + const PrincipledHairBSDF *bsdf = (const PrincipledHairBSDF*) sc; + float3 Y = float4_to_float3(bsdf->extra->geom); + + float3 X = safe_normalize(sd->dPdu); + kernel_assert(fabsf(dot(X, Y)) < 1e-4f); + float3 Z = safe_normalize(cross(X, Y)); + + float3 wo = make_float3(dot(sd->I, X), dot(sd->I, Y), dot(sd->I, Z)); + float3 wi = make_float3(dot(omega_in, X), dot(omega_in, Y), dot(omega_in, Z)); + + float sin_theta_o = wo.x; + float cos_theta_o = cos_from_sin(sin_theta_o); + float phi_o = atan2f(wo.z, wo.y); + + float sin_theta_t = sin_theta_o / bsdf->eta; + float cos_theta_t = cos_from_sin(sin_theta_t); + + float sin_gamma_o = bsdf->extra->geom.w; + float cos_gamma_o = cos_from_sin(sin_gamma_o); + float gamma_o = safe_asinf(sin_gamma_o); + + float sin_gamma_t = sin_gamma_o * cos_theta_o / sqrtf(sqr(bsdf->eta) - sqr(sin_theta_o)); + float cos_gamma_t = cos_from_sin(sin_gamma_t); + float gamma_t = safe_asinf(sin_gamma_t); + + float3 T = exp3(-bsdf->sigma * (2.0f * cos_gamma_t / cos_theta_t)); + float4 Ap[4]; + hair_attenuation(kg, fresnel_dielectric_cos(cos_theta_o * cos_gamma_o, bsdf->eta), T, Ap); + + float sin_theta_i = wi.x; + float cos_theta_i = cos_from_sin(sin_theta_i); + float phi_i = atan2f(wi.z, wi.y); + + float phi = phi_i - phi_o; + + float angles[6]; + hair_alpha_angles(sin_theta_i, cos_theta_i, bsdf->alpha, angles); + + float4 F; + float Mp, Np; + + /* Primary specular (R). */ + Mp = longitudinal_scattering(angles[0], angles[1], sin_theta_o, cos_theta_o, bsdf->m0_roughness); + Np = azimuthal_scattering(phi, 0, bsdf->s, gamma_o, gamma_t); + F = Ap[0] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Transmission (TT). */ + Mp = longitudinal_scattering(angles[2], angles[3], sin_theta_o, cos_theta_o, 0.25f*bsdf->v); + Np = azimuthal_scattering(phi, 1, bsdf->s, gamma_o, gamma_t); + F += Ap[1] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Secondary specular (TRT). */ + Mp = longitudinal_scattering(angles[4], angles[5], sin_theta_o, cos_theta_o, 4.0f*bsdf->v); + Np = azimuthal_scattering(phi, 2, bsdf->s, gamma_o, gamma_t); + F += Ap[2] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Residual component (TRRT+). */ + Mp = longitudinal_scattering(sin_theta_i, cos_theta_i, sin_theta_o, cos_theta_o, 4.0f*bsdf->v); + Np = M_1_2PI_F; + F += Ap[3] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + *pdf = F.w; + return float4_to_float3(F); +} + +/* Sampling function for the hair shader. */ +ccl_device int bsdf_principled_hair_sample(KernelGlobals *kg, + const ShaderClosure *sc, + ShaderData *sd, + float randu, + float randv, + float3 *eval, + float3 *omega_in, + float3 *domega_in_dx, + float3 *domega_in_dy, + float *pdf) +{ + PrincipledHairBSDF *bsdf = (PrincipledHairBSDF*) sc; + + float3 Y = float4_to_float3(bsdf->extra->geom); + + float3 X = safe_normalize(sd->dPdu); + kernel_assert(fabsf(dot(X, Y)) < 1e-4f); + float3 Z = safe_normalize(cross(X, Y)); + + float3 wo = make_float3(dot(sd->I, X), dot(sd->I, Y), dot(sd->I, Z)); + + float2 u[2]; + u[0] = make_float2(randu, randv); + u[1].x = lcg_step_float_addrspace(&sd->lcg_state); + u[1].y = lcg_step_float_addrspace(&sd->lcg_state); + + float sin_theta_o = wo.x; + float cos_theta_o = cos_from_sin(sin_theta_o); + float phi_o = atan2f(wo.z, wo.y); + + float sin_theta_t = sin_theta_o / bsdf->eta; + float cos_theta_t = cos_from_sin(sin_theta_t); + + float sin_gamma_o = bsdf->extra->geom.w; + float cos_gamma_o = cos_from_sin(sin_gamma_o); + float gamma_o = safe_asinf(sin_gamma_o); + + float sin_gamma_t = sin_gamma_o * cos_theta_o / sqrtf(sqr(bsdf->eta) - sqr(sin_theta_o)); + float cos_gamma_t = cos_from_sin(sin_gamma_t); + float gamma_t = safe_asinf(sin_gamma_t); + + float3 T = exp3(-bsdf->sigma * (2.0f * cos_gamma_t / cos_theta_t)); + float4 Ap[4]; + hair_attenuation(kg, fresnel_dielectric_cos(cos_theta_o * cos_gamma_o, bsdf->eta), T, Ap); + + int p = 0; + for(; p < 3; p++) { + if(u[0].x < Ap[p].w) { + break; + } + u[0].x -= Ap[p].w; + } + + float v = bsdf->v; + if(p == 1) { + v *= 0.25f; + } + if(p >= 2) { + v *= 4.0f; + } + + u[1].x = max(u[1].x, 1e-5f); + float fac = 1.0f + v*logf(u[1].x + (1.0f - u[1].x)*expf(-2.0f/v)); + float sin_theta_i = -fac * sin_theta_o + cos_from_sin(fac) * cosf(M_2PI_F * u[1].y) * cos_theta_o; + float cos_theta_i = cos_from_sin(sin_theta_i); + + float angles[6]; + if(p < 3) { + hair_alpha_angles(sin_theta_i, cos_theta_i, -bsdf->alpha, angles); + sin_theta_i = angles[2*p]; + cos_theta_i = angles[2*p+1]; + } + + float phi; + if(p < 3) { + phi = delta_phi(p, gamma_o, gamma_t) + sample_trimmed_logistic(u[0].y, bsdf->s); + } + else { + phi = M_2PI_F*u[0].y; + } + float phi_i = phi_o + phi; + + hair_alpha_angles(sin_theta_i, cos_theta_i, bsdf->alpha, angles); + + float4 F; + float Mp, Np; + + /* Primary specular (R). */ + Mp = longitudinal_scattering(angles[0], angles[1], sin_theta_o, cos_theta_o, bsdf->m0_roughness); + Np = azimuthal_scattering(phi, 0, bsdf->s, gamma_o, gamma_t); + F = Ap[0] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Transmission (TT). */ + Mp = longitudinal_scattering(angles[2], angles[3], sin_theta_o, cos_theta_o, 0.25f*bsdf->v); + Np = azimuthal_scattering(phi, 1, bsdf->s, gamma_o, gamma_t); + F += Ap[1] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Secondary specular (TRT). */ + Mp = longitudinal_scattering(angles[4], angles[5], sin_theta_o, cos_theta_o, 4.0f*bsdf->v); + Np = azimuthal_scattering(phi, 2, bsdf->s, gamma_o, gamma_t); + F += Ap[2] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + /* Residual component (TRRT+). */ + Mp = longitudinal_scattering(sin_theta_i, cos_theta_i, sin_theta_o, cos_theta_o, 4.0f*bsdf->v); + Np = M_1_2PI_F; + F += Ap[3] * Mp * Np; + kernel_assert(isfinite3_safe(float4_to_float3(F))); + + *eval = float4_to_float3(F); + *pdf = F.w; + + *omega_in = X*sin_theta_i + Y*cos_theta_i*cosf(phi_i) + Z*cos_theta_i*sinf(phi_i); + +#ifdef __RAY_DIFFERENTIALS__ + float3 N = safe_normalize(sd->I + *omega_in); + *domega_in_dx = (2 * dot(N, sd->dI.dx)) * N - sd->dI.dx; + *domega_in_dy = (2 * dot(N, sd->dI.dy)) * N - sd->dI.dy; +#endif + + return LABEL_GLOSSY|((p == 0)? LABEL_REFLECT : LABEL_TRANSMIT); +} + +/* Implements Filter Glossy by capping the effective roughness. */ +ccl_device void bsdf_principled_hair_blur(ShaderClosure *sc, float roughness) +{ + PrincipledHairBSDF *bsdf = (PrincipledHairBSDF*)sc; + + bsdf->v = fmaxf(roughness, bsdf->v); + bsdf->s = fmaxf(roughness, bsdf->s); + bsdf->m0_roughness = fmaxf(roughness, bsdf->m0_roughness); +} + +CCL_NAMESPACE_END + +#endif /* __BSDF_HAIR_PRINCIPLED_H__ */ diff --git a/intern/cycles/kernel/closure/bsdf_microfacet.h b/intern/cycles/kernel/closure/bsdf_microfacet.h index 2dd59354058c..e74d5ebaa426 100644 --- a/intern/cycles/kernel/closure/bsdf_microfacet.h +++ b/intern/cycles/kernel/closure/bsdf_microfacet.h @@ -231,7 +231,7 @@ ccl_device_forceinline float3 microfacet_sample_stretched( /* 5. compute normal */ return normalize(make_float3(-slope_x, -slope_y, 1.0f)); -} +} /* Calculate the reflection color * @@ -434,7 +434,7 @@ ccl_device float3 bsdf_microfacet_ggx_eval_reflect(const ShaderClosure *sc, cons /* eq. 34: now calculate G1(i,m) and G1(o,m) */ G1o = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO))); - G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); + G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); } else { /* anisotropic */ @@ -535,7 +535,7 @@ ccl_device float3 bsdf_microfacet_ggx_eval_transmit(const ShaderClosure *sc, con /* eq. 34: now calculate G1(i,m) and G1(o,m) */ G1o = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNO * cosNO) / (cosNO * cosNO))); - G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); + G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); float G = G1o * G1i; @@ -706,7 +706,7 @@ ccl_device int bsdf_microfacet_ggx_sample(KernelGlobals *kg, const ShaderClosure dIdx, dIdy, &dRdx, &dRdy, &dTdx, &dTdy, #endif &inside); - + if(!inside && fresnel != 1.0f) { *omega_in = T; @@ -733,7 +733,7 @@ ccl_device int bsdf_microfacet_ggx_sample(KernelGlobals *kg, const ShaderClosure float cosNI = dot(N, *omega_in); /* eq. 34: now calculate G1(i,m) */ - float G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); + float G1i = 2 / (1 + safe_sqrtf(1 + alpha2 * (1 - cosNI * cosNI) / (cosNI * cosNI))); /* eq. 21 */ float cosHI = dot(m, *omega_in); @@ -1125,4 +1125,3 @@ ccl_device int bsdf_microfacet_beckmann_sample(KernelGlobals *kg, const ShaderCl CCL_NAMESPACE_END #endif /* __BSDF_MICROFACET_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_phong_ramp.h b/intern/cycles/kernel/closure/bsdf_phong_ramp.h index 420f94755eea..91c7803346d4 100644 --- a/intern/cycles/kernel/closure/bsdf_phong_ramp.h +++ b/intern/cycles/kernel/closure/bsdf_phong_ramp.h @@ -47,7 +47,7 @@ typedef ccl_addr_space struct PhongRampBsdf { ccl_device float3 bsdf_phong_ramp_get_color(const float3 colors[8], float pos) { int MAXCOLORS = 8; - + float npos = pos * (float)(MAXCOLORS - 1); int ipos = float_to_int(npos); if(ipos < 0) @@ -71,7 +71,7 @@ ccl_device float3 bsdf_phong_ramp_eval_reflect(const ShaderClosure *sc, const fl float m_exponent = bsdf->exponent; float cosNI = dot(bsdf->N, omega_in); float cosNO = dot(bsdf->N, I); - + if(cosNI > 0 && cosNO > 0) { // reflect the view vector float3 R = (2 * cosNO) * bsdf->N - I; @@ -84,7 +84,7 @@ ccl_device float3 bsdf_phong_ramp_eval_reflect(const ShaderClosure *sc, const fl return bsdf_phong_ramp_get_color(bsdf->colors, cosp) * out; } } - + return make_float3(0.0f, 0.0f, 0.0f); } @@ -98,7 +98,7 @@ ccl_device int bsdf_phong_ramp_sample(const ShaderClosure *sc, float3 Ng, float3 const PhongRampBsdf *bsdf = (const PhongRampBsdf*)sc; float cosNO = dot(bsdf->N, I); float m_exponent = bsdf->exponent; - + if(cosNO > 0) { // reflect the view vector float3 R = (2 * cosNO) * bsdf->N - I; @@ -107,7 +107,7 @@ ccl_device int bsdf_phong_ramp_sample(const ShaderClosure *sc, float3 Ng, float3 *domega_in_dx = (2 * dot(bsdf->N, dIdx)) * bsdf->N - dIdx; *domega_in_dy = (2 * dot(bsdf->N, dIdy)) * bsdf->N - dIdy; #endif - + float3 T, B; make_orthonormals (R, &T, &B); float phi = M_2PI_F * randu; diff --git a/intern/cycles/kernel/closure/bsdf_principled_diffuse.h b/intern/cycles/kernel/closure/bsdf_principled_diffuse.h index f8ca64293b06..83be2b35a003 100644 --- a/intern/cycles/kernel/closure/bsdf_principled_diffuse.h +++ b/intern/cycles/kernel/closure/bsdf_principled_diffuse.h @@ -123,5 +123,3 @@ ccl_device int bsdf_principled_diffuse_sample(const ShaderClosure *sc, CCL_NAMESPACE_END #endif /* __BSDF_PRINCIPLED_DIFFUSE_H__ */ - - diff --git a/intern/cycles/kernel/closure/bsdf_principled_sheen.h b/intern/cycles/kernel/closure/bsdf_principled_sheen.h index f4476bfecd07..8b7c43995160 100644 --- a/intern/cycles/kernel/closure/bsdf_principled_sheen.h +++ b/intern/cycles/kernel/closure/bsdf_principled_sheen.h @@ -109,5 +109,3 @@ ccl_device int bsdf_principled_sheen_sample(const ShaderClosure *sc, CCL_NAMESPACE_END #endif /* __BSDF_PRINCIPLED_SHEEN_H__ */ - - diff --git a/intern/cycles/kernel/closure/bsdf_reflection.h b/intern/cycles/kernel/closure/bsdf_reflection.h index 1d21614eceef..b33b6e3597b0 100644 --- a/intern/cycles/kernel/closure/bsdf_reflection.h +++ b/intern/cycles/kernel/closure/bsdf_reflection.h @@ -78,4 +78,3 @@ ccl_device int bsdf_reflection_sample(const ShaderClosure *sc, float3 Ng, float3 CCL_NAMESPACE_END #endif /* __BSDF_REFLECTION_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_refraction.h b/intern/cycles/kernel/closure/bsdf_refraction.h index 050a4e76fa9b..b181650e9289 100644 --- a/intern/cycles/kernel/closure/bsdf_refraction.h +++ b/intern/cycles/kernel/closure/bsdf_refraction.h @@ -87,4 +87,3 @@ ccl_device int bsdf_refraction_sample(const ShaderClosure *sc, float3 Ng, float3 CCL_NAMESPACE_END #endif /* __BSDF_REFRACTION_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_toon.h b/intern/cycles/kernel/closure/bsdf_toon.h index d8b6d8ddead1..6d8074b71307 100644 --- a/intern/cycles/kernel/closure/bsdf_toon.h +++ b/intern/cycles/kernel/closure/bsdf_toon.h @@ -73,7 +73,7 @@ ccl_device float3 bsdf_toon_get_intensity(float max_angle, float smooth, float a is = (1.0f - (angle - max_angle)/smooth); else is = 0.0f; - + return make_float3(is, is, is); } @@ -90,7 +90,7 @@ ccl_device float3 bsdf_diffuse_toon_eval_reflect(const ShaderClosure *sc, const float angle = safe_acosf(fmaxf(dot(bsdf->N, omega_in), 0.0f)); float3 eval = bsdf_toon_get_intensity(max_angle, smooth, angle); - + if(eval.x > 0.0f) { float sample_angle = bsdf_toon_get_sample_angle(max_angle, smooth); @@ -152,7 +152,7 @@ ccl_device float3 bsdf_glossy_toon_eval_reflect(const ShaderClosure *sc, const f float smooth = bsdf->smooth*M_PI_2_F; float cosNI = dot(bsdf->N, omega_in); float cosNO = dot(bsdf->N, I); - + if(cosNI > 0 && cosNO > 0) { /* reflect the view vector */ float3 R = (2 * cosNO) * bsdf->N - I; @@ -166,7 +166,7 @@ ccl_device float3 bsdf_glossy_toon_eval_reflect(const ShaderClosure *sc, const f *pdf = 0.5f * M_1_PI_F / (1.0f - cosf(sample_angle)); return *pdf * eval; } - + return make_float3(0.0f, 0.0f, 0.0f); } @@ -181,7 +181,7 @@ ccl_device int bsdf_glossy_toon_sample(const ShaderClosure *sc, float3 Ng, float float max_angle = bsdf->size*M_PI_2_F; float smooth = bsdf->smooth*M_PI_2_F; float cosNO = dot(bsdf->N, I); - + if(cosNO > 0) { /* reflect the view vector */ float3 R = (2 * cosNO) * bsdf->N - I; @@ -216,4 +216,3 @@ ccl_device int bsdf_glossy_toon_sample(const ShaderClosure *sc, float3 Ng, float CCL_NAMESPACE_END #endif /* __BSDF_TOON_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_transparent.h b/intern/cycles/kernel/closure/bsdf_transparent.h index 8fc7ef4dd4fc..f788dbcd0ff1 100644 --- a/intern/cycles/kernel/closure/bsdf_transparent.h +++ b/intern/cycles/kernel/closure/bsdf_transparent.h @@ -107,4 +107,3 @@ ccl_device int bsdf_transparent_sample(const ShaderClosure *sc, float3 Ng, float CCL_NAMESPACE_END #endif /* __BSDF_TRANSPARENT_H__ */ - diff --git a/intern/cycles/kernel/closure/bsdf_util.h b/intern/cycles/kernel/closure/bsdf_util.h index 3dc15d5791cb..b080e025d166 100644 --- a/intern/cycles/kernel/closure/bsdf_util.h +++ b/intern/cycles/kernel/closure/bsdf_util.h @@ -62,14 +62,14 @@ ccl_device float fresnel_dielectric( Nn = -N; *is_inside = true; } - + // compute reflection *R = (2 * cos)* Nn - I; #ifdef __RAY_DIFFERENTIALS__ *dRdx = (2 * dot(Nn, dIdx)) * Nn - dIdx; *dRdy = (2 * dot(Nn, dIdy)) * Nn - dIdy; #endif - + float arg = 1 -(neta * neta *(1 -(cos * cos))); if(arg < 0) { *T = make_float3(0.0f, 0.0f, 0.0f); @@ -159,4 +159,3 @@ ccl_device_forceinline float3 interpolate_fresnel_color(float3 L, float3 H, floa CCL_NAMESPACE_END #endif /* __BSDF_UTIL_H__ */ - diff --git a/intern/cycles/kernel/closure/bssrdf.h b/intern/cycles/kernel/closure/bssrdf.h index 8578767b07ee..ba0c6ae8c616 100644 --- a/intern/cycles/kernel/closure/bssrdf.h +++ b/intern/cycles/kernel/closure/bssrdf.h @@ -500,4 +500,3 @@ ccl_device_forceinline float bssrdf_pdf(const ShaderClosure *sc, float r) CCL_NAMESPACE_END #endif /* __KERNEL_BSSRDF_H__ */ - diff --git a/intern/cycles/kernel/closure/emissive.h b/intern/cycles/kernel/closure/emissive.h index e709ca9a3724..a7f4a2a7327b 100644 --- a/intern/cycles/kernel/closure/emissive.h +++ b/intern/cycles/kernel/closure/emissive.h @@ -76,9 +76,8 @@ ccl_device void emissive_sample(const float3 Ng, float randu, float randv, ccl_device float3 emissive_simple_eval(const float3 Ng, const float3 I) { float res = emissive_pdf(Ng, I); - + return make_float3(res, res, res); } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/closure/volume.h b/intern/cycles/kernel/closure/volume.h index da791e9aa734..872d06c936a5 100644 --- a/intern/cycles/kernel/closure/volume.h +++ b/intern/cycles/kernel/closure/volume.h @@ -51,7 +51,7 @@ ccl_device float single_peaked_henyey_greenstein(float cos_theta, float g) ccl_device int volume_henyey_greenstein_setup(HenyeyGreensteinVolume *volume) { volume->type = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID; - + /* clamp anisotropy to avoid delta function */ volume->g = signf(volume->g) * min(fabsf(volume->g), 1.0f - 1e-3f); diff --git a/intern/cycles/kernel/filter/filter_defines.h b/intern/cycles/kernel/filter/filter_defines.h index ce96f733afff..1a2f22a69870 100644 --- a/intern/cycles/kernel/filter/filter_defines.h +++ b/intern/cycles/kernel/filter/filter_defines.h @@ -22,7 +22,7 @@ #define XTWX_SIZE (((DENOISE_FEATURES+1)*(DENOISE_FEATURES+2))/2) #define XTWY_SIZE (DENOISE_FEATURES+1) -typedef struct TilesInfo { +typedef struct TileInfo { int offsets[9]; int strides[9]; int x[4]; @@ -33,6 +33,39 @@ typedef struct TilesInfo { #else long long int buffers[9]; #endif -} TilesInfo; +} TileInfo; + +#ifdef __KERNEL_OPENCL__ +# define CCL_FILTER_TILE_INFO ccl_global TileInfo* tile_info, \ + ccl_global float *tile_buffer_1, \ + ccl_global float *tile_buffer_2, \ + ccl_global float *tile_buffer_3, \ + ccl_global float *tile_buffer_4, \ + ccl_global float *tile_buffer_5, \ + ccl_global float *tile_buffer_6, \ + ccl_global float *tile_buffer_7, \ + ccl_global float *tile_buffer_8, \ + ccl_global float *tile_buffer_9 +# define CCL_FILTER_TILE_INFO_ARG tile_info, \ + tile_buffer_1, tile_buffer_2, tile_buffer_3, \ + tile_buffer_4, tile_buffer_5, tile_buffer_6, \ + tile_buffer_7, tile_buffer_8, tile_buffer_9 +# define ccl_get_tile_buffer(id) (id == 0 ? tile_buffer_1 \ + : id == 1 ? tile_buffer_2 \ + : id == 2 ? tile_buffer_3 \ + : id == 3 ? tile_buffer_4 \ + : id == 4 ? tile_buffer_5 \ + : id == 5 ? tile_buffer_6 \ + : id == 6 ? tile_buffer_7 \ + : id == 7 ? tile_buffer_8 \ + : tile_buffer_9) +#else +# ifdef __KERNEL_CUDA__ +# define CCL_FILTER_TILE_INFO ccl_global TileInfo* tile_info +# else +# define CCL_FILTER_TILE_INFO TileInfo* tile_info +# endif +# define ccl_get_tile_buffer(id) (tile_info->buffers[id]) +#endif #endif /* __FILTER_DEFINES_H__*/ diff --git a/intern/cycles/kernel/filter/filter_prefilter.h b/intern/cycles/kernel/filter/filter_prefilter.h index 4af209341f6b..3507f80df465 100644 --- a/intern/cycles/kernel/filter/filter_prefilter.h +++ b/intern/cycles/kernel/filter/filter_prefilter.h @@ -26,7 +26,7 @@ CCL_NAMESPACE_BEGIN * bufferVariance: The buffer-based variance of the shadow feature. Unbiased, but quite noisy. */ ccl_device void kernel_filter_divide_shadow(int sample, - ccl_global TilesInfo *tiles, + CCL_FILTER_TILE_INFO, int x, int y, ccl_global float *unfilteredA, ccl_global float *unfilteredB, @@ -37,13 +37,13 @@ ccl_device void kernel_filter_divide_shadow(int sample, int buffer_pass_stride, int buffer_denoising_offset) { - int xtile = (x < tiles->x[1])? 0: ((x < tiles->x[2])? 1: 2); - int ytile = (y < tiles->y[1])? 0: ((y < tiles->y[2])? 1: 2); + int xtile = (x < tile_info->x[1])? 0: ((x < tile_info->x[2])? 1: 2); + int ytile = (y < tile_info->y[1])? 0: ((y < tile_info->y[2])? 1: 2); int tile = ytile*3+xtile; - int offset = tiles->offsets[tile]; - int stride = tiles->strides[tile]; - const ccl_global float *ccl_restrict center_buffer = (ccl_global float*) tiles->buffers[tile]; + int offset = tile_info->offsets[tile]; + int stride = tile_info->strides[tile]; + const ccl_global float *ccl_restrict center_buffer = (ccl_global float*) ccl_get_tile_buffer(tile); center_buffer += (y*stride + x + offset)*buffer_pass_stride; center_buffer += buffer_denoising_offset + 14; @@ -79,7 +79,7 @@ ccl_device void kernel_filter_divide_shadow(int sample, * - rect: The prefilter area (lower pixels inclusive, upper pixels exclusive). */ ccl_device void kernel_filter_get_feature(int sample, - ccl_global TilesInfo *tiles, + CCL_FILTER_TILE_INFO, int m_offset, int v_offset, int x, int y, ccl_global float *mean, @@ -87,10 +87,10 @@ ccl_device void kernel_filter_get_feature(int sample, int4 rect, int buffer_pass_stride, int buffer_denoising_offset) { - int xtile = (x < tiles->x[1])? 0: ((x < tiles->x[2])? 1: 2); - int ytile = (y < tiles->y[1])? 0: ((y < tiles->y[2])? 1: 2); + int xtile = (x < tile_info->x[1])? 0: ((x < tile_info->x[2])? 1: 2); + int ytile = (y < tile_info->y[1])? 0: ((y < tile_info->y[2])? 1: 2); int tile = ytile*3+xtile; - ccl_global float *center_buffer = ((ccl_global float*) tiles->buffers[tile]) + (tiles->offsets[tile] + y*tiles->strides[tile] + x)*buffer_pass_stride + buffer_denoising_offset; + ccl_global float *center_buffer = ((ccl_global float*) ccl_get_tile_buffer(tile)) + (tile_info->offsets[tile] + y*tile_info->strides[tile] + x)*buffer_pass_stride + buffer_denoising_offset; int buffer_w = align_up(rect.z - rect.x, 4); int idx = (y-rect.y)*buffer_w + (x - rect.x); diff --git a/intern/cycles/kernel/geom/geom.h b/intern/cycles/kernel/geom/geom.h index f34b77ebc07f..e81c1b781c83 100644 --- a/intern/cycles/kernel/geom/geom.h +++ b/intern/cycles/kernel/geom/geom.h @@ -30,4 +30,3 @@ #include "kernel/geom/geom_curve_intersect.h" #include "kernel/geom/geom_volume.h" #include "kernel/geom/geom_primitive.h" - diff --git a/intern/cycles/kernel/geom/geom_attribute.h b/intern/cycles/kernel/geom/geom_attribute.h index 42c053704d54..e991f3d685ad 100644 --- a/intern/cycles/kernel/geom/geom_attribute.h +++ b/intern/cycles/kernel/geom/geom_attribute.h @@ -66,7 +66,7 @@ ccl_device_inline AttributeDescriptor find_attribute(KernelGlobals *kg, const Sh uint attr_offset = object_attribute_map_offset(kg, sd->object); attr_offset += attribute_primitive_type(kg, sd); uint4 attr_map = kernel_tex_fetch(__attributes_map, attr_offset); - + while(attr_map.x != id) { if(UNLIKELY(attr_map.x == ATTR_STD_NONE)) { return attribute_not_found(); @@ -77,7 +77,7 @@ ccl_device_inline AttributeDescriptor find_attribute(KernelGlobals *kg, const Sh AttributeDescriptor desc; desc.element = (AttributeElement)attr_map.y; - + if(sd->prim == PRIM_NONE && desc.element != ATTR_ELEMENT_MESH && desc.element != ATTR_ELEMENT_VOXEL && @@ -108,4 +108,3 @@ ccl_device Transform primitive_attribute_matrix(KernelGlobals *kg, const ShaderD } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_curve.h b/intern/cycles/kernel/geom/geom_curve.h index e35267f02bf4..dea0c742ed75 100644 --- a/intern/cycles/kernel/geom/geom_curve.h +++ b/intern/cycles/kernel/geom/geom_curve.h @@ -23,6 +23,33 @@ CCL_NAMESPACE_BEGIN #ifdef __HAIR__ +/* Interpolation of curve geometry */ + +ccl_device_inline float3 curvetangent(float t, float3 p0, float3 p1, float3 p2, float3 p3) +{ + float fc = 0.71f; + float data[4]; + float t2 = t * t; + data[0] = -3.0f * fc * t2 + 4.0f * fc * t - fc; + data[1] = 3.0f * (2.0f - fc) * t2 + 2.0f * (fc - 3.0f) * t; + data[2] = 3.0f * (fc - 2.0f) * t2 + 2.0f * (3.0f - 2.0f * fc) * t + fc; + data[3] = 3.0f * fc * t2 - 2.0f * fc * t; + return data[0] * p0 + data[1] * p1 + data[2] * p2 + data[3] * p3; +} + +ccl_device_inline float3 curvepoint(float t, float3 p0, float3 p1, float3 p2, float3 p3) +{ + float data[4]; + float fc = 0.71f; + float t2 = t * t; + float t3 = t2 * t; + data[0] = -fc * t3 + 2.0f * fc * t2 - fc * t; + data[1] = (2.0f - fc) * t3 + (fc - 3.0f) * t2 + 1.0f; + data[2] = (fc - 2.0f) * t3 + (3.0f - 2.0f * fc) * t2 + fc * t; + data[3] = fc * t3 - fc * t2; + return data[0] * p0 + data[1] * p1 + data[2] * p2 + data[3] * p3; +} + /* Reading attributes on various curve elements */ ccl_device float curve_attribute_float(KernelGlobals *kg, const ShaderData *sd, const AttributeDescriptor desc, float *dx, float *dy) diff --git a/intern/cycles/kernel/geom/geom_curve_intersect.h b/intern/cycles/kernel/geom/geom_curve_intersect.h index 46c3f408f0b2..4cfbe21685cc 100644 --- a/intern/cycles/kernel/geom/geom_curve_intersect.h +++ b/intern/cycles/kernel/geom/geom_curve_intersect.h @@ -752,31 +752,6 @@ ccl_device_forceinline bool curve_intersect(KernelGlobals *kg, #endif } -ccl_device_inline float3 curvetangent(float t, float3 p0, float3 p1, float3 p2, float3 p3) -{ - float fc = 0.71f; - float data[4]; - float t2 = t * t; - data[0] = -3.0f * fc * t2 + 4.0f * fc * t - fc; - data[1] = 3.0f * (2.0f - fc) * t2 + 2.0f * (fc - 3.0f) * t; - data[2] = 3.0f * (fc - 2.0f) * t2 + 2.0f * (3.0f - 2.0f * fc) * t + fc; - data[3] = 3.0f * fc * t2 - 2.0f * fc * t; - return data[0] * p0 + data[1] * p1 + data[2] * p2 + data[3] * p3; -} - -ccl_device_inline float3 curvepoint(float t, float3 p0, float3 p1, float3 p2, float3 p3) -{ - float data[4]; - float fc = 0.71f; - float t2 = t * t; - float t3 = t2 * t; - data[0] = -fc * t3 + 2.0f * fc * t2 - fc * t; - data[1] = (2.0f - fc) * t3 + (fc - 3.0f) * t2 + 1.0f; - data[2] = (fc - 2.0f) * t3 + (3.0f - 2.0f * fc) * t2 + fc * t; - data[3] = fc * t3 - fc * t2; - return data[0] * p0 + data[1] * p1 + data[2] * p2 + data[3] * p3; -} - ccl_device_inline float3 curve_refine(KernelGlobals *kg, ShaderData *sd, const Intersection *isect, diff --git a/intern/cycles/kernel/geom/geom_motion_curve.h b/intern/cycles/kernel/geom/geom_motion_curve.h index fad29e431ece..5cc22ae21556 100644 --- a/intern/cycles/kernel/geom/geom_motion_curve.h +++ b/intern/cycles/kernel/geom/geom_motion_curve.h @@ -214,4 +214,3 @@ ccl_device_inline void motion_cardinal_curve_keys_avx(KernelGlobals *kg, #endif CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_motion_triangle.h b/intern/cycles/kernel/geom/geom_motion_triangle.h index 7ac6807e7498..64f6d027b998 100644 --- a/intern/cycles/kernel/geom/geom_motion_triangle.h +++ b/intern/cycles/kernel/geom/geom_motion_triangle.h @@ -34,14 +34,14 @@ ccl_device_inline int find_attribute_motion(KernelGlobals *kg, int object, uint /* todo: find a better (faster) solution for this, maybe store offset per object */ uint attr_offset = object_attribute_map_offset(kg, object); uint4 attr_map = kernel_tex_fetch(__attributes_map, attr_offset); - + while(attr_map.x != id) { attr_offset += ATTR_PRIM_TYPES; attr_map = kernel_tex_fetch(__attributes_map, attr_offset); } *elem = (AttributeElement)attr_map.y; - + /* return result */ return (attr_map.y == ATTR_ELEMENT_NONE) ? (int)ATTR_STD_NOT_FOUND : (int)attr_map.z; } diff --git a/intern/cycles/kernel/geom/geom_motion_triangle_shader.h b/intern/cycles/kernel/geom/geom_motion_triangle_shader.h index 4789137d5b08..e91a4be96ba4 100644 --- a/intern/cycles/kernel/geom/geom_motion_triangle_shader.h +++ b/intern/cycles/kernel/geom/geom_motion_triangle_shader.h @@ -120,4 +120,3 @@ ccl_device_noinline void motion_triangle_shader_setup(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_object.h b/intern/cycles/kernel/geom/geom_object.h index 800649abf38a..cfe17e636276 100644 --- a/intern/cycles/kernel/geom/geom_object.h +++ b/intern/cycles/kernel/geom/geom_object.h @@ -613,4 +613,3 @@ ccl_device_inline void object_normal_transform_addrspace(KernelGlobals *kg, #endif CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_patch.h b/intern/cycles/kernel/geom/geom_patch.h index 5663b5985086..343649ad9348 100644 --- a/intern/cycles/kernel/geom/geom_patch.h +++ b/intern/cycles/kernel/geom/geom_patch.h @@ -340,4 +340,3 @@ ccl_device float3 patch_eval_uchar4(KernelGlobals *kg, const ShaderData *sd, int } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_primitive.h b/intern/cycles/kernel/geom/geom_primitive.h index c159be928856..6db8475d196c 100644 --- a/intern/cycles/kernel/geom/geom_primitive.h +++ b/intern/cycles/kernel/geom/geom_primitive.h @@ -192,7 +192,7 @@ ccl_device_inline float4 primitive_motion_vector(KernelGlobals *kg, ShaderData * /* object motion. note that depending on the mesh having motion vectors, this * transformation was set match the world/object space of motion_pre/post */ Transform tfm; - + tfm = object_fetch_motion_pass_transform(kg, sd->object, OBJECT_PASS_MOTION_PRE); motion_pre = transform_point(&tfm, motion_pre); @@ -240,4 +240,3 @@ ccl_device_inline float4 primitive_motion_vector(KernelGlobals *kg, ShaderData * } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_subd_triangle.h b/intern/cycles/kernel/geom/geom_subd_triangle.h index 044e82f03d43..00ce89ae5672 100644 --- a/intern/cycles/kernel/geom/geom_subd_triangle.h +++ b/intern/cycles/kernel/geom/geom_subd_triangle.h @@ -352,4 +352,3 @@ ccl_device_noinline float3 subd_triangle_attribute_float3(KernelGlobals *kg, con } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/geom/geom_triangle_intersect.h b/intern/cycles/kernel/geom/geom_triangle_intersect.h index a2b1e050e58a..aa6b102a0f31 100644 --- a/intern/cycles/kernel/geom/geom_triangle_intersect.h +++ b/intern/cycles/kernel/geom/geom_triangle_intersect.h @@ -1,4 +1,4 @@ -/* + /* * Copyright 2014, Blender Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -70,7 +70,483 @@ ccl_device_inline bool triangle_intersect(KernelGlobals *kg, return false; } -/* Special ray intersection routines for local intersection. In that case we +#ifdef __KERNEL_AVX2__ + +#define cross256(A,B, C,D) _mm256_fmsub_ps(A,B, _mm256_mul_ps(C,D)) +#if defined(__KERNEL_CUDA__) && __CUDA_ARCH__ < 300 +ccl_device_inline +#else +ccl_device_forceinline +#endif +int ray_triangle_intersect8(KernelGlobals *kg, + float3 ray_P, + float3 ray_dir, + Intersection **isect, + uint visibility, + int object, + __m256 *triA, + __m256 *triB, + __m256 *triC, + int prim_addr, + int prim_num, + uint *num_hits, + uint max_hits, + int *num_hits_in_instance, + float isec_t) +{ + + const unsigned char prim_num_mask = (1 << prim_num) - 1; + + const __m256i zero256 = _mm256_setzero_si256(); + + const __m256 Px256 = _mm256_set1_ps(ray_P.x); + const __m256 Py256 = _mm256_set1_ps(ray_P.y); + const __m256 Pz256 = _mm256_set1_ps(ray_P.z); + + const __m256 dirx256 = _mm256_set1_ps(ray_dir.x); + const __m256 diry256 = _mm256_set1_ps(ray_dir.y); + const __m256 dirz256 = _mm256_set1_ps(ray_dir.z); + + /* Calculate vertices relative to ray origin. */ + /* const float3 v0 = tri_c - P; + const float3 v1 = tri_a - P; + const float3 v2 = tri_b - P; */ + + __m256 v0_x_256 = _mm256_sub_ps(triC[0], Px256); + __m256 v0_y_256 = _mm256_sub_ps(triC[1], Py256); + __m256 v0_z_256 = _mm256_sub_ps(triC[2], Pz256); + + __m256 v1_x_256 = _mm256_sub_ps(triA[0], Px256); + __m256 v1_y_256 = _mm256_sub_ps(triA[1], Py256); + __m256 v1_z_256 = _mm256_sub_ps(triA[2], Pz256); + + __m256 v2_x_256 = _mm256_sub_ps(triB[0], Px256); + __m256 v2_y_256 = _mm256_sub_ps(triB[1], Py256); + __m256 v2_z_256 = _mm256_sub_ps(triB[2], Pz256); + + __m256 v0_v1_x_256 = _mm256_add_ps(v0_x_256, v1_x_256); + __m256 v0_v1_y_256 = _mm256_add_ps(v0_y_256, v1_y_256); + __m256 v0_v1_z_256 = _mm256_add_ps(v0_z_256, v1_z_256); + + __m256 v0_v2_x_256 = _mm256_add_ps(v0_x_256, v2_x_256); + __m256 v0_v2_y_256 = _mm256_add_ps(v0_y_256, v2_y_256); + __m256 v0_v2_z_256 = _mm256_add_ps(v0_z_256, v2_z_256); + + __m256 v1_v2_x_256 = _mm256_add_ps(v1_x_256, v2_x_256); + __m256 v1_v2_y_256 = _mm256_add_ps(v1_y_256, v2_y_256); + __m256 v1_v2_z_256 = _mm256_add_ps(v1_z_256, v2_z_256); + + /* Calculate triangle edges. + const float3 e0 = v2 - v0; + const float3 e1 = v0 - v1; + const float3 e2 = v1 - v2;*/ + + __m256 e0_x_256 = _mm256_sub_ps(v2_x_256, v0_x_256); + __m256 e0_y_256 = _mm256_sub_ps(v2_y_256, v0_y_256); + __m256 e0_z_256 = _mm256_sub_ps(v2_z_256, v0_z_256); + + __m256 e1_x_256 = _mm256_sub_ps(v0_x_256, v1_x_256); + __m256 e1_y_256 = _mm256_sub_ps(v0_y_256, v1_y_256); + __m256 e1_z_256 = _mm256_sub_ps(v0_z_256, v1_z_256); + + __m256 e2_x_256 = _mm256_sub_ps(v1_x_256, v2_x_256); + __m256 e2_y_256 = _mm256_sub_ps(v1_y_256, v2_y_256); + __m256 e2_z_256 = _mm256_sub_ps(v1_z_256, v2_z_256); + + /* Perform edge tests. + const float U = dot(cross(v2 + v0, e0), ray_dir); + const float V = dot(cross(v0 + v1, e1), ray_dir); + const float W = dot(cross(v1 + v2, e2), ray_dir);*/ + + //cross (AyBz - AzBy, AzBx -AxBz, AxBy - AyBx) + __m256 U_x_256 = cross256(v0_v2_y_256, e0_z_256, v0_v2_z_256, e0_y_256); + __m256 U_y_256 = cross256(v0_v2_z_256, e0_x_256, v0_v2_x_256, e0_z_256); + __m256 U_z_256 = cross256(v0_v2_x_256, e0_y_256, v0_v2_y_256, e0_x_256); + //vertical dot + __m256 U_256 = _mm256_mul_ps(U_x_256, dirx256); + U_256 = _mm256_fmadd_ps(U_y_256, diry256, U_256); //_mm256_add_ps(U_256, _mm256_mul_ps(U_y_256, diry256)); + U_256 = _mm256_fmadd_ps(U_z_256, dirz256, U_256); //_mm256_add_ps(U_256, _mm256_mul_ps(U_z_256, dirz256)); + + __m256 V_x_256 = cross256(v0_v1_y_256, e1_z_256, v0_v1_z_256, e1_y_256); + __m256 V_y_256 = cross256(v0_v1_z_256, e1_x_256, v0_v1_x_256, e1_z_256); + __m256 V_z_256 = cross256(v0_v1_x_256, e1_y_256, v0_v1_y_256, e1_x_256); + //vertical dot + __m256 V_256 = _mm256_mul_ps(V_x_256, dirx256); + V_256 = _mm256_fmadd_ps(V_y_256, diry256, V_256);// _mm256_add_ps(V_256, _mm256_mul_ps(V_y_256, diry256)); + V_256 = _mm256_fmadd_ps(V_z_256, dirz256, V_256);// _mm256_add_ps(V_256, _mm256_mul_ps(V_z_256, dirz256)); + + __m256 W_x_256 = cross256(v1_v2_y_256, e2_z_256, v1_v2_z_256, e2_y_256); + __m256 W_y_256 = cross256(v1_v2_z_256, e2_x_256, v1_v2_x_256, e2_z_256); + __m256 W_z_256 = cross256(v1_v2_x_256, e2_y_256, v1_v2_y_256, e2_x_256); + //vertical dot + __m256 W_256 = _mm256_mul_ps(W_x_256, dirx256); + W_256 = _mm256_fmadd_ps(W_y_256, diry256,W_256);//_mm256_add_ps(W_256, _mm256_mul_ps(W_y_256, diry256)); + W_256 = _mm256_fmadd_ps(W_z_256, dirz256,W_256);//_mm256_add_ps(W_256, _mm256_mul_ps(W_z_256, dirz256)); + + //const float minUVW = min(U, min(V, W)); + //const float maxUVW = max(U, max(V, W)); +#if 0 + __m256 minUVW_256 = _mm256_min_ps(U_256, _mm256_min_ps(V_256, W_256)); + __m256 maxUVW_256 = _mm256_max_ps(U_256, _mm256_max_ps(V_256, W_256)); + + //if(minUVW < 0.0f && maxUVW > 0.0f) + __m256i mask_minmaxUVW_256 = _mm256_and_si256( + _mm256_cmpgt_epi32(zero256, _mm256_castps_si256(minUVW_256)), + //_mm256_castps_si256(minUVW_256), + _mm256_cmpgt_epi32(_mm256_castps_si256(maxUVW_256), zero256)); +#else + __m256i U_256_1 = _mm256_srli_epi32(_mm256_castps_si256(U_256), 31); + __m256i V_256_1 = _mm256_srli_epi32(_mm256_castps_si256(V_256), 31); + __m256i W_256_1 = _mm256_srli_epi32(_mm256_castps_si256(W_256), 31); + __m256i UVW_256_1 = _mm256_add_epi32(_mm256_add_epi32(U_256_1, V_256_1), W_256_1); + + const __m256i one256 = _mm256_set1_epi32(1); + const __m256i two256 = _mm256_set1_epi32(2); + + __m256i mask_minmaxUVW_256 = _mm256_or_si256( + _mm256_cmpeq_epi32(one256, UVW_256_1), + _mm256_cmpeq_epi32(two256, UVW_256_1) ); +#endif + + unsigned char mask_minmaxUVW_pos = _mm256_movemask_ps(_mm256_castsi256_ps(mask_minmaxUVW_256)); + if((mask_minmaxUVW_pos & prim_num_mask) == prim_num_mask) { //all bits set + return false; + } + + /* Calculate geometry normal and denominator. */ + // const float3 Ng1 = cross(e1, e0); + //const Vec3vfM Ng1 = stable_triangle_normal(e2,e1,e0); + + __m256 Ng1_x_256 = cross256(e1_y_256, e0_z_256, e1_z_256, e0_y_256); + __m256 Ng1_y_256 = cross256(e1_z_256, e0_x_256, e1_x_256, e0_z_256); + __m256 Ng1_z_256 = cross256(e1_x_256, e0_y_256, e1_y_256, e0_x_256); + + //const float3 Ng = Ng1 + Ng1; + Ng1_x_256 = _mm256_add_ps(Ng1_x_256, Ng1_x_256); + Ng1_y_256 = _mm256_add_ps(Ng1_y_256, Ng1_y_256); + Ng1_z_256 = _mm256_add_ps(Ng1_z_256, Ng1_z_256); + + //const float den = dot3(Ng, dir); + //vertical dot + __m256 den_256 = _mm256_mul_ps(Ng1_x_256, dirx256); + den_256 = _mm256_fmadd_ps(Ng1_y_256, diry256,den_256);//_mm256_add_ps(den_256, _mm256_mul_ps(Ng1_y_256, diry256)); + den_256 = _mm256_fmadd_ps(Ng1_z_256, dirz256,den_256);//_mm256_add_ps(den_256, _mm256_mul_ps(Ng1_z_256, dirz256)); + + // __m256i maskden256 = _mm256_cmpeq_epi32(_mm256_castps_si256(den_256), zero256); + + /* Perform depth test. */ + //const float T = dot3(v0, Ng); + __m256 T_256 = _mm256_mul_ps(Ng1_x_256, v0_x_256); + T_256 = _mm256_fmadd_ps(Ng1_y_256, v0_y_256,T_256);//_mm256_add_ps(T_256, _mm256_mul_ps(Ng1_y_256, v0_y_256)); + T_256 = _mm256_fmadd_ps(Ng1_z_256, v0_z_256,T_256);//_mm256_add_ps(T_256, _mm256_mul_ps(Ng1_z_256, v0_z_256)); + + //const int sign_den = (__float_as_int(den) & 0x80000000); + const __m256i c0x80000000 = _mm256_set1_epi32(0x80000000); + __m256i sign_den_256 = _mm256_and_si256(_mm256_castps_si256(den_256), c0x80000000); + + //const float sign_T = xor_signmask(T, sign_den); + __m256 sign_T_256 = _mm256_castsi256_ps(_mm256_xor_si256(_mm256_castps_si256(T_256), sign_den_256)); + + /*if((sign_T < 0.0f) || mask_minmaxUVW_pos { return false;} */ + unsigned char mask_sign_T = _mm256_movemask_ps(sign_T_256); + if(((mask_minmaxUVW_pos | mask_sign_T) & prim_num_mask) == prim_num_mask) { + return false; + } /**/ + + __m256 xor_signmask_256 = _mm256_castsi256_ps(_mm256_xor_si256(_mm256_castps_si256(den_256), sign_den_256)); + + + ccl_align(32) float den8[8], U8[8], V8[8], T8[8], sign_T8[8], xor_signmask8[8]; + ccl_align(32) unsigned int mask_minmaxUVW8[8]; + + if(visibility == PATH_RAY_SHADOW_OPAQUE){ + __m256i mask_final_256 = _mm256_cmpeq_epi32(mask_minmaxUVW_256, zero256);//~mask_minmaxUVW_256 + + __m256i maskden256 = _mm256_cmpeq_epi32(_mm256_castps_si256(den_256), zero256); + + __m256i mask0 = _mm256_cmpgt_epi32(zero256, _mm256_castps_si256(sign_T_256)); + __m256 rayt_256 = _mm256_set1_ps((*isect)->t); + + __m256i mask1 = _mm256_cmpgt_epi32(_mm256_castps_si256(sign_T_256), + _mm256_castps_si256( + _mm256_mul_ps(_mm256_castsi256_ps(_mm256_xor_si256(_mm256_castps_si256(den_256), sign_den_256)), rayt_256) + ) + ); + /* __m256i mask1 = _mm256_castps_si256(_mm256_cmp_ps(sign_T_256, + _mm256_mul_ps(_mm256_castsi256_ps(_mm256_xor_si256(_mm256_castps_si256(den_256), sign_den_256)), rayt_256), + _CMP_GT_OS + ) );*/ + + mask0 = _mm256_or_si256(mask1, mask0); + //unsigned char mask = _mm256_movemask_ps(_mm256_castsi256_ps(mask0)); + //unsigned char maskden = _mm256_movemask_ps(_mm256_castsi256_ps(maskden256)); + //unsigned char mask_final = ((~mask) & (~maskden) & (~mask_minmaxUVW_pos)); + mask_final_256 = _mm256_andnot_si256(mask0, mask_final_256); //(~mask_minmaxUVW_pos) &(~mask) + mask_final_256 = _mm256_andnot_si256(maskden256, mask_final_256); //(~mask_minmaxUVW_pos) &(~mask) & (~maskden) + + unsigned char mask_final = _mm256_movemask_ps(_mm256_castsi256_ps(mask_final_256)); + if((mask_final & prim_num_mask) == 0) { //all bits NOT set + return false; + } /**/ + + unsigned long i = 0; +#if defined(_MSC_VER) + unsigned char res = _BitScanForward(&i, (unsigned long)mask_final); +#else + i = __builtin_ffs(mask_final)-1; +#endif + + den_256 = _mm256_rcp_ps(den_256); //inv_den + U_256 = _mm256_mul_ps(U_256, den_256); //*inv_den + V_256 = _mm256_mul_ps(V_256, den_256); //*inv_den + T_256 = _mm256_mul_ps(T_256, den_256); //*inv_den + + _mm256_store_ps(U8, U_256); + _mm256_store_ps(V8, V_256); + _mm256_store_ps(T8, T_256); + + + //here we assume (kernel_tex_fetch(__prim_visibility, (prim_addr +i)) & visibility) is always true + + (*isect)->u = U8[i]; + (*isect)->v = V8[i]; + (*isect)->t = T8[i]; + + (*isect)->prim = (prim_addr + i); + (*isect)->object = object; + (*isect)->type = PRIMITIVE_TRIANGLE; + + return true; + } + else { + _mm256_store_ps(den8, den_256); + _mm256_store_ps(U8, U_256); + _mm256_store_ps(V8, V_256); + _mm256_store_ps(T8, T_256); + + _mm256_store_ps(sign_T8, sign_T_256); + _mm256_store_ps(xor_signmask8, xor_signmask_256); + _mm256_store_si256((__m256i*)mask_minmaxUVW8, mask_minmaxUVW_256); + + int ret = false; + + if(visibility == PATH_RAY_SHADOW) { + for(int i = 0; i < prim_num; i++) { + if(!mask_minmaxUVW8[i]) { +#ifdef __VISIBILITY_FLAG__ + if(kernel_tex_fetch(__prim_visibility, (prim_addr + i)) & visibility) +#endif + { + if((sign_T8[i] >= 0.0f) && + (sign_T8[i] <= (*isect)->t * xor_signmask8[i])) + { + if(den8[i]) { + const float inv_den = 1.0f / den8[i]; + + (*isect)->u = U8[i] * inv_den; + (*isect)->v = V8[i] * inv_den; + (*isect)->t = T8[i] * inv_den; + + (*isect)->prim = (prim_addr + i); + (*isect)->object = object; + (*isect)->type = PRIMITIVE_TRIANGLE; + + int prim = kernel_tex_fetch(__prim_index, (*isect)->prim); + int shader = 0; + +#ifdef __HAIR__ + if(kernel_tex_fetch(__prim_type, (*isect)->prim) & PRIMITIVE_ALL_TRIANGLE) +#endif + { + shader = kernel_tex_fetch(__tri_shader, prim); + } +#ifdef __HAIR__ + else { + float4 str = kernel_tex_fetch(__curves, prim); + shader = __float_as_int(str.z); + } +#endif + int flag = kernel_tex_fetch(__shaders, (shader & SHADER_MASK)).flags; + + /* if no transparent shadows, all light is blocked */ + if(!(flag & SD_HAS_TRANSPARENT_SHADOW)) { + return 2; + } + /* if maximum number of hits reached, block all light */ + else if(*num_hits == max_hits) { + return 2; + } + /* move on to next entry in intersections array */ + ret = true; + + (*isect)++; + (*num_hits)++; + + (*num_hits_in_instance)++; + + (*isect)->t = isec_t; + + } //den + } //if sign + } //vis + }//if mask + } //for + } + else { //default case + for(int i = 0; i < prim_num; i++) { + if(!mask_minmaxUVW8[i]) { +#ifdef __VISIBILITY_FLAG__ + if(kernel_tex_fetch(__prim_visibility, (prim_addr + i)) & visibility) +#endif + { + if((sign_T8[i] >= 0.0f) && + (sign_T8[i] <= (*isect)->t * xor_signmask8[i])) + { + if(den8[i]) { + const float inv_den = 1.0f / den8[i]; + + (*isect)->u = U8[i] * inv_den; + (*isect)->v = V8[i] * inv_den; + (*isect)->t = T8[i] * inv_den; + + (*isect)->prim = (prim_addr + i); + (*isect)->object = object; + (*isect)->type = PRIMITIVE_TRIANGLE; + + ret = true; + } //den + } //if sign + } //vis + }//if mask + } //for + } //default + return ret; +}// else PATH_RAY_SHADOW_OPAQUE + +} + +//vz static +ccl_device_inline +int triangle_intersect8(KernelGlobals *kg, + Intersection **isect, + float3 P, + float3 dir, + uint visibility, + int object, + int prim_addr, + int prim_num, + uint *num_hits, + uint max_hits, + int *num_hits_in_instance, + float isec_t) + { + __m128 tri_a[8], tri_b[8], tri_c[8]; + __m256 tritmp[12], tri[12]; + __m256 triA[3], triB[3], triC[3]; + + int i, r; + + uint tri_vindex = kernel_tex_fetch(__prim_tri_index, prim_addr); + for(i = 0; i < prim_num; i++) { + tri_a[i] = *(__m128*)&kg->__prim_tri_verts.data[tri_vindex++]; + tri_b[i] = *(__m128*)&kg->__prim_tri_verts.data[tri_vindex++]; + tri_c[i] = *(__m128*)&kg->__prim_tri_verts.data[tri_vindex++]; + } + //create 9 or 12 placeholders + tri[0] = _mm256_castps128_ps256(tri_a[0]); //_mm256_zextps128_ps256 + tri[1] = _mm256_castps128_ps256(tri_b[0]);//_mm256_zextps128_ps256 + tri[2] = _mm256_castps128_ps256(tri_c[0]);//_mm256_zextps128_ps256 + + tri[3] = _mm256_castps128_ps256(tri_a[1]); //_mm256_zextps128_ps256 + tri[4] = _mm256_castps128_ps256(tri_b[1]);//_mm256_zextps128_ps256 + tri[5] = _mm256_castps128_ps256(tri_c[1]);//_mm256_zextps128_ps256 + + tri[6] = _mm256_castps128_ps256(tri_a[2]); //_mm256_zextps128_ps256 + tri[7] = _mm256_castps128_ps256(tri_b[2]);//_mm256_zextps128_ps256 + tri[8] = _mm256_castps128_ps256(tri_c[2]);//_mm256_zextps128_ps256 + + if(prim_num > 3) { + tri[9] = _mm256_castps128_ps256(tri_a[3]); //_mm256_zextps128_ps256 + tri[10] = _mm256_castps128_ps256(tri_b[3]);//_mm256_zextps128_ps256 + tri[11] = _mm256_castps128_ps256(tri_c[3]);//_mm256_zextps128_ps256 + } + + for(i = 4, r = 0; i < prim_num; i ++, r += 3) { + tri[r] = _mm256_insertf128_ps(tri[r] , tri_a[i], 1); + tri[r + 1] = _mm256_insertf128_ps(tri[r + 1], tri_b[i], 1); + tri[r + 2] = _mm256_insertf128_ps(tri[r + 2], tri_c[i], 1); + } + + //------------------------------------------------ + //0! Xa0 Ya0 Za0 1 Xa4 Ya4 Za4 1 + //1! Xb0 Yb0 Zb0 1 Xb4 Yb4 Zb4 1 + //2! Xc0 Yc0 Zc0 1 Xc4 Yc4 Zc4 1 + + //3! Xa1 Ya1 Za1 1 Xa5 Ya5 Za5 1 + //4! Xb1 Yb1 Zb1 1 Xb5 Yb5 Zb5 1 + //5! Xc1 Yc1 Zc1 1 Xc5 Yc5 Zc5 1 + + //6! Xa2 Ya2 Za2 1 Xa6 Ya6 Za6 1 + //7! Xb2 Yb2 Zb2 1 Xb6 Yb6 Zb6 1 + //8! Xc2 Yc2 Zc2 1 Xc6 Yc6 Zc6 1 + + //9! Xa3 Ya3 Za3 1 Xa7 Ya7 Za7 1 + //10! Xb3 Yb3 Zb3 1 Xb7 Yb7 Zb7 1 + //11! Xc3 Yc3 Zc3 1 Xc7 Yc7 Zc7 1 + + //"transpose" + tritmp[0] = _mm256_unpacklo_ps(tri[0], tri[3]); //0! Xa0 Xa1 Ya0 Ya1 Xa4 Xa5 Ya4 Ya5 + tritmp[1] = _mm256_unpackhi_ps(tri[0], tri[3]); //1! Za0 Za1 1 1 Za4 Za5 1 1 + + tritmp[2] = _mm256_unpacklo_ps(tri[6], tri[9]); //2! Xa2 Xa3 Ya2 Ya3 Xa6 Xa7 Ya6 Ya7 + tritmp[3] = _mm256_unpackhi_ps(tri[6], tri[9]); //3! Za2 Za3 1 1 Za6 Za7 1 1 + + tritmp[4] = _mm256_unpacklo_ps(tri[1], tri[4]); //4! Xb0 Xb1 Yb0 Yb1 Xb4 Xb5 Yb4 Yb5 + tritmp[5] = _mm256_unpackhi_ps(tri[1], tri[4]); //5! Zb0 Zb1 1 1 Zb4 Zb5 1 1 + + tritmp[6] = _mm256_unpacklo_ps(tri[7], tri[10]); //6! Xb2 Xb3 Yb2 Yb3 Xb6 Xb7 Yb6 Yb7 + tritmp[7] = _mm256_unpackhi_ps(tri[7], tri[10]); //7! Zb2 Zb3 1 1 Zb6 Zb7 1 1 + + tritmp[8] = _mm256_unpacklo_ps(tri[2], tri[5]); //8! Xc0 Xc1 Yc0 Yc1 Xc4 Xc5 Yc4 Yc5 + tritmp[9] = _mm256_unpackhi_ps(tri[2], tri[5]); //9! Zc0 Zc1 1 1 Zc4 Zc5 1 1 + + tritmp[10] = _mm256_unpacklo_ps(tri[8], tri[11]); //10! Xc2 Xc3 Yc2 Yc3 Xc6 Xc7 Yc6 Yc7 + tritmp[11] = _mm256_unpackhi_ps(tri[8], tri[11]); //11! Zc2 Zc3 1 1 Zc6 Zc7 1 1 + + /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ + triA[0] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[0]), _mm256_castps_pd(tritmp[2]))); // Xa0 Xa1 Xa2 Xa3 Xa4 Xa5 Xa6 Xa7 + triA[1] = _mm256_castpd_ps(_mm256_unpackhi_pd(_mm256_castps_pd(tritmp[0]), _mm256_castps_pd(tritmp[2]))); // Ya0 Ya1 Ya2 Ya3 Ya4 Ya5 Ya6 Ya7 + triA[2] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[1]), _mm256_castps_pd(tritmp[3]))); // Za0 Za1 Za2 Za3 Za4 Za5 Za6 Za7 + + triB[0] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[4]), _mm256_castps_pd(tritmp[6]))); // Xb0 Xb1 Xb2 Xb3 Xb4 Xb5 Xb5 Xb7 + triB[1] = _mm256_castpd_ps(_mm256_unpackhi_pd(_mm256_castps_pd(tritmp[4]), _mm256_castps_pd(tritmp[6]))); // Yb0 Yb1 Yb2 Yb3 Yb4 Yb5 Yb5 Yb7 + triB[2] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[5]), _mm256_castps_pd(tritmp[7]))); // Zb0 Zb1 Zb2 Zb3 Zb4 Zb5 Zb5 Zb7 + + triC[0] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[8]), _mm256_castps_pd(tritmp[10]))); //Xc0 Xc1 Xc2 Xc3 Xc4 Xc5 Xc6 Xc7 + triC[1] = _mm256_castpd_ps(_mm256_unpackhi_pd(_mm256_castps_pd(tritmp[8]), _mm256_castps_pd(tritmp[10]))); //Yc0 Yc1 Yc2 Yc3 Yc4 Yc5 Yc6 Yc7 + triC[2] = _mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(tritmp[9]), _mm256_castps_pd(tritmp[11]))); //Zc0 Zc1 Zc2 Zc3 Zc4 Zc5 Zc6 Zc7 + + /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ + + int result = ray_triangle_intersect8(kg, P, + dir, + isect, + visibility, object, + triA, + triB, + triC, + prim_addr, + prim_num, + num_hits, + max_hits, + num_hits_in_instance, + isec_t); + return result; +} + +#endif /* __KERNEL_AVX2__ */ + +/* Special ray intersection routines for subsurface scattering. In that case we * only want to intersect with primitives in the same object, and if case of * multiple hits we pick a single random primitive as the intersection point. * Returns whether traversal should be stopped. @@ -83,7 +559,7 @@ ccl_device_inline bool triangle_intersect_local( float3 P, float3 dir, int object, - int local_object, + int local_object, int prim_addr, float tmax, uint *lcg_state, diff --git a/intern/cycles/kernel/geom/geom_volume.h b/intern/cycles/kernel/geom/geom_volume.h index 346f228e9612..688413b74a14 100644 --- a/intern/cycles/kernel/geom/geom_volume.h +++ b/intern/cycles/kernel/geom/geom_volume.h @@ -80,4 +80,3 @@ ccl_device float3 volume_attribute_float3(KernelGlobals *kg, const ShaderData *s #endif CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel.h b/intern/cycles/kernel/kernel.h index cfb35dd33f5f..373324afb019 100644 --- a/intern/cycles/kernel/kernel.h +++ b/intern/cycles/kernel/kernel.h @@ -64,4 +64,3 @@ void kernel_tex_copy(KernelGlobals *kg, CCL_NAMESPACE_END #endif /* __KERNEL_H__ */ - diff --git a/intern/cycles/kernel/kernel_accumulate.h b/intern/cycles/kernel/kernel_accumulate.h index c0f281cae97f..86ad6e1a0615 100644 --- a/intern/cycles/kernel/kernel_accumulate.h +++ b/intern/cycles/kernel/kernel_accumulate.h @@ -270,7 +270,7 @@ ccl_device_inline void path_radiance_bsdf_bounce( L_state->transmission + L_state->subsurface + L_state->scatter; - + L_state->direct = *throughput; } else { @@ -320,7 +320,13 @@ ccl_device_inline void path_radiance_accum_ao(PathRadiance *L, float3 bsdf, float3 ao) { + /* Store AO pass. */ + if(L->use_light_pass && state->bounce == 0) { + L->ao += alpha*throughput*ao; + } + #ifdef __SHADOW_TRICKS__ + /* For shadow catcher, accumulate ratio. */ if(state->flag & PATH_RAY_STORE_SHADOW_INFO) { float3 light = throughput * bsdf; L->path_total += light; @@ -335,12 +341,11 @@ ccl_device_inline void path_radiance_accum_ao(PathRadiance *L, #ifdef __PASSES__ if(L->use_light_pass) { if(state->bounce == 0) { - /* directly visible lighting */ + /* Directly visible lighting. */ L->direct_diffuse += throughput*bsdf*ao; - L->ao += alpha*throughput*ao; } else { - /* indirectly visible lighting after BSDF bounce */ + /* Indirectly visible lighting after BSDF bounce. */ L->indirect += throughput*bsdf*ao; } } diff --git a/intern/cycles/kernel/kernel_bake.h b/intern/cycles/kernel/kernel_bake.h index 79e6d1b4862a..afb631528309 100644 --- a/intern/cycles/kernel/kernel_bake.h +++ b/intern/cycles/kernel/kernel_bake.h @@ -563,4 +563,3 @@ ccl_device void kernel_background_evaluate(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_compat_cpu.h b/intern/cycles/kernel/kernel_compat_cpu.h index d26b668cb112..aa7a16afa1d4 100644 --- a/intern/cycles/kernel/kernel_compat_cpu.h +++ b/intern/cycles/kernel/kernel_compat_cpu.h @@ -71,15 +71,13 @@ CCL_NAMESPACE_BEGIN /* Texture types to be compatible with CUDA textures. These are really just * simple arrays and after inlining fetch hopefully revert to being a simple * pointer lookup. */ - template struct texture { ccl_always_inline const T& fetch(int index) { kernel_assert(index >= 0 && index < width); return data[index]; } - -#ifdef __KERNEL_AVX__ +#if defined(__KERNEL_AVX__) || defined(__KERNEL_AVX2__) /* Reads 256 bytes but indexes in blocks of 128 bytes to maintain * compatibility with existing indicies and data structures. */ @@ -90,7 +88,6 @@ template struct texture { ssef *ssef_node_data = &ssef_data[index]; return _mm256_loadu_ps((float *)ssef_node_data); } - #endif #ifdef __KERNEL_SSE2__ @@ -148,9 +145,12 @@ ccl_device_inline void print_sse3i(const char *label, sse3i& a) print_ssei(label, a.z); } +#if defined(__KERNEL_AVX__) || defined(__KERNEL_AVX2__) +typedef vector3 avx3f; +#endif + #endif CCL_NAMESPACE_END #endif /* __KERNEL_COMPAT_CPU_H__ */ - diff --git a/intern/cycles/kernel/kernel_compat_opencl.h b/intern/cycles/kernel/kernel_compat_opencl.h index 671c47e2225f..3f7e264fbee7 100644 --- a/intern/cycles/kernel/kernel_compat_opencl.h +++ b/intern/cycles/kernel/kernel_compat_opencl.h @@ -123,6 +123,7 @@ #define fmaxf(x, y) fmax(((float)(x)), ((float)(y))) #define fminf(x, y) fmin(((float)(x)), ((float)(y))) #define fmodf(x, y) fmod((float)(x), (float)(y)) +#define sinhf(x) sinh(((float)(x))) #ifndef __CL_USE_NATIVE__ # define sinf(x) native_sin(((float)(x))) @@ -150,8 +151,12 @@ /* define NULL */ #define NULL 0 +/* enable extensions */ +#ifdef __KERNEL_CL_KHR_FP16__ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#endif + #include "util/util_half.h" #include "util/util_types.h" #endif /* __KERNEL_COMPAT_OPENCL_H__ */ - diff --git a/intern/cycles/kernel/kernel_differential.h b/intern/cycles/kernel/kernel_differential.h index ae1e70f01670..924d96c72e5b 100644 --- a/intern/cycles/kernel/kernel_differential.h +++ b/intern/cycles/kernel/kernel_differential.h @@ -103,4 +103,3 @@ ccl_device differential3 differential3_zero() } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_emission.h b/intern/cycles/kernel/kernel_emission.h index 524e2467ebc5..302bb0476479 100644 --- a/intern/cycles/kernel/kernel_emission.h +++ b/intern/cycles/kernel/kernel_emission.h @@ -76,7 +76,7 @@ ccl_device_noinline float3 direct_emissive_eval(KernelGlobals *kg, /* Evaluate emissive closure. */ eval = shader_emissive_eval(kg, emission_sd); } - + eval *= ls->eval_fac; return eval; @@ -338,4 +338,3 @@ ccl_device_noinline float3 indirect_background(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_film.h b/intern/cycles/kernel/kernel_film.h index 948156011797..b5f151d86639 100644 --- a/intern/cycles/kernel/kernel_film.h +++ b/intern/cycles/kernel/kernel_film.h @@ -87,4 +87,3 @@ ccl_device void kernel_film_convert_to_half_float(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_jitter.h b/intern/cycles/kernel/kernel_jitter.h index f5855757d3f0..3bde96b078cb 100644 --- a/intern/cycles/kernel/kernel_jitter.h +++ b/intern/cycles/kernel/kernel_jitter.h @@ -226,4 +226,3 @@ ccl_device void cmj_sample_2D(int s, int N, int p, float *fx, float *fy) #endif CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_light.h b/intern/cycles/kernel/kernel_light.h index bb182ef1f259..2a300d3419ee 100644 --- a/intern/cycles/kernel/kernel_light.h +++ b/intern/cycles/kernel/kernel_light.h @@ -72,24 +72,17 @@ ccl_device_inline float area_light_sample(float3 P, float y0 = dot(dir, y); float x1 = x0 + axisu_len; float y1 = y0 + axisv_len; - /* Create vectors to four vertices. */ - float3 v00 = make_float3(x0, y0, z0); - float3 v01 = make_float3(x0, y1, z0); - float3 v10 = make_float3(x1, y0, z0); - float3 v11 = make_float3(x1, y1, z0); - /* Compute normals to edges. */ - float3 n0 = normalize(cross(v00, v10)); - float3 n1 = normalize(cross(v10, v11)); - float3 n2 = normalize(cross(v11, v01)); - float3 n3 = normalize(cross(v01, v00)); /* Compute internal angles (gamma_i). */ - float g0 = safe_acosf(-dot(n0, n1)); - float g1 = safe_acosf(-dot(n1, n2)); - float g2 = safe_acosf(-dot(n2, n3)); - float g3 = safe_acosf(-dot(n3, n0)); + float4 diff = make_float4(x0, y1, x1, y0) - make_float4(x1, y0, x0, y1); + float4 nz = make_float4(y0, x1, y1, x0) * diff; + nz = nz / sqrt(z0 * z0 * diff * diff + nz * nz); + float g0 = safe_acosf(-nz.x * nz.y); + float g1 = safe_acosf(-nz.y * nz.z); + float g2 = safe_acosf(-nz.z * nz.w); + float g3 = safe_acosf(-nz.w * nz.x); /* Compute predefined constants. */ - float b0 = n0.z; - float b1 = n2.z; + float b0 = nz.x; + float b1 = nz.z; float b0sq = b0 * b0; float k = M_2PI_F - g2 - g3; /* Compute solid angle from internal angles. */ @@ -506,7 +499,7 @@ ccl_device float lamp_light_pdf(KernelGlobals *kg, const float3 Ng, const float3 if(cos_pi <= 0.0f) return 0.0f; - + return t*t/cos_pi; } diff --git a/intern/cycles/kernel/kernel_montecarlo.h b/intern/cycles/kernel/kernel_montecarlo.h index 9995490505fb..09a3fe8f23df 100644 --- a/intern/cycles/kernel/kernel_montecarlo.h +++ b/intern/cycles/kernel/kernel_montecarlo.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -184,6 +184,35 @@ ccl_device float2 regular_polygon_sample(float corners, float rotation, float u, return make_float2(cr*p.x - sr*p.y, sr*p.x + cr*p.y); } +ccl_device float3 ensure_valid_reflection(float3 Ng, float3 I, float3 N) +{ + float3 R = 2*dot(N, I)*N - I; + if(dot(Ng, R) >= 0.05f) { + return N; + } + + /* Form coordinate system with Ng as the Z axis and N inside the X-Z-plane. + * The X axis is found by normalizing the component of N that's orthogonal to Ng. + * The Y axis isn't actually needed. + */ + float3 X = normalize(N - dot(N, Ng)*Ng); + + /* Calculate N.z and N.x in the local coordinate system. */ + float Iz = dot(I, Ng); + float Ix2 = sqr(dot(I, X)), Iz2 = sqr(Iz); + float Ix2Iz2 = Ix2 + Iz2; + + float a = sqrtf(Ix2*(Ix2Iz2 - sqr(0.05f))); + float b = Iz*0.05f + Ix2Iz2; + float c = (a + b > 0.0f)? (a + b) : (-a + b); + + float Nz = sqrtf(0.5f * c * (1.0f / Ix2Iz2)); + float Nx = sqrtf(1.0f - sqr(Nz)); + + /* Transform back into global coordinates. */ + return Nx*X + Nz*Ng; +} + CCL_NAMESPACE_END #endif /* __KERNEL_MONTECARLO_CL__ */ diff --git a/intern/cycles/kernel/kernel_passes.h b/intern/cycles/kernel/kernel_passes.h index a42a8e9812f3..458aa6c2a972 100644 --- a/intern/cycles/kernel/kernel_passes.h +++ b/intern/cycles/kernel/kernel_passes.h @@ -203,7 +203,7 @@ ccl_device_inline void kernel_write_data_passes(KernelGlobals *kg, ccl_global fl if(!((flag | light_flag) & PASS_ANY)) return; - + if(!(path_flag & PATH_RAY_SINGLE_PASS_DONE)) { if(!(sd->flag & SD_TRANSPARENT) || kernel_data.film.pass_alpha_threshold == 0.0f || @@ -285,7 +285,7 @@ ccl_device_inline void kernel_write_light_passes(KernelGlobals *kg, ccl_global f if(!kernel_data.film.use_light_pass) return; - + if(light_flag & PASSMASK(DIFFUSE_INDIRECT)) kernel_write_pass_float3(buffer + kernel_data.film.pass_diffuse_indirect, L->indirect_diffuse); if(light_flag & PASSMASK(GLOSSY_INDIRECT)) @@ -392,4 +392,3 @@ ccl_device_inline void kernel_write_result(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_path.h b/intern/cycles/kernel/kernel_path.h index d79b556c2ce9..5745762e1836 100644 --- a/intern/cycles/kernel/kernel_path.h +++ b/intern/cycles/kernel/kernel_path.h @@ -762,4 +762,3 @@ ccl_device void kernel_path_trace(KernelGlobals *kg, #endif /* __SPLIT_KERNEL__ */ CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_path_state.h b/intern/cycles/kernel/kernel_path_state.h index 8a358e51f94c..e85050df4bbe 100644 --- a/intern/cycles/kernel/kernel_path_state.h +++ b/intern/cycles/kernel/kernel_path_state.h @@ -170,7 +170,7 @@ ccl_device_inline bool path_state_volume_next(KernelGlobals *kg, ccl_addr_space /* For volume bounding meshes we pass through without counting transparent * bounces, only sanity check in case self intersection gets us stuck. */ state->volume_bounds_bounce++; - if (state->volume_bounds_bounce > VOLUME_BOUNDS_MAX) { + if(state->volume_bounds_bounce > VOLUME_BOUNDS_MAX) { return false; } @@ -269,4 +269,3 @@ ccl_device_inline void path_state_branch(ccl_addr_space PathState *state, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_path_subsurface.h b/intern/cycles/kernel/kernel_path_subsurface.h index 71aea9e3b272..ff4a8a9d5800 100644 --- a/intern/cycles/kernel/kernel_path_subsurface.h +++ b/intern/cycles/kernel/kernel_path_subsurface.h @@ -152,4 +152,3 @@ ccl_device void kernel_path_subsurface_setup_indirect( #endif /* __SUBSURFACE__ */ CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_path_surface.h b/intern/cycles/kernel/kernel_path_surface.h index 27be90d50599..c9202ccb16d1 100644 --- a/intern/cycles/kernel/kernel_path_surface.h +++ b/intern/cycles/kernel/kernel_path_surface.h @@ -356,4 +356,3 @@ ccl_device bool kernel_path_surface_bounce(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_path_volume.h b/intern/cycles/kernel/kernel_path_volume.h index 6275d0d65621..feaea15d3c4c 100644 --- a/intern/cycles/kernel/kernel_path_volume.h +++ b/intern/cycles/kernel/kernel_path_volume.h @@ -85,7 +85,7 @@ bool kernel_path_volume_bounce( if(phase_pdf == 0.0f || bsdf_eval_is_zero(&phase_eval)) return false; - + /* modify throughput */ path_radiance_bsdf_bounce(kg, L_state, throughput, &phase_eval, phase_pdf, state->bounce, label); @@ -223,7 +223,7 @@ ccl_device void kernel_branched_path_volume_connect_light( VolumeIntegrateResult result = kernel_volume_decoupled_scatter(kg, state, ray, sd, &tp, rphase, rscatter, segment, (ls.t != FLT_MAX)? &ls.P: NULL, false); - + /* todo: split up light_sample so we don't have to call it again with new position */ if(result == VOLUME_PATH_SCATTERED && light_sample(kg, light_u, light_v, sd->time, sd->P, state->bounce, &ls)) { @@ -260,7 +260,7 @@ ccl_device void kernel_branched_path_volume_connect_light( VolumeIntegrateResult result = kernel_volume_decoupled_scatter(kg, state, ray, sd, &tp, rphase, rscatter, segment, (ls.t != FLT_MAX)? &ls.P: NULL, false); - + /* todo: split up light_sample so we don't have to call it again with new position */ if(result == VOLUME_PATH_SCATTERED && light_sample(kg, light_u, light_v, sd->time, sd->P, state->bounce, &ls)) { @@ -284,4 +284,3 @@ ccl_device void kernel_branched_path_volume_connect_light( #endif /* __VOLUME_SCATTER__ */ CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_projection.h b/intern/cycles/kernel/kernel_projection.h index 4540d733af4b..7bad89c831c8 100644 --- a/intern/cycles/kernel/kernel_projection.h +++ b/intern/cycles/kernel/kernel_projection.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: diff --git a/intern/cycles/kernel/kernel_random.h b/intern/cycles/kernel/kernel_random.h index 93152e9ff1c4..b33e4eba8a42 100644 --- a/intern/cycles/kernel/kernel_random.h +++ b/intern/cycles/kernel/kernel_random.h @@ -296,4 +296,3 @@ ccl_device float lcg_step_float_addrspace(ccl_addr_space uint *rng) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_shader.h b/intern/cycles/kernel/kernel_shader.h index b83460b3ffb9..e834b701f963 100644 --- a/intern/cycles/kernel/kernel_shader.h +++ b/intern/cycles/kernel/kernel_shader.h @@ -1010,7 +1010,7 @@ ccl_device void shader_eval_surface(KernelGlobals *kg, ShaderData *sd, DiffuseBsdf *bsdf = (DiffuseBsdf*)bsdf_alloc(sd, sizeof(DiffuseBsdf), make_float3(0.8f, 0.8f, 0.8f)); - if (bsdf != NULL) { + if(bsdf != NULL) { bsdf->N = sd->N; sd->flag |= bsdf_diffuse_setup(bsdf); } diff --git a/intern/cycles/kernel/kernel_subsurface.h b/intern/cycles/kernel/kernel_subsurface.h index e8553d84547d..a06fbe72ffaf 100644 --- a/intern/cycles/kernel/kernel_subsurface.h +++ b/intern/cycles/kernel/kernel_subsurface.h @@ -50,7 +50,7 @@ ccl_device_inline float3 subsurface_scatter_eval(ShaderData *sd, for(int i = 0; i < sd->num_closure; i++) { sc = &sd->closure[i]; - + if(CLOSURE_IS_DISK_BSSRDF(sc->type)) { /* in case of branched path integrate we sample all bssrdf's once, * for path trace we pick one, so adjust pdf for that */ @@ -533,4 +533,3 @@ ccl_device_inline int subsurface_scatter_multi_intersect( } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/kernel_textures.h b/intern/cycles/kernel/kernel_textures.h index a7b8c492ee96..e83727ec64e9 100644 --- a/intern/cycles/kernel/kernel_textures.h +++ b/intern/cycles/kernel/kernel_textures.h @@ -85,4 +85,3 @@ KERNEL_TEX(TextureInfo, __texture_info) KERNEL_TEX(float, __ies) #undef KERNEL_TEX - diff --git a/intern/cycles/kernel/kernel_types.h b/intern/cycles/kernel/kernel_types.h index c2a65dc99993..e93100a64428 100644 --- a/intern/cycles/kernel/kernel_types.h +++ b/intern/cycles/kernel/kernel_types.h @@ -54,7 +54,7 @@ CCL_NAMESPACE_BEGIN #define PRIM_NONE (~0) #define LAMP_NONE (~0) -#define VOLUME_STACK_SIZE 16 +#define VOLUME_STACK_SIZE 32 /* Split kernel constants */ #define WORK_POOL_SIZE_GPU 64 @@ -454,6 +454,7 @@ typedef enum DenoisingPassOffsets { DENOISING_PASS_SHADOW_B = 17, DENOISING_PASS_COLOR = 20, DENOISING_PASS_COLOR_VAR = 23, + DENOISING_PASS_CLEAN = 26, DENOISING_PASS_SIZE_BASE = 26, DENOISING_PASS_SIZE_CLEAN = 3, @@ -1238,19 +1239,19 @@ typedef struct KernelFilm { int pass_glossy_color; int pass_transmission_color; int pass_subsurface_color; - + int pass_diffuse_indirect; int pass_glossy_indirect; int pass_transmission_indirect; int pass_subsurface_indirect; int pass_volume_indirect; - + int pass_diffuse_direct; int pass_glossy_direct; int pass_transmission_direct; int pass_subsurface_direct; int pass_volume_direct; - + int pass_emission; int pass_background; int pass_ao; @@ -1383,8 +1384,9 @@ typedef enum KernelBVHLayout { BVH_LAYOUT_BVH2 = (1 << 0), BVH_LAYOUT_BVH4 = (1 << 1), + BVH_LAYOUT_BVH8 = (1 << 2), - BVH_LAYOUT_DEFAULT = BVH_LAYOUT_BVH4, + BVH_LAYOUT_DEFAULT = BVH_LAYOUT_BVH8, BVH_LAYOUT_ALL = (unsigned int)(-1), } KernelBVHLayout; @@ -1671,4 +1673,3 @@ typedef struct WorkTile { CCL_NAMESPACE_END #endif /* __KERNEL_TYPES_H__ */ - diff --git a/intern/cycles/kernel/kernel_volume.h b/intern/cycles/kernel/kernel_volume.h index 86378289b02a..d71761a97bca 100644 --- a/intern/cycles/kernel/kernel_volume.h +++ b/intern/cycles/kernel/kernel_volume.h @@ -68,7 +68,7 @@ ccl_device_inline bool volume_shader_sample(KernelGlobals *kg, if(!(sd->flag & (SD_EXTINCTION|SD_SCATTER|SD_EMISSION))) return false; - + coeff->sigma_s = make_float3(0.0f, 0.0f, 0.0f); coeff->sigma_t = (sd->flag & SD_EXTINCTION)? sd->closure_transparent_extinction: make_float3(0.0f, 0.0f, 0.0f); @@ -91,7 +91,7 @@ ccl_device_inline bool volume_shader_sample(KernelGlobals *kg, ccl_device float3 volume_color_transmittance(float3 sigma, float t) { - return make_float3(expf(-sigma.x * t), expf(-sigma.y * t), expf(-sigma.z * t)); + return exp3(-sigma * t); } ccl_device float kernel_volume_channel_get(float3 value, int channel) @@ -234,7 +234,7 @@ ccl_device void kernel_volume_shadow_heterogeneous(KernelGlobals *kg, sum += (-sigma_t * (new_t - t)); if((i & 0x07) == 0) { /* ToDo: Other interval? */ - tp = *throughput * make_float3(expf(sum.x), expf(sum.y), expf(sum.z)); + tp = *throughput * exp3(sum); /* stop if nearly all light is blocked */ if(tp.x < tp_eps && tp.y < tp_eps && tp.z < tp_eps) @@ -246,7 +246,7 @@ ccl_device void kernel_volume_shadow_heterogeneous(KernelGlobals *kg, t = new_t; if(t == ray->t) { /* Update throughput in case we haven't done it above */ - tp = *throughput * make_float3(expf(sum.x), expf(sum.y), expf(sum.z)); + tp = *throughput * exp3(sum); break; } } @@ -368,7 +368,7 @@ ccl_device float3 kernel_volume_emission_integrate(VolumeShaderCoefficients *coe } else emission *= t; - + return emission; } @@ -475,7 +475,7 @@ ccl_device VolumeIntegrateResult kernel_volume_integrate_homogeneous( new_tp = *throughput * transmittance / pdf; } } - else + else #endif if(closure_flag & SD_EXTINCTION) { /* absorption only, no sampling needed */ @@ -596,7 +596,7 @@ ccl_device VolumeIntegrateResult kernel_volume_integrate_heterogeneous_distance( xi = 1.0f - (1.0f - xi)/sample_transmittance; } } - else + else #endif if(closure_flag & SD_EXTINCTION) { /* absorption only, no sampling needed */ @@ -751,7 +751,7 @@ ccl_device void kernel_volume_decoupled_record(KernelGlobals *kg, PathState *sta step_offset = 0.0f; segment->steps = &segment->stack_step; } - + /* init accumulation variables */ float3 accum_emission = make_float3(0.0f, 0.0f, 0.0f); float3 accum_transmittance = make_float3(1.0f, 1.0f, 1.0f); @@ -1172,7 +1172,7 @@ ccl_device void kernel_volume_stack_init(KernelGlobals *kg, break; } } - if(need_add) { + if(need_add && stack_index < VOLUME_STACK_SIZE - 1) { stack[stack_index].object = stack_sd->object; stack[stack_index].shader = stack_sd->shader; ++stack_index; @@ -1263,7 +1263,7 @@ ccl_device void kernel_volume_stack_enter_exit(KernelGlobals *kg, ShaderData *sd if(!(sd->flag & SD_HAS_VOLUME)) return; - + if(sd->flag & SD_BACKFACING) { /* exit volume object: remove from stack */ for(int i = 0; stack[i].shader != SHADER_NONE; i++) { diff --git a/intern/cycles/kernel/kernels/cpu/filter_cpu.h b/intern/cycles/kernel/kernels/cpu/filter_cpu.h index 4231aba88d7b..b62aa9663ec5 100644 --- a/intern/cycles/kernel/kernels/cpu/filter_cpu.h +++ b/intern/cycles/kernel/kernels/cpu/filter_cpu.h @@ -17,7 +17,7 @@ /* Templated common declaration part of all CPU kernels. */ void KERNEL_FUNCTION_FULL_NAME(filter_divide_shadow)(int sample, - TilesInfo *tiles, + TileInfo *tile_info, int x, int y, float *unfilteredA, @@ -30,7 +30,7 @@ void KERNEL_FUNCTION_FULL_NAME(filter_divide_shadow)(int sample, int buffer_denoising_offset); void KERNEL_FUNCTION_FULL_NAME(filter_get_feature)(int sample, - TilesInfo *tiles, + TileInfo *tile_info, int m_offset, int v_offset, int x, diff --git a/intern/cycles/kernel/kernels/cpu/filter_cpu_impl.h b/intern/cycles/kernel/kernels/cpu/filter_cpu_impl.h index 504622ecfd97..26777fdabb2b 100644 --- a/intern/cycles/kernel/kernels/cpu/filter_cpu_impl.h +++ b/intern/cycles/kernel/kernels/cpu/filter_cpu_impl.h @@ -34,7 +34,7 @@ CCL_NAMESPACE_BEGIN /* Denoise filter */ void KERNEL_FUNCTION_FULL_NAME(filter_divide_shadow)(int sample, - TilesInfo *tiles, + TileInfo *tile_info, int x, int y, float *unfilteredA, @@ -49,7 +49,7 @@ void KERNEL_FUNCTION_FULL_NAME(filter_divide_shadow)(int sample, #ifdef KERNEL_STUB STUB_ASSERT(KERNEL_ARCH, filter_divide_shadow); #else - kernel_filter_divide_shadow(sample, tiles, + kernel_filter_divide_shadow(sample, tile_info, x, y, unfilteredA, unfilteredB, @@ -63,7 +63,7 @@ void KERNEL_FUNCTION_FULL_NAME(filter_divide_shadow)(int sample, } void KERNEL_FUNCTION_FULL_NAME(filter_get_feature)(int sample, - TilesInfo *tiles, + TileInfo *tile_info, int m_offset, int v_offset, int x, @@ -76,7 +76,7 @@ void KERNEL_FUNCTION_FULL_NAME(filter_get_feature)(int sample, #ifdef KERNEL_STUB STUB_ASSERT(KERNEL_ARCH, filter_get_feature); #else - kernel_filter_get_feature(sample, tiles, + kernel_filter_get_feature(sample, tile_info, m_offset, v_offset, x, y, mean, variance, diff --git a/intern/cycles/kernel/kernels/cpu/kernel_cpu_image.h b/intern/cycles/kernel/kernels/cpu/kernel_cpu_image.h index 7bf833eadbc9..b77b7350d86b 100644 --- a/intern/cycles/kernel/kernels/cpu/kernel_cpu_image.h +++ b/intern/cycles/kernel/kernels/cpu/kernel_cpu_image.h @@ -35,13 +35,13 @@ template struct TextureInterpolator { static ccl_always_inline float4 read(uchar4 r) { - float f = 1.0f/255.0f; + float f = 1.0f / 255.0f; return make_float4(r.x*f, r.y*f, r.z*f, r.w*f); } static ccl_always_inline float4 read(uchar r) { - float f = r*(1.0f/255.0f); + float f = r * (1.0f / 255.0f); return make_float4(f, f, f, 1.0f); } @@ -63,6 +63,18 @@ template struct TextureInterpolator { return make_float4(f, f, f, 1.0f); } + static ccl_always_inline float4 read(uint16_t r) + { + float f = r*(1.0f/65535.0f); + return make_float4(f, f, f, 1.0f); + } + + static ccl_always_inline float4 read(ushort4 r) + { + float f = 1.0f/65535.0f; + return make_float4(r.x*f, r.y*f, r.z*f, r.w*f); + } + static ccl_always_inline float4 read(const T *data, int x, int y, int width, int height) @@ -481,15 +493,21 @@ ccl_device float4 kernel_tex_image_interp(KernelGlobals *kg, int id, float x, fl return TextureInterpolator::interp(info, x, y); case IMAGE_DATA_TYPE_BYTE: return TextureInterpolator::interp(info, x, y); + case IMAGE_DATA_TYPE_USHORT: + return TextureInterpolator::interp(info, x, y); case IMAGE_DATA_TYPE_FLOAT: return TextureInterpolator::interp(info, x, y); case IMAGE_DATA_TYPE_HALF4: return TextureInterpolator::interp(info, x, y); case IMAGE_DATA_TYPE_BYTE4: return TextureInterpolator::interp(info, x, y); + case IMAGE_DATA_TYPE_USHORT4: + return TextureInterpolator::interp(info, x, y); case IMAGE_DATA_TYPE_FLOAT4: - default: return TextureInterpolator::interp(info, x, y); + default: + assert(0); + return make_float4(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B, TEX_IMAGE_MISSING_A); } } @@ -502,15 +520,21 @@ ccl_device float4 kernel_tex_image_interp_3d(KernelGlobals *kg, int id, float x, return TextureInterpolator::interp_3d(info, x, y, z, interp); case IMAGE_DATA_TYPE_BYTE: return TextureInterpolator::interp_3d(info, x, y, z, interp); + case IMAGE_DATA_TYPE_USHORT: + return TextureInterpolator::interp_3d(info, x, y, z, interp); case IMAGE_DATA_TYPE_FLOAT: return TextureInterpolator::interp_3d(info, x, y, z, interp); case IMAGE_DATA_TYPE_HALF4: return TextureInterpolator::interp_3d(info, x, y, z, interp); case IMAGE_DATA_TYPE_BYTE4: return TextureInterpolator::interp_3d(info, x, y, z, interp); + case IMAGE_DATA_TYPE_USHORT4: + return TextureInterpolator::interp_3d(info, x, y, z, interp); case IMAGE_DATA_TYPE_FLOAT4: - default: return TextureInterpolator::interp_3d(info, x, y, z, interp); + default: + assert(0); + return make_float4(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B, TEX_IMAGE_MISSING_A); } } diff --git a/intern/cycles/kernel/kernels/cpu/kernel_split.cpp b/intern/cycles/kernel/kernels/cpu/kernel_split.cpp index ca750e5a00d6..c5e199b0a690 100644 --- a/intern/cycles/kernel/kernels/cpu/kernel_split.cpp +++ b/intern/cycles/kernel/kernels/cpu/kernel_split.cpp @@ -60,4 +60,3 @@ #include "kernel/kernel.h" #define KERNEL_ARCH cpu #include "kernel/kernels/cpu/kernel_cpu_impl.h" - diff --git a/intern/cycles/kernel/kernels/cuda/filter.cu b/intern/cycles/kernel/kernels/cuda/filter.cu index 035f0484488c..0561c40e6b18 100644 --- a/intern/cycles/kernel/kernels/cuda/filter.cu +++ b/intern/cycles/kernel/kernels/cuda/filter.cu @@ -29,7 +29,7 @@ extern "C" __global__ void CUDA_LAUNCH_BOUNDS(CUDA_THREADS_BLOCK_WIDTH, CUDA_KERNEL_MAX_REGISTERS) kernel_cuda_filter_divide_shadow(int sample, - TilesInfo *tiles, + TileInfo *tile_info, float *unfilteredA, float *unfilteredB, float *sampleVariance, @@ -43,7 +43,7 @@ kernel_cuda_filter_divide_shadow(int sample, int y = prefilter_rect.y + blockDim.y*blockIdx.y + threadIdx.y; if(x < prefilter_rect.z && y < prefilter_rect.w) { kernel_filter_divide_shadow(sample, - tiles, + tile_info, x, y, unfilteredA, unfilteredB, @@ -59,7 +59,7 @@ kernel_cuda_filter_divide_shadow(int sample, extern "C" __global__ void CUDA_LAUNCH_BOUNDS(CUDA_THREADS_BLOCK_WIDTH, CUDA_KERNEL_MAX_REGISTERS) kernel_cuda_filter_get_feature(int sample, - TilesInfo *tiles, + TileInfo *tile_info, int m_offset, int v_offset, float *mean, @@ -72,7 +72,7 @@ kernel_cuda_filter_get_feature(int sample, int y = prefilter_rect.y + blockDim.y*blockIdx.y + threadIdx.y; if(x < prefilter_rect.z && y < prefilter_rect.w) { kernel_filter_get_feature(sample, - tiles, + tile_info, m_offset, v_offset, x, y, mean, variance, diff --git a/intern/cycles/kernel/kernels/cuda/kernel_config.h b/intern/cycles/kernel/kernels/cuda/kernel_config.h index f3d0d721c5ce..3808898c5cab 100644 --- a/intern/cycles/kernel/kernels/cuda/kernel_config.h +++ b/intern/cycles/kernel/kernels/cuda/kernel_config.h @@ -106,4 +106,3 @@ #if CUDA_KERNEL_BRANCHED_MAX_REGISTERS > CUDA_THREAD_MAX_REGISTERS # error "Maximum number of registers per thread exceeded" #endif - diff --git a/intern/cycles/kernel/kernels/cuda/kernel_cuda_image.h b/intern/cycles/kernel/kernels/cuda/kernel_cuda_image.h index 91ad289a8588..37cfbbcb2351 100644 --- a/intern/cycles/kernel/kernels/cuda/kernel_cuda_image.h +++ b/intern/cycles/kernel/kernels/cuda/kernel_cuda_image.h @@ -127,11 +127,12 @@ ccl_device float4 kernel_tex_image_interp(KernelGlobals *kg, int id, float x, fl const TextureInfo& info = kernel_tex_fetch(__texture_info, id); CUtexObject tex = (CUtexObject)info.data; - /* float4, byte4 and half4 */ + /* float4, byte4, ushort4 and half4 */ const int texture_type = kernel_tex_type(id); if(texture_type == IMAGE_DATA_TYPE_FLOAT4 || texture_type == IMAGE_DATA_TYPE_BYTE4 || - texture_type == IMAGE_DATA_TYPE_HALF4) + texture_type == IMAGE_DATA_TYPE_HALF4 || + texture_type == IMAGE_DATA_TYPE_USHORT4) { if(info.interpolation == INTERPOLATION_CUBIC) { return kernel_tex_image_interp_bicubic(info, tex, x, y); @@ -164,7 +165,8 @@ ccl_device float4 kernel_tex_image_interp_3d(KernelGlobals *kg, int id, float x, const int texture_type = kernel_tex_type(id); if(texture_type == IMAGE_DATA_TYPE_FLOAT4 || texture_type == IMAGE_DATA_TYPE_BYTE4 || - texture_type == IMAGE_DATA_TYPE_HALF4) + texture_type == IMAGE_DATA_TYPE_HALF4 || + texture_type == IMAGE_DATA_TYPE_USHORT4) { if(interpolation == INTERPOLATION_CUBIC) { return kernel_tex_image_interp_bicubic_3d(info, tex, x, y, z); @@ -186,4 +188,3 @@ ccl_device float4 kernel_tex_image_interp_3d(KernelGlobals *kg, int id, float x, return make_float4(f, f, f, 1.0f); } } - diff --git a/intern/cycles/kernel/kernels/opencl/filter.cl b/intern/cycles/kernel/kernels/opencl/filter.cl index 2b77807c38bf..3c75754fb391 100644 --- a/intern/cycles/kernel/kernels/opencl/filter.cl +++ b/intern/cycles/kernel/kernels/opencl/filter.cl @@ -23,7 +23,7 @@ /* kernels */ __kernel void kernel_ocl_filter_divide_shadow(int sample, - ccl_global TilesInfo *tiles, + CCL_FILTER_TILE_INFO, ccl_global float *unfilteredA, ccl_global float *unfilteredB, ccl_global float *sampleVariance, @@ -37,7 +37,7 @@ __kernel void kernel_ocl_filter_divide_shadow(int sample, int y = prefilter_rect.y + get_global_id(1); if(x < prefilter_rect.z && y < prefilter_rect.w) { kernel_filter_divide_shadow(sample, - tiles, + CCL_FILTER_TILE_INFO_ARG, x, y, unfilteredA, unfilteredB, @@ -51,7 +51,7 @@ __kernel void kernel_ocl_filter_divide_shadow(int sample, } __kernel void kernel_ocl_filter_get_feature(int sample, - ccl_global TilesInfo *tiles, + CCL_FILTER_TILE_INFO, int m_offset, int v_offset, ccl_global float *mean, @@ -64,7 +64,7 @@ __kernel void kernel_ocl_filter_get_feature(int sample, int y = prefilter_rect.y + get_global_id(1); if(x < prefilter_rect.z && y < prefilter_rect.w) { kernel_filter_get_feature(sample, - tiles, + CCL_FILTER_TILE_INFO_ARG, m_offset, v_offset, x, y, mean, variance, @@ -276,27 +276,3 @@ __kernel void kernel_ocl_filter_finalize(ccl_global float *buffer, buffer_params, sample); } } - -__kernel void kernel_ocl_filter_set_tiles(ccl_global TilesInfo* tiles, - ccl_global float *buffer_1, - ccl_global float *buffer_2, - ccl_global float *buffer_3, - ccl_global float *buffer_4, - ccl_global float *buffer_5, - ccl_global float *buffer_6, - ccl_global float *buffer_7, - ccl_global float *buffer_8, - ccl_global float *buffer_9) -{ - if((get_global_id(0) == 0) && (get_global_id(1) == 0)) { - tiles->buffers[0] = buffer_1; - tiles->buffers[1] = buffer_2; - tiles->buffers[2] = buffer_3; - tiles->buffers[3] = buffer_4; - tiles->buffers[4] = buffer_5; - tiles->buffers[5] = buffer_6; - tiles->buffers[6] = buffer_7; - tiles->buffers[7] = buffer_8; - tiles->buffers[8] = buffer_9; - } -} diff --git a/intern/cycles/kernel/kernels/opencl/kernel_opencl_image.h b/intern/cycles/kernel/kernels/opencl/kernel_opencl_image.h index faa9dd66d0eb..dd9d683e0307 100644 --- a/intern/cycles/kernel/kernels/opencl/kernel_opencl_image.h +++ b/intern/cycles/kernel/kernels/opencl/kernel_opencl_image.h @@ -54,12 +54,35 @@ ccl_device_inline float4 svm_image_texture_read(KernelGlobals *kg, const ccl_glo float f = 1.0f/255.0f; return make_float4(r.x*f, r.y*f, r.z*f, r.w*f); } + /* Ushort4 */ + else if(texture_type == IMAGE_DATA_TYPE_USHORT4) { + ushort4 r = tex_fetch(ushort4, info, offset); + float f = 1.0f/65535.f; + return make_float4(r.x*f, r.y*f, r.z*f, r.w*f); + } /* Float */ else if(texture_type == IMAGE_DATA_TYPE_FLOAT) { float f = tex_fetch(float, info, offset); return make_float4(f, f, f, 1.0f); } + /* UShort */ + else if(texture_type == IMAGE_DATA_TYPE_USHORT) { + ushort r = tex_fetch(ushort, info, offset); + float f = r * (1.0f / 65535.0f); + return make_float4(f, f, f, 1.0f); + } /* Byte */ +#ifdef cl_khr_fp16 + /* half and half4 are optional in OpenCL */ + else if(texture_type == IMAGE_DATA_TYPE_HALF) { + float f = tex_fetch(half, info, offset); + return make_float4(f, f, f, 1.0f); + } + else if(texture_type == IMAGE_DATA_TYPE_HALF4) { + half4 r = tex_fetch(half4, info, offset); + return make_float4(r.x, r.y, r.z, r.w); + } +#endif else { uchar r = tex_fetch(uchar, info, offset); float f = r * (1.0f/255.0f); diff --git a/intern/cycles/kernel/kernels/opencl/kernel_split_function.h b/intern/cycles/kernel/kernels/opencl/kernel_split_function.h index 6aa7681cbed5..05e1ddf6da27 100644 --- a/intern/cycles/kernel/kernels/opencl/kernel_split_function.h +++ b/intern/cycles/kernel/kernels/opencl/kernel_split_function.h @@ -62,4 +62,3 @@ __kernel void KERNEL_NAME_EVAL(kernel_ocl_path_trace, KERNEL_NAME)( #undef KERNEL_NAME_JOIN #undef KERNEL_NAME_EVAL - diff --git a/intern/cycles/kernel/osl/CMakeLists.txt b/intern/cycles/kernel/osl/CMakeLists.txt index 159de63a0442..adca45c5c76d 100644 --- a/intern/cycles/kernel/osl/CMakeLists.txt +++ b/intern/cycles/kernel/osl/CMakeLists.txt @@ -31,4 +31,3 @@ include_directories(${INC}) include_directories(SYSTEM ${INC_SYS}) cycles_add_library(cycles_kernel_osl ${SRC} ${HEADER_SRC}) - diff --git a/intern/cycles/kernel/osl/background.cpp b/intern/cycles/kernel/osl/background.cpp index 30a9e84c3994..6924a4144c5b 100644 --- a/intern/cycles/kernel/osl/background.cpp +++ b/intern/cycles/kernel/osl/background.cpp @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -96,4 +96,3 @@ ClosureParam *closure_holdout_params() CCLOSURE_PREPARE(closure_holdout_prepare, HoldoutClosure) CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/bsdf_diffuse_ramp.cpp b/intern/cycles/kernel/osl/bsdf_diffuse_ramp.cpp index ea18f2c8c86d..ed5d5235a346 100644 --- a/intern/cycles/kernel/osl/bsdf_diffuse_ramp.cpp +++ b/intern/cycles/kernel/osl/bsdf_diffuse_ramp.cpp @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -82,4 +82,3 @@ ClosureParam *closure_bsdf_diffuse_ramp_params() CCLOSURE_PREPARE(closure_bsdf_diffuse_ramp_prepare, DiffuseRampClosure) CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/bsdf_phong_ramp.cpp b/intern/cycles/kernel/osl/bsdf_phong_ramp.cpp index a26671eb09e9..a8acdb8e342c 100644 --- a/intern/cycles/kernel/osl/bsdf_phong_ramp.cpp +++ b/intern/cycles/kernel/osl/bsdf_phong_ramp.cpp @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -82,4 +82,3 @@ ClosureParam *closure_bsdf_phong_ramp_params() CCLOSURE_PREPARE(closure_bsdf_phong_ramp_prepare, PhongRampClosure) CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/emissive.cpp b/intern/cycles/kernel/osl/emissive.cpp index 6162786b5276..c2a848231f2a 100644 --- a/intern/cycles/kernel/osl/emissive.cpp +++ b/intern/cycles/kernel/osl/emissive.cpp @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -72,4 +72,3 @@ ClosureParam *closure_emission_params() CCLOSURE_PREPARE(closure_emission_prepare, GenericEmissiveClosure) CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/osl_bssrdf.cpp b/intern/cycles/kernel/osl/osl_bssrdf.cpp index da7368bbc61f..66ec8a996cae 100644 --- a/intern/cycles/kernel/osl/osl_bssrdf.cpp +++ b/intern/cycles/kernel/osl/osl_bssrdf.cpp @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -69,22 +69,22 @@ class CBSSRDFClosure : public CClosurePrimitive { void setup(ShaderData *sd, int path_flag, float3 weight) { - if (method == u_cubic) { + if(method == u_cubic) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_CUBIC_ID); } - else if (method == u_gaussian) { + else if(method == u_gaussian) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_GAUSSIAN_ID); } - else if (method == u_burley) { + else if(method == u_burley) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_BURLEY_ID); } - else if (method == u_principled) { + else if(method == u_principled) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_PRINCIPLED_ID); } - else if (method == u_random_walk) { + else if(method == u_random_walk) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_RANDOM_WALK_ID); } - else if (method == u_principled_random_walk) { + else if(method == u_principled_random_walk) { alloc(sd, path_flag, weight, CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID); } } @@ -132,4 +132,3 @@ ClosureParam *closure_bssrdf_params() CCLOSURE_PREPARE(closure_bssrdf_prepare, CBSSRDFClosure) CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/osl_closures.cpp b/intern/cycles/kernel/osl/osl_closures.cpp index 6a1e52d7d169..169351d5ad95 100644 --- a/intern/cycles/kernel/osl/osl_closures.cpp +++ b/intern/cycles/kernel/osl/osl_closures.cpp @@ -4,8 +4,8 @@ * Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. * All Rights Reserved. * - * Modifications Copyright 2011, Blender Foundation. - * + * Modifications Copyright 2011-2018, Blender Foundation. + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -59,6 +59,7 @@ #include "kernel/closure/bsdf_ashikhmin_shirley.h" #include "kernel/closure/bsdf_toon.h" #include "kernel/closure/bsdf_hair.h" +#include "kernel/closure/bsdf_hair_principled.h" #include "kernel/closure/bsdf_principled_diffuse.h" #include "kernel/closure/bsdf_principled_sheen.h" #include "kernel/closure/volume.h" @@ -176,6 +177,59 @@ BSDF_CLOSURE_CLASS_BEGIN(PrincipledSheen, principled_sheen, PrincipledSheenBsdf, CLOSURE_FLOAT3_PARAM(PrincipledSheenClosure, params.N), BSDF_CLOSURE_CLASS_END(PrincipledSheen, principled_sheen) +/* PRINCIPLED HAIR BSDF */ +class PrincipledHairClosure : public CBSDFClosure { +public: + PrincipledHairBSDF params; + + PrincipledHairBSDF *alloc(ShaderData *sd, int path_flag, float3 weight) + { + PrincipledHairBSDF *bsdf = (PrincipledHairBSDF*)bsdf_alloc_osl(sd, sizeof(PrincipledHairBSDF), weight, ¶ms); + if(!bsdf) { + return NULL; + } + + PrincipledHairExtra *extra = (PrincipledHairExtra*)closure_alloc_extra(sd, sizeof(PrincipledHairExtra)); + if(!extra) { + return NULL; + } + + bsdf->extra = extra; + return bsdf; + } + + void setup(ShaderData *sd, int path_flag, float3 weight) + { + if(!skip(sd, path_flag, LABEL_GLOSSY)) { + PrincipledHairBSDF *bsdf = (PrincipledHairBSDF*)alloc(sd, path_flag, weight); + if(!bsdf) { + return; + } + + sd->flag |= (bsdf) ? bsdf_principled_hair_setup(sd, bsdf) : 0; + } + } +}; + +static ClosureParam *closure_bsdf_principled_hair_params() +{ + static ClosureParam params[] = { + CLOSURE_FLOAT3_PARAM(PrincipledHairClosure, params.N), + CLOSURE_FLOAT3_PARAM(PrincipledHairClosure, params.sigma), + CLOSURE_FLOAT_PARAM(PrincipledHairClosure, params.v), + CLOSURE_FLOAT_PARAM(PrincipledHairClosure, params.s), + CLOSURE_FLOAT_PARAM(PrincipledHairClosure, params.m0_roughness), + CLOSURE_FLOAT_PARAM(PrincipledHairClosure, params.alpha), + CLOSURE_FLOAT_PARAM(PrincipledHairClosure, params.eta), + CLOSURE_STRING_KEYPARAM(PrincipledHairClosure, label, "label"), + CLOSURE_FINISH_PARAM(PrincipledHairClosure) + }; + + return params; +} + +CCLOSURE_PREPARE(closure_bsdf_principled_hair_prepare, PrincipledHairClosure) + /* DISNEY PRINCIPLED CLEARCOAT */ class PrincipledClearcoatClosure : public CBSDFClosure { public: @@ -322,6 +376,9 @@ void OSLShader::register_closures(OSLShadingSystem *ss_) register_closure(ss, "hair_transmission", id++, bsdf_hair_transmission_params(), bsdf_hair_transmission_prepare); + register_closure(ss, "principled_hair", id++, + closure_bsdf_principled_hair_params(), closure_bsdf_principled_hair_prepare); + register_closure(ss, "henyey_greenstein", id++, closure_henyey_greenstein_params(), closure_henyey_greenstein_prepare); register_closure(ss, "absorption", id++, @@ -770,4 +827,3 @@ CCLOSURE_PREPARE(closure_henyey_greenstein_prepare, VolumeHenyeyGreensteinClosur CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/osl_closures.h b/intern/cycles/kernel/osl/osl_closures.h index 68dfa9a46504..d9aeb9ab9fb2 100644 --- a/intern/cycles/kernel/osl/osl_closures.h +++ b/intern/cycles/kernel/osl/osl_closures.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -79,6 +79,7 @@ void closure_bsdf_microfacet_multi_ggx_fresnel_prepare(OSL::RendererServices *, void closure_bsdf_microfacet_multi_ggx_glass_fresnel_prepare(OSL::RendererServices *, int id, void *data); void closure_bsdf_microfacet_multi_ggx_aniso_fresnel_prepare(OSL::RendererServices *, int id, void *data); void closure_bsdf_principled_clearcoat_prepare(OSL::RendererServices *, int id, void *data); +void closure_bsdf_principled_hair_prepare(OSL::RendererServices *, int id, void *data); #define CCLOSURE_PREPARE(name, classname) \ void name(RendererServices *, int id, void *data) \ @@ -146,4 +147,3 @@ CCLOSURE_PREPARE_STATIC(bsdf_##lower##_prepare, Upper##Closure) CCL_NAMESPACE_END #endif /* __OSL_CLOSURES_H__ */ - diff --git a/intern/cycles/kernel/osl/osl_globals.h b/intern/cycles/kernel/osl/osl_globals.h index 9585d9f48254..30b29793e2dd 100644 --- a/intern/cycles/kernel/osl/osl_globals.h +++ b/intern/cycles/kernel/osl/osl_globals.h @@ -95,4 +95,3 @@ CCL_NAMESPACE_END #endif #endif /* __OSL_GLOBALS_H__ */ - diff --git a/intern/cycles/kernel/osl/osl_services.cpp b/intern/cycles/kernel/osl/osl_services.cpp index 4b7a4cb34b7d..7902381440bd 100644 --- a/intern/cycles/kernel/osl/osl_services.cpp +++ b/intern/cycles/kernel/osl/osl_services.cpp @@ -364,7 +364,7 @@ bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to) { KernelGlobals *kg = kernel_globals; - + if(to == u_ndc) { copy_matrix(result, kernel_data.cam.worldtondc); return true; @@ -381,11 +381,11 @@ bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 copy_matrix(result, kernel_data.cam.worldtocamera); return true; } - + return false; } -bool OSLRenderServices::get_array_attribute(OSL::ShaderGlobals *sg, bool derivatives, +bool OSLRenderServices::get_array_attribute(OSL::ShaderGlobals *sg, bool derivatives, ustring object, TypeDesc type, ustring name, int index, void *val) { @@ -684,7 +684,7 @@ bool OSLRenderServices::get_object_standard_attribute(KernelGlobals *kg, ShaderD float3 f = particle_angular_velocity(kg, particle_id); return set_attribute_float3(f, type, derivatives, val); } - + /* Geometry Attributes */ else if(name == u_geom_numpolyvertices) { return set_attribute_int(3, type, derivatives, val); @@ -873,7 +873,7 @@ bool OSLRenderServices::get_attribute(ShaderData *sd, bool derivatives, ustring return false; } -bool OSLRenderServices::get_userdata(bool derivatives, ustring name, TypeDesc type, +bool OSLRenderServices::get_userdata(bool derivatives, ustring name, TypeDesc type, OSL::ShaderGlobals *sg, void *val) { return false; /* disabled by lockgeom */ diff --git a/intern/cycles/kernel/osl/osl_services.h b/intern/cycles/kernel/osl/osl_services.h index 1a40e2ece2ba..50044746fd10 100644 --- a/intern/cycles/kernel/osl/osl_services.h +++ b/intern/cycles/kernel/osl/osl_services.h @@ -45,18 +45,18 @@ class OSLRenderServices : public OSL::RendererServices public: OSLRenderServices(); ~OSLRenderServices(); - + void thread_init(KernelGlobals *kernel_globals, OSL::TextureSystem *ts); bool get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time); bool get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time); - + bool get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from, float time); bool get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to, float time); - + bool get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform); bool get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform); - + bool get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from); bool get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from); @@ -195,4 +195,3 @@ class OSLRenderServices : public OSL::RendererServices CCL_NAMESPACE_END #endif /* __OSL_SERVICES_H__ */ - diff --git a/intern/cycles/kernel/osl/osl_shader.cpp b/intern/cycles/kernel/osl/osl_shader.cpp index b7d1c6292919..6a690e880ad2 100644 --- a/intern/cycles/kernel/osl/osl_shader.cpp +++ b/intern/cycles/kernel/osl/osl_shader.cpp @@ -115,7 +115,7 @@ static void shaderdata_to_shaderglobals(KernelGlobals *kg, ShaderData *sd, PathS globals->backfacing = (sd->flag & SD_BACKFACING); /* shader data to be used in services callbacks */ - globals->renderstate = sd; + globals->renderstate = sd; /* hacky, we leave it to services to fetch actual object matrix */ globals->shader2common = sd; @@ -340,7 +340,7 @@ void OSLShader::eval_volume(KernelGlobals *kg, ShaderData *sd, PathState *state, if(kg->osl->volume_state[shader]) { ss->execute(octx, *(kg->osl->volume_state[shader]), *globals); } - + /* flatten closure tree */ if(globals->Ci) flatten_volume_closure_tree(sd, globals->Ci); @@ -405,4 +405,3 @@ int OSLShader::find_attribute(KernelGlobals *kg, const ShaderData *sd, uint id, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/osl/osl_shader.h b/intern/cycles/kernel/osl/osl_shader.h index 6b392b25cf77..571a3f502be6 100644 --- a/intern/cycles/kernel/osl/osl_shader.h +++ b/intern/cycles/kernel/osl/osl_shader.h @@ -67,4 +67,3 @@ CCL_NAMESPACE_END #endif #endif /* __OSL_SHADER_H__ */ - diff --git a/intern/cycles/kernel/shaders/CMakeLists.txt b/intern/cycles/kernel/shaders/CMakeLists.txt index b28d017c1c25..4740db27d4e3 100644 --- a/intern/cycles/kernel/shaders/CMakeLists.txt +++ b/intern/cycles/kernel/shaders/CMakeLists.txt @@ -85,6 +85,7 @@ set(SRC_OSL node_wave_texture.osl node_wireframe.osl node_hair_bsdf.osl + node_principled_hair_bsdf.osl node_uv_map.osl node_principled_bsdf.osl node_rgb_to_bw.osl @@ -110,7 +111,7 @@ foreach(_file ${SRC_OSL}) string(REPLACE ".osl" ".oso" _OSO_FILE ${_OSL_FILE}) string(REPLACE ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} _OSO_FILE ${_OSO_FILE}) add_custom_command( - OUTPUT ${_OSO_FILE} + OUTPUT ${_OSO_FILE} COMMAND ${OSL_COMPILER} -q -O2 -I"${CMAKE_CURRENT_SOURCE_DIR}" -o ${_OSO_FILE} ${_OSL_FILE} DEPENDS ${_OSL_FILE} ${SRC_OSL_HEADERS} ${OSL_COMPILER}) list(APPEND SRC_OSO @@ -127,4 +128,3 @@ cycles_set_solution_folder(cycles_osl_shaders) # CMAKE_CURRENT_SOURCE_DIR is already included in OSO paths delayed_install("" "${SRC_OSO}" ${CYCLES_INSTALL_PATH}/shader) delayed_install("${CMAKE_CURRENT_SOURCE_DIR}" "${SRC_OSL_HEADERS}" ${CYCLES_INSTALL_PATH}/shader) - diff --git a/intern/cycles/kernel/shaders/node_ambient_occlusion.osl b/intern/cycles/kernel/shaders/node_ambient_occlusion.osl index d7ffa3c1606f..825cccd59ce4 100644 --- a/intern/cycles/kernel/shaders/node_ambient_occlusion.osl +++ b/intern/cycles/kernel/shaders/node_ambient_occlusion.osl @@ -17,13 +17,13 @@ #include "stdosl.h" shader node_ambient_occlusion( - color ColorIn = color(0.8, 0.8, 0.8), - int samples = 8, + color ColorIn = color(1.0, 1.0, 1.0), + int samples = 16, float Distance = 1.0, normal Normal = N, int inside = 0, - int only_local = 1, - output color ColorOut = color(0.8, 0.8, 0.8), + int only_local = 0, + output color ColorOut = color(1.0, 1.0, 1.0), output float AO = 1.0) { int global_radius = (Distance == 0.0 && !isconnected(Distance)); diff --git a/intern/cycles/kernel/shaders/node_bump.osl b/intern/cycles/kernel/shaders/node_bump.osl index 7f01cf2ca919..a2a4468d5f3d 100644 --- a/intern/cycles/kernel/shaders/node_bump.osl +++ b/intern/cycles/kernel/shaders/node_bump.osl @@ -64,5 +64,7 @@ surface node_bump( if (use_object_space) { NormalOut = normalize(transform("object", "world", NormalOut)); } + + NormalOut = ensure_valid_reflection(Ng, I, NormalOut); } diff --git a/intern/cycles/kernel/shaders/node_color.h b/intern/cycles/kernel/shaders/node_color.h index 2c3a810cb18a..fc758bef1fa0 100644 --- a/intern/cycles/kernel/shaders/node_color.h +++ b/intern/cycles/kernel/shaders/node_color.h @@ -131,7 +131,7 @@ color hsv_to_rgb(color hsv) else { if (h == 1.0) h = 0.0; - + h *= 6.0; i = floor(h); f = h - i; @@ -150,4 +150,3 @@ color hsv_to_rgb(color hsv) return rgb; } - diff --git a/intern/cycles/kernel/shaders/node_fresnel.h b/intern/cycles/kernel/shaders/node_fresnel.h index de2d40a849c5..fcb0efa84456 100644 --- a/intern/cycles/kernel/shaders/node_fresnel.h +++ b/intern/cycles/kernel/shaders/node_fresnel.h @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + float fresnel_dielectric_cos(float cosi, float eta) { /* compute fresnel reflectance without explicitly computing @@ -46,4 +46,3 @@ color fresnel_conductor(float cosi, color eta, color k) (tmp_f + (2.0 * eta * cosi) + cosi2); return (Rparl2 + Rperp2) * 0.5; } - diff --git a/intern/cycles/kernel/shaders/node_math.osl b/intern/cycles/kernel/shaders/node_math.osl index c5fcbc311d35..aa9f6e671c36 100644 --- a/intern/cycles/kernel/shaders/node_math.osl +++ b/intern/cycles/kernel/shaders/node_math.osl @@ -40,6 +40,18 @@ float safe_modulo(float a, float b) return result; } +float safe_sqrt(float a) +{ + float result; + + if (a > 0.0) + result = sqrt(a); + else + result = 0.0; + + return result; +} + float safe_log(float a, float b) { if (a < 0.0 || b < 0.0) @@ -97,6 +109,14 @@ shader node_math( Value = fabs(Value1); else if (type == "arctan2") Value = atan2(Value1, Value2); + else if (type == "floor") + Value = floor(Value1); + else if (type == "ceil") + Value = ceil(Value1); + else if (type == "fract") + Value = Value1 - floor(Value1); + else if (type == "sqrt") + Value = safe_sqrt(Value1); if (use_clamp) Value = clamp(Value, 0.0, 1.0); diff --git a/intern/cycles/kernel/shaders/node_normal_map.osl b/intern/cycles/kernel/shaders/node_normal_map.osl index 41bcac4fb101..fda6f12a5daf 100644 --- a/intern/cycles/kernel/shaders/node_normal_map.osl +++ b/intern/cycles/kernel/shaders/node_normal_map.osl @@ -88,5 +88,7 @@ shader node_normal_map( if (Strength != 1.0) Normal = normalize(NormalIn + (Normal - NormalIn) * max(Strength, 0.0)); + + Normal = ensure_valid_reflection(Ng, I, Normal); } diff --git a/intern/cycles/kernel/shaders/node_principled_hair_bsdf.osl b/intern/cycles/kernel/shaders/node_principled_hair_bsdf.osl new file mode 100644 index 000000000000..757a88f8ecee --- /dev/null +++ b/intern/cycles/kernel/shaders/node_principled_hair_bsdf.osl @@ -0,0 +1,105 @@ +/* + * Copyright 2018 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stdosl.h" + +color log3(color a) +{ + return color(log(a[0]), log(a[1]), log(a[2])); +} + +color sigma_from_concentration(float eumelanin, float pheomelanin) +{ + return eumelanin*color(0.506, 0.841, 1.653) + pheomelanin*color(0.343, 0.733, 1.924); +} + +color sigma_from_reflectance(color c, float azimuthal_roughness) +{ + float x = azimuthal_roughness; + float roughness_fac = (((((0.245*x) + 5.574)*x - 10.73)*x + 2.532)*x - 0.215)*x + 5.969; + color sigma = log3(c) / roughness_fac; + return sigma * sigma; +} + +shader node_principled_hair_bsdf( + color Color = color(0.017513, 0.005763, 0.002059), + float Melanin = 0.8, + float MelaninRedness = 1.0, + float RandomColor = 0.0, + color Tint = 1.0, + color AbsorptionCoefficient = color(0.245531, 0.52, 1.365), + normal Normal = Ng, + string parametrization = "Absorption coefficient", + float Offset = radians(2), + float Roughness = 0.3, + float RadialRoughness = 0.3, + float RandomRoughness = 0.0, + float Coat = 0.0, + float IOR = 1.55, + string AttrRandom = "geom:curve_random", + float Random = 0.0, + + output closure color BSDF = 0) +{ + /* Get random value from curve in none is specified. */ + float random_value = 0.0; + + if (isconnected(Random)) { + random_value = Random; + } + else { + getattribute(AttrRandom, random_value); + } + + /* Compute roughness. */ + float factor_random_roughness = 1.0 + 2.0*(random_value - 0.5)*RandomRoughness; + float m0_roughness = 1.0 - clamp(Coat, 0.0, 1.0); + float roughness = Roughness*factor_random_roughness; + float radial_roughness = RadialRoughness*factor_random_roughness; + + /* Compute absorption. */ + color sigma; + + if (parametrization == "Absorption coefficient") { + sigma = AbsorptionCoefficient; + } + else if (parametrization == "Melanin concentration") { + /* Randomize melanin. */ + float factor_random_color = 1.0 + 2.0*(random_value - 0.5) * RandomColor; + float melanin = Melanin * factor_random_color; + + /* Map melanin 0..inf from more perceptually linear 0..1. */ + melanin = -log(max(1.0 - melanin, 0.0001)); + + /* Benedikt Bitterli's melanin ratio remapping. */ + float eumelanin = melanin * (1.0 - MelaninRedness); + float pheomelanin = melanin * MelaninRedness; + color melanin_sigma = sigma_from_concentration(eumelanin, pheomelanin); + + /* Optional tint. */ + color tint_sigma = sigma_from_reflectance(Tint, radial_roughness); + sigma = melanin_sigma + tint_sigma; + } + else if (parametrization == "Direct coloring"){ + sigma = sigma_from_reflectance(Color, radial_roughness); + } + else { + /* Fallback to brownish hair, same as defaults for melanin. */ + sigma = sigma_from_concentration(0.0, 0.8054375); + } + + BSDF = principled_hair(Normal, sigma, roughness, radial_roughness, m0_roughness, Offset, IOR); +} diff --git a/intern/cycles/kernel/shaders/node_ramp_util.h b/intern/cycles/kernel/shaders/node_ramp_util.h index 917fb65c6dff..d07d5a98316a 100644 --- a/intern/cycles/kernel/shaders/node_ramp_util.h +++ b/intern/cycles/kernel/shaders/node_ramp_util.h @@ -84,6 +84,6 @@ float rgb_ramp_lookup(float ramp[], float at, int interpolate, int extrapolate) if (interpolate && t > 0.0) result = (1.0 - t) * result + t * ramp[i + 1]; - + return result; } diff --git a/intern/cycles/kernel/shaders/node_texture.h b/intern/cycles/kernel/shaders/node_texture.h index fc2cfdcd55cc..88305fb320f4 100644 --- a/intern/cycles/kernel/shaders/node_texture.h +++ b/intern/cycles/kernel/shaders/node_texture.h @@ -90,11 +90,11 @@ void voronoi(point p, float e, float da[4], point pa[4]) float safe_noise(point p, string type) { float f = 0.0; - + /* Perlin noise in range -1..1 */ if (type == "signed") f = noise("perlin", p); - + /* Perlin noise in range 0..1 */ else f = noise(p); @@ -102,7 +102,7 @@ float safe_noise(point p, string type) /* can happen for big coordinates, things even out to 0.5 then anyway */ if (!isfinite(f)) return 0.5; - + return f; } @@ -114,7 +114,7 @@ float noise_turbulence(point p, float details, int hard) float amp = 1.0; float sum = 0.0; int i, n; - + float octaves = clamp(details, 0.0, 16.0); n = (int)octaves; @@ -128,7 +128,7 @@ float noise_turbulence(point p, float details, int hard) amp *= 0.5; fscale *= 2.0; } - + float rmd = octaves - floor(octaves); if (rmd != 0.0) { @@ -160,7 +160,6 @@ float nonzero(float f, float eps) r = sign(f) * eps; else r = f; - + return r; } - diff --git a/intern/cycles/kernel/shaders/node_voronoi_texture.osl b/intern/cycles/kernel/shaders/node_voronoi_texture.osl index 0c3b95ae4d09..2e47d74a414f 100644 --- a/intern/cycles/kernel/shaders/node_voronoi_texture.osl +++ b/intern/cycles/kernel/shaders/node_voronoi_texture.osl @@ -17,12 +17,93 @@ #include "stdosl.h" #include "node_texture.h" +void voronoi_m(point p, string metric, float e, float da[4], point pa[4]) +{ + /* Compute the distance to and the position of the four closest neighbors to p. + * + * The neighbors are randomly placed, 1 each in a 3x3x3 grid (Worley pattern). + * The distances and points are returned in ascending order, i.e. da[0] and pa[0] will + * contain the distance to the closest point and its coordinates respectively. + */ + int xx, yy, zz, xi, yi, zi; + + xi = (int)floor(p[0]); + yi = (int)floor(p[1]); + zi = (int)floor(p[2]); + + da[0] = 1e10; + da[1] = 1e10; + da[2] = 1e10; + da[3] = 1e10; + + for (xx = xi - 1; xx <= xi + 1; xx++) { + for (yy = yi - 1; yy <= yi + 1; yy++) { + for (zz = zi - 1; zz <= zi + 1; zz++) { + point ip = point(xx, yy, zz); + point vp = (point)cellnoise_color(ip); + point pd = p - (vp + ip); + + float d = 0.0; + if (metric == "distance") { + d = dot(pd, pd); + } + else if (metric == "manhattan") { + d = fabs(pd[0]) + fabs(pd[1]) + fabs(pd[2]); + } + else if (metric == "chebychev") { + d = max(fabs(pd[0]), max(fabs(pd[1]), fabs(pd[2]))); + } + else if (metric == "minkowski") { + d = pow(pow(fabs(pd[0]), e) + pow(fabs(pd[1]), e) + pow(fabs(pd[2]), e), 1.0/e); + } + + vp += point(xx, yy, zz); + + if (d < da[0]) { + da[3] = da[2]; + da[2] = da[1]; + da[1] = da[0]; + da[0] = d; + + pa[3] = pa[2]; + pa[2] = pa[1]; + pa[1] = pa[0]; + pa[0] = vp; + } + else if (d < da[1]) { + da[3] = da[2]; + da[2] = da[1]; + da[1] = d; + + pa[3] = pa[2]; + pa[2] = pa[1]; + pa[1] = vp; + } + else if (d < da[2]) { + da[3] = da[2]; + da[2] = d; + + pa[3] = pa[2]; + pa[2] = vp; + } + else if (d < da[3]) { + da[3] = d; + pa[3] = vp; + } + } + } + } +} + /* Voronoi */ shader node_voronoi_texture( int use_mapping = 0, matrix mapping = matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), string coloring = "intensity", + string metric = "distance", + string feature = "F1", + float Exponent = 1.0, float Scale = 5.0, point Vector = P, output float Fac = 0.0, @@ -37,17 +118,48 @@ shader node_voronoi_texture( float da[4]; point pa[4]; - voronoi(p * Scale, 1.0, da, pa); + /* compute distance and point coordinate of 4 nearest neighbours */ + voronoi_m(p * Scale, metric, Exponent, da, pa); - /* Colored output */ if (coloring == "intensity") { - Fac = fabs(da[0]); + /* Intensity output */ + if (feature == "F1") { + Fac = fabs(da[0]); + } + else if (feature == "F2") { + Fac = fabs(da[1]); + } + else if (feature == "F3") { + Fac = fabs(da[2]); + } + else if (feature == "F4") { + Fac = fabs(da[3]); + } + else if (feature == "F2F1") { + Fac = fabs(da[1] - da[0]); + } Color = color(Fac); } else { - Color = cellnoise_color(pa[0]); - Fac = (Color[0] + Color[1] + Color[2]) * (1.0 / 3.0); + /* Color output */ + if (feature == "F1") { + Color = pa[0]; + } + else if (feature == "F2") { + Color = pa[1]; + } + else if (feature == "F3") { + Color = pa[2]; + } + else if (feature == "F4") { + Color = pa[3]; + } + else if (feature == "F2F1") { + Color = fabs(pa[1] - pa[0]); + } + Color = cellnoise_color(Color); + Fac = (Color[0] + Color[1] + Color[2]) * (1.0 / 3.0); } } diff --git a/intern/cycles/kernel/shaders/stdosl.h b/intern/cycles/kernel/shaders/stdosl.h index 091ade4a60d0..4a8378796ba4 100644 --- a/intern/cycles/kernel/shaders/stdosl.h +++ b/intern/cycles/kernel/shaders/stdosl.h @@ -213,7 +213,7 @@ void fresnel (vector I, normal N, float eta, F *= sqr (beta / (g+c)); Kr = F; Kt = (1.0 - Kr) * eta*eta; - // OPT: the following recomputes some of the above values, but it + // OPT: the following recomputes some of the above values, but it // gives us the same result as if the shader-writer called refract() T = refract(I, N, eta); } else { @@ -282,6 +282,36 @@ point rotate (point p, float angle, point a, point b) return transform (M, p-a) + a; } +normal ensure_valid_reflection(normal Ng, vector I, normal N) +{ + float sqr(float x) { return x*x; } + + vector R = 2*dot(N, I)*N - I; + if (dot(Ng, R) >= 0.05) { + return N; + } + + /* Form coordinate system with Ng as the Z axis and N inside the X-Z-plane. + * The X axis is found by normalizing the component of N that's orthogonal to Ng. + * The Y axis isn't actually needed. + */ + vector X = normalize(N - dot(N, Ng)*Ng); + + /* Calculate N.z and N.x in the local coordinate system. */ + float Ix = dot(I, X), Iz = dot(I, Ng); + float Ix2 = sqr(dot(I, X)), Iz2 = sqr(dot(I, Ng)); + float Ix2Iz2 = Ix2 + Iz2; + + float a = sqrt(Ix2*(Ix2Iz2 - sqr(0.05))); + float b = Iz*0.05 + Ix2Iz2; + float c = (a + b > 0.0)? (a + b) : (-a + b); + + float Nz = sqrt(0.5 * c * (1.0 / Ix2Iz2)); + float Nx = sqrt(1.0 - sqr(Nz)); + + /* Transform back into global coordinates. */ + return Nx*X + Nz*Ng; +} // Color functions @@ -415,7 +445,7 @@ color transformc (string from, string to, color x) return transformc (to, r); } - + // Matrix functions @@ -554,6 +584,7 @@ closure color bssrdf(string method, normal N, vector radius, color albedo) BUILT // Hair closure color hair_reflection(normal N, float roughnessu, float roughnessv, vector T, float offset) BUILTIN; closure color hair_transmission(normal N, float roughnessu, float roughnessv, vector T, float offset) BUILTIN; +closure color principled_hair(normal N, color sigma, float roughnessu, float roughnessv, float coat, float alpha, float eta) BUILTIN; // Volume closure color henyey_greenstein(float g) BUILTIN; diff --git a/intern/cycles/kernel/split/kernel_branched.h b/intern/cycles/kernel/split/kernel_branched.h index 368a4395760c..ed0a82067f1c 100644 --- a/intern/cycles/kernel/split/kernel_branched.h +++ b/intern/cycles/kernel/split/kernel_branched.h @@ -231,4 +231,3 @@ ccl_device_noinline bool kernel_split_branched_path_surface_indirect_light_iter( #endif /* __BRANCHED_PATH__ */ CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/split/kernel_lamp_emission.h b/intern/cycles/kernel/split/kernel_lamp_emission.h index c14f66f664f8..5b2c554b922b 100644 --- a/intern/cycles/kernel/split/kernel_lamp_emission.h +++ b/intern/cycles/kernel/split/kernel_lamp_emission.h @@ -65,4 +65,3 @@ ccl_device void kernel_lamp_emission(KernelGlobals *kg) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/split/kernel_shadow_blocked_ao.h b/intern/cycles/kernel/split/kernel_shadow_blocked_ao.h index a4cffd77eff9..fb08112503a0 100644 --- a/intern/cycles/kernel/split/kernel_shadow_blocked_ao.h +++ b/intern/cycles/kernel/split/kernel_shadow_blocked_ao.h @@ -52,4 +52,3 @@ ccl_device void kernel_shadow_blocked_ao(KernelGlobals *kg) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm.h b/intern/cycles/kernel/svm/svm.h index 10d5fe0e42b7..ab69afa051e9 100644 --- a/intern/cycles/kernel/svm/svm.h +++ b/intern/cycles/kernel/svm/svm.h @@ -144,7 +144,6 @@ CCL_NAMESPACE_END #include "kernel/svm/svm_color_util.h" #include "kernel/svm/svm_math_util.h" -#include "kernel/svm/svm_ao.h" #include "kernel/svm/svm_attribute.h" #include "kernel/svm/svm_gradient.h" #include "kernel/svm/svm_blackbody.h" @@ -185,6 +184,7 @@ CCL_NAMESPACE_END #include "kernel/svm/svm_bump.h" #ifdef __SHADER_RAYTRACE__ +# include "kernel/svm/svm_ao.h" # include "kernel/svm/svm_bevel.h" #endif @@ -498,4 +498,3 @@ ccl_device_noinline void svm_eval_nodes(KernelGlobals *kg, ShaderData *sd, ccl_a CCL_NAMESPACE_END #endif /* __SVM_H__ */ - diff --git a/intern/cycles/kernel/svm/svm_ao.h b/intern/cycles/kernel/svm/svm_ao.h index 3f761627e2c0..0337c88a5434 100644 --- a/intern/cycles/kernel/svm/svm_ao.h +++ b/intern/cycles/kernel/svm/svm_ao.h @@ -30,7 +30,7 @@ ccl_device_noinline float svm_ao(KernelGlobals *kg, /* Early out if no sampling needed. */ if(max_dist <= 0.0f || num_samples < 1 || sd->object == OBJECT_NONE) { - return 0.0f; + return 1.0f; } if(flags & NODE_AO_INSIDE) { @@ -98,11 +98,11 @@ ccl_device void svm_node_ao(KernelGlobals *kg, float3 normal = stack_valid(normal_offset)? stack_load_float3(stack, normal_offset): sd->N; float ao = svm_ao(kg, sd, normal, state, dist, samples, flags); - if (stack_valid(out_ao_offset)) { + if(stack_valid(out_ao_offset)) { stack_store_float(stack, out_ao_offset, ao); } - if (stack_valid(out_color_offset)) { + if(stack_valid(out_color_offset)) { float3 color = stack_load_float3(stack, color_offset); stack_store_float3(stack, out_color_offset, ao * color); } diff --git a/intern/cycles/kernel/svm/svm_attribute.h b/intern/cycles/kernel/svm/svm_attribute.h index 229a3f204211..d98f538d0894 100644 --- a/intern/cycles/kernel/svm/svm_attribute.h +++ b/intern/cycles/kernel/svm/svm_attribute.h @@ -154,4 +154,3 @@ void svm_node_attr_bump_dy(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_bevel.h b/intern/cycles/kernel/svm/svm_bevel.h index 89f4a98e846d..79d0fb6ddbec 100644 --- a/intern/cycles/kernel/svm/svm_bevel.h +++ b/intern/cycles/kernel/svm/svm_bevel.h @@ -148,11 +148,11 @@ ccl_device_noinline float3 svm_bevel( int prim = kernel_tex_fetch(__prim_index, isect.hits[hit].prim); int shader = kernel_tex_fetch(__tri_shader, prim); - if (shader & SHADER_SMOOTH_NORMAL) { + if(shader & SHADER_SMOOTH_NORMAL) { float u = isect.hits[hit].u; float v = isect.hits[hit].v; - if (sd->type & PRIMITIVE_TRIANGLE) { + if(sd->type & PRIMITIVE_TRIANGLE) { N = triangle_smooth_normal(kg, N, prim, u, v); } #ifdef __OBJECT_MOTION__ @@ -223,4 +223,3 @@ ccl_device void svm_node_bevel( } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_brick.h b/intern/cycles/kernel/svm/svm_brick.h index 90fa2a99b67c..744d9ff16c55 100644 --- a/intern/cycles/kernel/svm/svm_brick.h +++ b/intern/cycles/kernel/svm/svm_brick.h @@ -36,7 +36,7 @@ ccl_device_noinline float2 svm_brick(float3 p, float mortar_size, float mortar_s float x, y; rownum = floor_to_int(p.y / row_height); - + if(offset_frequency && squash_frequency) { brick_width *= (rownum % squash_frequency) ? 1.0f : squash_amount; /* squash */ offset = (rownum % offset_frequency) ? 0.0f : (brick_width*offset_amount); /* offset */ @@ -66,31 +66,31 @@ ccl_device_noinline float2 svm_brick(float3 p, float mortar_size, float mortar_s } ccl_device void svm_node_tex_brick(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node, int *offset) -{ +{ uint4 node2 = read_node(kg, offset); uint4 node3 = read_node(kg, offset); uint4 node4 = read_node(kg, offset); - + /* Input and Output Sockets */ uint co_offset, color1_offset, color2_offset, mortar_offset, scale_offset; uint mortar_size_offset, bias_offset, brick_width_offset, row_height_offset; uint color_offset, fac_offset, mortar_smooth_offset; - + /* RNA properties */ uint offset_frequency, squash_frequency; - + decode_node_uchar4(node.y, &co_offset, &color1_offset, &color2_offset, &mortar_offset); decode_node_uchar4(node.z, &scale_offset, &mortar_size_offset, &bias_offset, &brick_width_offset); decode_node_uchar4(node.w, &row_height_offset, &color_offset, &fac_offset, &mortar_smooth_offset); - + decode_node_uchar4(node2.x, &offset_frequency, &squash_frequency, NULL, NULL); float3 co = stack_load_float3(stack, co_offset); - + float3 color1 = stack_load_float3(stack, color1_offset); float3 color2 = stack_load_float3(stack, color2_offset); float3 mortar = stack_load_float3(stack, mortar_offset); - + float scale = stack_load_float_default(stack, scale_offset, node2.y); float mortar_size = stack_load_float_default(stack, mortar_size_offset, node2.z); float mortar_smooth = stack_load_float_default(stack, mortar_smooth_offset, node4.x); @@ -99,13 +99,13 @@ ccl_device void svm_node_tex_brick(KernelGlobals *kg, ShaderData *sd, float *sta float row_height = stack_load_float_default(stack, row_height_offset, node3.y); float offset_amount = __int_as_float(node3.z); float squash_amount = __int_as_float(node3.w); - + float2 f2 = svm_brick(co*scale, mortar_size, mortar_smooth, bias, brick_width, row_height, offset_amount, offset_frequency, squash_amount, squash_frequency); float tint = f2.x; float f = f2.y; - + if(f != 1.0f) { float facm = 1.0f - tint; color1 = facm * color1 + tint * color2; @@ -118,4 +118,3 @@ ccl_device void svm_node_tex_brick(KernelGlobals *kg, ShaderData *sd, float *sta } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_bump.h b/intern/cycles/kernel/svm/svm_bump.h index 610d9af9e1f3..1c1fe1555384 100644 --- a/intern/cycles/kernel/svm/svm_bump.h +++ b/intern/cycles/kernel/svm/svm_bump.h @@ -51,4 +51,3 @@ ccl_device void svm_node_leave_bump_eval(KernelGlobals *kg, ShaderData *sd, floa } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_camera.h b/intern/cycles/kernel/svm/svm_camera.h index 90249dfd978d..cf90229b53b6 100644 --- a/intern/cycles/kernel/svm/svm_camera.h +++ b/intern/cycles/kernel/svm/svm_camera.h @@ -38,4 +38,3 @@ ccl_device void svm_node_camera(KernelGlobals *kg, ShaderData *sd, float *stack, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_checker.h b/intern/cycles/kernel/svm/svm_checker.h index cea245991de1..45e6c181e9ed 100644 --- a/intern/cycles/kernel/svm/svm_checker.h +++ b/intern/cycles/kernel/svm/svm_checker.h @@ -33,7 +33,7 @@ ccl_device_noinline float svm_checker(float3 p) } ccl_device void svm_node_tex_checker(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node) -{ +{ uint co_offset, color1_offset, color2_offset, scale_offset; uint color_offset, fac_offset; @@ -44,7 +44,7 @@ ccl_device void svm_node_tex_checker(KernelGlobals *kg, ShaderData *sd, float *s float3 color1 = stack_load_float3(stack, color1_offset); float3 color2 = stack_load_float3(stack, color2_offset); float scale = stack_load_float_default(stack, scale_offset, node.w); - + float f = svm_checker(co*scale); if(stack_valid(color_offset)) @@ -54,4 +54,3 @@ ccl_device void svm_node_tex_checker(KernelGlobals *kg, ShaderData *sd, float *s } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_closure.h b/intern/cycles/kernel/svm/svm_closure.h index f5b316c67dab..cce0e0eefe0d 100644 --- a/intern/cycles/kernel/svm/svm_closure.h +++ b/intern/cycles/kernel/svm/svm_closure.h @@ -16,6 +16,21 @@ CCL_NAMESPACE_BEGIN +/* Hair Melanin */ + +ccl_device_inline float3 sigma_from_concentration(float eumelanin, float pheomelanin) +{ + return eumelanin*make_float3(0.506f, 0.841f, 1.653f) + pheomelanin*make_float3(0.343f, 0.733f, 1.924f); +} + +ccl_device_inline float3 sigma_from_reflectance(float3 color, float azimuthal_roughness) +{ + float x = azimuthal_roughness; + float roughness_fac = (((((0.245f*x) + 5.574f)*x - 10.73f)*x + 2.532f)*x - 0.215f)*x + 5.969f; + float3 sigma = log3(color) / roughness_fac; + return sigma * sigma; +} + /* Closure Nodes */ ccl_device void svm_node_glass_setup(ShaderData *sd, MicrofacetBsdf *bsdf, int type, float eta, float roughness, bool refract) @@ -130,7 +145,7 @@ ccl_device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float * // calculate weights of the diffuse and specular part float diffuse_weight = (1.0f - saturate(metallic)) * (1.0f - saturate(transmission)); - + float final_transmission = saturate(transmission) * (1.0f - saturate(metallic)); float specular_weight = (1.0f - final_transmission); @@ -243,7 +258,7 @@ ccl_device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float * float3 spec_weight = weight * specular_weight; MicrofacetBsdf *bsdf = (MicrofacetBsdf*)bsdf_alloc(sd, sizeof(MicrofacetBsdf), spec_weight); - if(!bsdf){ + if(!bsdf) { break; } @@ -713,7 +728,7 @@ ccl_device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float * bsdf->N = N; bsdf->size = param1; bsdf->smooth = param2; - + if(type == CLOSURE_BSDF_DIFFUSE_TOON_ID) sd->flag |= bsdf_diffuse_toon_setup(bsdf); else @@ -722,10 +737,111 @@ ccl_device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float * break; } #ifdef __HAIR__ + case CLOSURE_BSDF_HAIR_PRINCIPLED_ID: { + uint4 data_node2 = read_node(kg, offset); + uint4 data_node3 = read_node(kg, offset); + uint4 data_node4 = read_node(kg, offset); + + float3 weight = sd->svm_closure_weight * mix_weight; + + uint offset_ofs, ior_ofs, color_ofs, parametrization; + decode_node_uchar4(data_node.y, &offset_ofs, &ior_ofs, &color_ofs, ¶metrization); + float alpha = stack_load_float_default(stack, offset_ofs, data_node.z); + float ior = stack_load_float_default(stack, ior_ofs, data_node.w); + + uint coat_ofs, melanin_ofs, melanin_redness_ofs, absorption_coefficient_ofs; + decode_node_uchar4(data_node2.x, &coat_ofs, &melanin_ofs, &melanin_redness_ofs, &absorption_coefficient_ofs); + + uint tint_ofs, random_ofs, random_color_ofs, random_roughness_ofs; + decode_node_uchar4(data_node3.x, &tint_ofs, &random_ofs, &random_color_ofs, &random_roughness_ofs); + + const AttributeDescriptor attr_descr_random = find_attribute(kg, sd, data_node4.y); + float random = 0.0f; + if(attr_descr_random.offset != ATTR_STD_NOT_FOUND) { + random = primitive_attribute_float(kg, sd, attr_descr_random, NULL, NULL); + } + else { + random = stack_load_float_default(stack, random_ofs, data_node3.y); + } + + + PrincipledHairBSDF *bsdf = (PrincipledHairBSDF*)bsdf_alloc(sd, sizeof(PrincipledHairBSDF), weight); + if(bsdf) { + PrincipledHairExtra *extra = (PrincipledHairExtra*)closure_alloc_extra(sd, sizeof(PrincipledHairExtra)); + + if(!extra) + break; + + /* Random factors range: [-randomization/2, +randomization/2]. */ + float random_roughness = stack_load_float_default(stack, random_roughness_ofs, data_node3.w); + float factor_random_roughness = 1.0f + 2.0f*(random - 0.5f)*random_roughness; + float roughness = param1 * factor_random_roughness; + float radial_roughness = param2 * factor_random_roughness; + + /* Remap Coat value to [0, 100]% of Roughness. */ + float coat = stack_load_float_default(stack, coat_ofs, data_node2.y); + float m0_roughness = 1.0f - clamp(coat, 0.0f, 1.0f); + + bsdf->N = N; + bsdf->v = roughness; + bsdf->s = radial_roughness; + bsdf->m0_roughness = m0_roughness; + bsdf->alpha = alpha; + bsdf->eta = ior; + bsdf->extra = extra; + + switch(parametrization) { + case NODE_PRINCIPLED_HAIR_DIRECT_ABSORPTION: { + float3 absorption_coefficient = stack_load_float3(stack, absorption_coefficient_ofs); + bsdf->sigma = absorption_coefficient; + break; + } + case NODE_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION: { + float melanin = stack_load_float_default(stack, melanin_ofs, data_node2.z); + float melanin_redness = stack_load_float_default(stack, melanin_redness_ofs, data_node2.w); + + /* Randomize melanin. */ + float random_color = stack_load_float_default(stack, random_color_ofs, data_node3.z); + random_color = clamp(random_color, 0.0f, 1.0f); + float factor_random_color = 1.0f + 2.0f * (random - 0.5f) * random_color; + melanin *= factor_random_color; + + /* Map melanin 0..inf from more perceptually linear 0..1. */ + melanin = -logf(fmaxf(1.0f - melanin, 0.0001f)); + + /* Benedikt Bitterli's melanin ratio remapping. */ + float eumelanin = melanin * (1.0f - melanin_redness); + float pheomelanin = melanin * melanin_redness; + float3 melanin_sigma = sigma_from_concentration(eumelanin, pheomelanin); + + /* Optional tint. */ + float3 tint = stack_load_float3(stack, tint_ofs); + float3 tint_sigma = sigma_from_reflectance(tint, radial_roughness); + + bsdf->sigma = melanin_sigma + tint_sigma; + break; + } + case NODE_PRINCIPLED_HAIR_REFLECTANCE: { + float3 color = stack_load_float3(stack, color_ofs); + bsdf->sigma = sigma_from_reflectance(color, radial_roughness); + break; + } + default: { + /* Fallback to brownish hair, same as defaults for melanin. */ + kernel_assert(!"Invalid Principled Hair parametrization!"); + bsdf->sigma = sigma_from_concentration(0.0f, 0.8054375f); + break; + } + } + + sd->flag |= bsdf_principled_hair_setup(sd, bsdf); + } + break; + } case CLOSURE_BSDF_HAIR_REFLECTION_ID: case CLOSURE_BSDF_HAIR_TRANSMISSION_ID: { float3 weight = sd->svm_closure_weight * mix_weight; - + if(sd->flag & SD_BACKFACING && sd->type & PRIMITIVE_ALL_CURVE) { /* todo: giving a fixed weight here will cause issues when * mixing multiple BSDFS. energy will not be conserved and @@ -764,7 +880,7 @@ ccl_device void svm_node_closure_bsdf(KernelGlobals *kg, ShaderData *sd, float * break; } -#endif +#endif /* __HAIR__ */ #ifdef __SUBSURFACE__ case CLOSURE_BSSRDF_CUBIC_ID: @@ -1055,4 +1171,3 @@ ccl_device void svm_node_set_normal(KernelGlobals *kg, ShaderData *sd, float *st } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_color_util.h b/intern/cycles/kernel/svm/svm_color_util.h index 258cdeb630e7..d5945f915c6e 100644 --- a/intern/cycles/kernel/svm/svm_color_util.h +++ b/intern/cycles/kernel/svm/svm_color_util.h @@ -60,7 +60,7 @@ ccl_device float3 svm_mix_overlay(float t, float3 col1, float3 col2) outcol.z *= tm + 2.0f*t*col2.z; else outcol.z = 1.0f - (tm + 2.0f*t*(1.0f - col2.z))*(1.0f - outcol.z); - + return outcol; } @@ -167,7 +167,7 @@ ccl_device float3 svm_mix_burn(float t, float3 col1, float3 col2) outcol.z = 1.0f; else outcol.z = tmp; - + return outcol; } @@ -180,7 +180,7 @@ ccl_device float3 svm_mix_hue(float t, float3 col1, float3 col2) if(hsv2.y != 0.0f) { float3 hsv = rgb_to_hsv(outcol); hsv.x = hsv2.x; - float3 tmp = hsv_to_rgb(hsv); + float3 tmp = hsv_to_rgb(hsv); outcol = interp(outcol, tmp, t); } @@ -227,7 +227,7 @@ ccl_device float3 svm_mix_color(float t, float3 col1, float3 col2) float3 hsv = rgb_to_hsv(outcol); hsv.x = hsv2.x; hsv.y = hsv2.y; - float3 tmp = hsv_to_rgb(hsv); + float3 tmp = hsv_to_rgb(hsv); outcol = interp(outcol, tmp, t); } @@ -303,4 +303,3 @@ ccl_device_inline float3 svm_brightness_contrast(float3 color, float brightness, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_convert.h b/intern/cycles/kernel/svm/svm_convert.h index c88ac57e20d8..63b1dc6865e1 100644 --- a/intern/cycles/kernel/svm/svm_convert.h +++ b/intern/cycles/kernel/svm/svm_convert.h @@ -69,4 +69,3 @@ ccl_device void svm_node_convert(KernelGlobals *kg, ShaderData *sd, float *stack } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_displace.h b/intern/cycles/kernel/svm/svm_displace.h index 533b7f065e67..0f5b3abef87f 100644 --- a/intern/cycles/kernel/svm/svm_displace.h +++ b/intern/cycles/kernel/svm/svm_displace.h @@ -75,6 +75,8 @@ ccl_device void svm_node_set_bump(KernelGlobals *kg, ShaderData *sd, float *stac object_normal_transform(kg, sd, &normal_out); } + normal_out = ensure_valid_reflection(sd->Ng, sd->I, normal_out); + stack_store_float3(stack, node.w, normal_out); #endif } @@ -160,4 +162,3 @@ ccl_device void svm_node_vector_displacement(KernelGlobals *kg, ShaderData *sd, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_fresnel.h b/intern/cycles/kernel/svm/svm_fresnel.h index 3703ec550153..99dda5fb1702 100644 --- a/intern/cycles/kernel/svm/svm_fresnel.h +++ b/intern/cycles/kernel/svm/svm_fresnel.h @@ -24,7 +24,7 @@ ccl_device void svm_node_fresnel(ShaderData *sd, float *stack, uint ior_offset, decode_node_uchar4(node, &normal_offset, &out_offset, NULL, NULL); float eta = (stack_valid(ior_offset))? stack_load_float(stack, ior_offset): __uint_as_float(ior_value); float3 normal_in = stack_valid(normal_offset)? stack_load_float3(stack, normal_offset): sd->N; - + eta = fmaxf(eta, 1e-5f); eta = (sd->flag & SD_BACKFACING)? 1.0f/eta: eta; @@ -71,4 +71,3 @@ ccl_device void svm_node_layer_weight(ShaderData *sd, float *stack, uint4 node) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_geometry.h b/intern/cycles/kernel/svm/svm_geometry.h index 81308d6f12bf..05443772505a 100644 --- a/intern/cycles/kernel/svm/svm_geometry.h +++ b/intern/cycles/kernel/svm/svm_geometry.h @@ -208,4 +208,3 @@ ccl_device void svm_node_hair_info(KernelGlobals *kg, #endif CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_gradient.h b/intern/cycles/kernel/svm/svm_gradient.h index 74e36e70427d..177e0506deea 100644 --- a/intern/cycles/kernel/svm/svm_gradient.h +++ b/intern/cycles/kernel/svm/svm_gradient.h @@ -36,7 +36,7 @@ ccl_device float svm_gradient(float3 p, NodeGradientType type) else if(type == NODE_BLEND_EASING) { float r = fminf(fmaxf(x, 0.0f), 1.0f); float t = r*r; - + return (3.0f*t - 2.0f*t*r); } else if(type == NODE_BLEND_DIAGONAL) { @@ -78,4 +78,3 @@ ccl_device void svm_node_tex_gradient(ShaderData *sd, float *stack, uint4 node) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_hsv.h b/intern/cycles/kernel/svm/svm_hsv.h index 3a1840c12e25..27127b85323e 100644 --- a/intern/cycles/kernel/svm/svm_hsv.h +++ b/intern/cycles/kernel/svm/svm_hsv.h @@ -60,4 +60,3 @@ ccl_device void svm_node_hsv(KernelGlobals *kg, ShaderData *sd, float *stack, ui CCL_NAMESPACE_END #endif /* __SVM_HSV_H__ */ - diff --git a/intern/cycles/kernel/svm/svm_image.h b/intern/cycles/kernel/svm/svm_image.h index 285653088672..81ee79c984ea 100644 --- a/intern/cycles/kernel/svm/svm_image.h +++ b/intern/cycles/kernel/svm/svm_image.h @@ -203,4 +203,3 @@ ccl_device void svm_node_tex_environment(KernelGlobals *kg, ShaderData *sd, floa } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_invert.h b/intern/cycles/kernel/svm/svm_invert.h index 5ce858e2e5d5..57cc42811010 100644 --- a/intern/cycles/kernel/svm/svm_invert.h +++ b/intern/cycles/kernel/svm/svm_invert.h @@ -35,4 +35,3 @@ ccl_device void svm_node_invert(ShaderData *sd, float *stack, uint in_fac, uint } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_light_path.h b/intern/cycles/kernel/svm/svm_light_path.h index 1492e3586087..dd4390057cfb 100644 --- a/intern/cycles/kernel/svm/svm_light_path.h +++ b/intern/cycles/kernel/svm/svm_light_path.h @@ -74,4 +74,3 @@ ccl_device void svm_node_light_falloff(ShaderData *sd, float *stack, uint4 node) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_magic.h b/intern/cycles/kernel/svm/svm_magic.h index ac87c77d7196..6afaff37acdd 100644 --- a/intern/cycles/kernel/svm/svm_magic.h +++ b/intern/cycles/kernel/svm/svm_magic.h @@ -109,4 +109,3 @@ ccl_device void svm_node_tex_magic(KernelGlobals *kg, ShaderData *sd, float *sta } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_mapping.h b/intern/cycles/kernel/svm/svm_mapping.h index 42a7ae9946f4..861812838210 100644 --- a/intern/cycles/kernel/svm/svm_mapping.h +++ b/intern/cycles/kernel/svm/svm_mapping.h @@ -43,4 +43,3 @@ ccl_device void svm_node_min_max(KernelGlobals *kg, ShaderData *sd, float *stack } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_math.h b/intern/cycles/kernel/svm/svm_math.h index d633e54ed8d8..c9a838361cdc 100644 --- a/intern/cycles/kernel/svm/svm_math.h +++ b/intern/cycles/kernel/svm/svm_math.h @@ -47,4 +47,3 @@ ccl_device void svm_node_vector_math(KernelGlobals *kg, ShaderData *sd, float *s } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_math_util.h b/intern/cycles/kernel/svm/svm_math_util.h index caf0addbf35c..669b174e4a3e 100644 --- a/intern/cycles/kernel/svm/svm_math_util.h +++ b/intern/cycles/kernel/svm/svm_math_util.h @@ -94,11 +94,19 @@ ccl_device float svm_math(NodeMath type, float Fac1, float Fac2) Fac = fabsf(Fac1); else if(type == NODE_MATH_ARCTAN2) Fac = atan2f(Fac1, Fac2); + else if(type == NODE_MATH_FLOOR) + Fac = floorf(Fac1); + else if(type == NODE_MATH_CEIL) + Fac = ceilf(Fac1); + else if(type == NODE_MATH_FRACT) + Fac = Fac1 - floorf(Fac1); + else if(type == NODE_MATH_SQRT) + Fac = safe_sqrtf(Fac1); else if(type == NODE_MATH_CLAMP) Fac = saturate(Fac1); else Fac = 0.0f; - + return Fac; } @@ -180,4 +188,3 @@ ccl_device_inline float3 svm_math_gamma_color(float3 color, float gamma) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_mix.h b/intern/cycles/kernel/svm/svm_mix.h index 022a68d19287..903a4dacebf6 100644 --- a/intern/cycles/kernel/svm/svm_mix.h +++ b/intern/cycles/kernel/svm/svm_mix.h @@ -32,4 +32,3 @@ ccl_device void svm_node_mix(KernelGlobals *kg, ShaderData *sd, float *stack, ui } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_musgrave.h b/intern/cycles/kernel/svm/svm_musgrave.h index 09eba31945ea..5d9e12628ca0 100644 --- a/intern/cycles/kernel/svm/svm_musgrave.h +++ b/intern/cycles/kernel/svm/svm_musgrave.h @@ -193,7 +193,7 @@ ccl_device float svm_musgrave(NodeMusgraveType type, float dimension, float lacu return intensity*noise_musgrave_ridged_multi_fractal(p, dimension, lacunarity, octaves, offset, gain); else if(type == NODE_MUSGRAVE_HETERO_TERRAIN) return intensity*noise_musgrave_hetero_terrain(p, dimension, lacunarity, octaves, offset); - + return 0.0f; } @@ -232,4 +232,3 @@ ccl_device void svm_node_tex_musgrave(KernelGlobals *kg, ShaderData *sd, float * } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_noise.h b/intern/cycles/kernel/svm/svm_noise.h index 3f75ae5c04e1..8c425ecf3264 100644 --- a/intern/cycles/kernel/svm/svm_noise.h +++ b/intern/cycles/kernel/svm/svm_noise.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2011, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -32,12 +32,7 @@ CCL_NAMESPACE_BEGIN -#ifndef __KERNEL_SSE2__ -ccl_device int quick_floor(float x) -{ - return float_to_int(x) - ((x < 0) ? 1 : 0); -} -#else +#ifdef __KERNEL_SSE2__ ccl_device_inline ssei quick_floor_sse(const ssef& x) { ssei b = truncatei(x); @@ -46,18 +41,6 @@ ccl_device_inline ssei quick_floor_sse(const ssef& x) } #endif -#ifndef __KERNEL_SSE2__ -ccl_device float bits_to_01(uint bits) -{ - return bits * (1.0f/(float)0xFFFFFFFF); -} -#else -ccl_device_inline ssef bits_to_01_sse(const ssei& bits) -{ - return uint32_to_float(bits) * ssef(1.0f/(float)0xFFFFFFFF); -} -#endif - ccl_device uint hash(uint kx, uint ky, uint kz) { // define some handy macros @@ -120,7 +103,7 @@ ccl_device int imod(int a, int b) return a < 0 ? a + b : a; } -ccl_device uint phash(int kx, int ky, int kz, int3 p) +ccl_device uint phash(int kx, int ky, int kz, int3 p) { return hash(imod(kx, p.x), imod(ky, p.y), imod(kz, p.z)); } @@ -129,7 +112,7 @@ ccl_device uint phash(int kx, int ky, int kz, int3 p) #ifndef __KERNEL_SSE2__ ccl_device float floorfrac(float x, int* i) { - *i = quick_floor(x); + *i = quick_floor_to_int(x); return x - *i; } #else @@ -304,34 +287,27 @@ ccl_device float snoise(float3 p) } /* cell noise */ -#ifndef __KERNEL_SSE2__ -ccl_device_noinline float cellnoise(float3 p) +ccl_device float cellnoise(float3 p) { - uint ix = quick_floor(p.x); - uint iy = quick_floor(p.y); - uint iz = quick_floor(p.z); - - return bits_to_01(hash(ix, iy, iz)); + int3 ip = quick_floor_to_int3(p); + return bits_to_01(hash(ip.x, ip.y, ip.z)); } -ccl_device float3 cellnoise_color(float3 p) +ccl_device float3 cellnoise3(float3 p) { - float r = cellnoise(p); - float g = cellnoise(make_float3(p.y, p.x, p.z)); - float b = cellnoise(make_float3(p.y, p.z, p.x)); - + int3 ip = quick_floor_to_int3(p); +#ifndef __KERNEL_SSE__ + float r = bits_to_01(hash(ip.x, ip.y, ip.z)); + float g = bits_to_01(hash(ip.y, ip.x, ip.z)); + float b = bits_to_01(hash(ip.y, ip.z, ip.x)); return make_float3(r, g, b); -} #else -ccl_device ssef cellnoise_color(const ssef& p) -{ - ssei ip = quick_floor_sse(p); - ssei ip_yxz = shuffle<1, 0, 2, 3>(ip); - ssei ip_xyy = shuffle<0, 1, 1, 3>(ip); - ssei ip_zzx = shuffle<2, 2, 0, 3>(ip); - return bits_to_01_sse(hash_sse(ip_xyy, ip_yxz, ip_zzx)); -} + ssei ip_yxz = shuffle<1, 0, 2, 3>(ssei(ip.m128)); + ssei ip_xyy = shuffle<0, 1, 1, 3>(ssei(ip.m128)); + ssei ip_zzx = shuffle<2, 2, 0, 3>(ssei(ip.m128)); + ssei bits = hash_sse(ip_xyy, ip_yxz, ip_zzx); + return float3(uint32_to_float(bits) * ssef(1.0f/(float)0xFFFFFFFF)); #endif +} CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_noisetex.h b/intern/cycles/kernel/svm/svm_noisetex.h index 0347ab7b1930..c02940f96d6e 100644 --- a/intern/cycles/kernel/svm/svm_noisetex.h +++ b/intern/cycles/kernel/svm/svm_noisetex.h @@ -57,4 +57,3 @@ ccl_device void svm_node_tex_noise(KernelGlobals *kg, ShaderData *sd, float *sta } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_normal.h b/intern/cycles/kernel/svm/svm_normal.h index 53abef710129..fe46d79fe15f 100644 --- a/intern/cycles/kernel/svm/svm_normal.h +++ b/intern/cycles/kernel/svm/svm_normal.h @@ -36,4 +36,3 @@ ccl_device void svm_node_normal(KernelGlobals *kg, ShaderData *sd, float *stack, } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_ramp.h b/intern/cycles/kernel/svm/svm_ramp.h index 368740f64c7d..a3e4b6e87cdd 100644 --- a/intern/cycles/kernel/svm/svm_ramp.h +++ b/intern/cycles/kernel/svm/svm_ramp.h @@ -109,4 +109,3 @@ ccl_device void svm_node_curves(KernelGlobals *kg, ShaderData *sd, float *stack, CCL_NAMESPACE_END #endif /* __SVM_RAMP_H__ */ - diff --git a/intern/cycles/kernel/svm/svm_ramp_util.h b/intern/cycles/kernel/svm/svm_ramp_util.h index b0adadae9b73..a67689ff9d1b 100644 --- a/intern/cycles/kernel/svm/svm_ramp_util.h +++ b/intern/cycles/kernel/svm/svm_ramp_util.h @@ -96,4 +96,3 @@ ccl_device float float_ramp_lookup(const float *ramp, CCL_NAMESPACE_END #endif /* __SVM_RAMP_UTIL_H__ */ - diff --git a/intern/cycles/kernel/svm/svm_sepcomb_hsv.h b/intern/cycles/kernel/svm/svm_sepcomb_hsv.h index 6f51b1637568..1096aed2d97b 100644 --- a/intern/cycles/kernel/svm/svm_sepcomb_hsv.h +++ b/intern/cycles/kernel/svm/svm_sepcomb_hsv.h @@ -20,11 +20,11 @@ ccl_device void svm_node_combine_hsv(KernelGlobals *kg, ShaderData *sd, float *s { uint4 node1 = read_node(kg, offset); uint color_out = node1.y; - + float hue = stack_load_float(stack, hue_in); float saturation = stack_load_float(stack, saturation_in); float value = stack_load_float(stack, value_in); - + /* Combine, and convert back to RGB */ float3 color = hsv_to_rgb(make_float3(hue, saturation, value)); @@ -36,9 +36,9 @@ ccl_device void svm_node_separate_hsv(KernelGlobals *kg, ShaderData *sd, float * { uint4 node1 = read_node(kg, offset); uint value_out = node1.y; - + float3 color = stack_load_float3(stack, color_in); - + /* Convert to HSV */ color = rgb_to_hsv(color); @@ -51,4 +51,3 @@ ccl_device void svm_node_separate_hsv(KernelGlobals *kg, ShaderData *sd, float * } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_sepcomb_vector.h b/intern/cycles/kernel/svm/svm_sepcomb_vector.h index 63570dd69421..0d85c0d6f1d5 100644 --- a/intern/cycles/kernel/svm/svm_sepcomb_vector.h +++ b/intern/cycles/kernel/svm/svm_sepcomb_vector.h @@ -41,4 +41,3 @@ ccl_device void svm_node_separate_vector(ShaderData *sd, float *stack, uint ivec } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_sky.h b/intern/cycles/kernel/svm/svm_sky.h index b83a71685415..092f6e045d6d 100644 --- a/intern/cycles/kernel/svm/svm_sky.h +++ b/intern/cycles/kernel/svm/svm_sky.h @@ -110,7 +110,7 @@ ccl_device void svm_node_tex_sky(KernelGlobals *kg, ShaderData *sd, float *stack /* Define variables */ float sunphi, suntheta, radiance_x, radiance_y, radiance_z; float config_x[9], config_y[9], config_z[9]; - + /* Load data */ uint dir_offset = node.y; uint out_offset = node.z; @@ -121,49 +121,49 @@ ccl_device void svm_node_tex_sky(KernelGlobals *kg, ShaderData *sd, float *stack suntheta = data.y; radiance_x = data.z; radiance_y = data.w; - + data = read_node_float(kg, offset); radiance_z = data.x; config_x[0] = data.y; config_x[1] = data.z; config_x[2] = data.w; - + data = read_node_float(kg, offset); config_x[3] = data.x; config_x[4] = data.y; config_x[5] = data.z; config_x[6] = data.w; - + data = read_node_float(kg, offset); config_x[7] = data.x; config_x[8] = data.y; config_y[0] = data.z; config_y[1] = data.w; - + data = read_node_float(kg, offset); config_y[2] = data.x; config_y[3] = data.y; config_y[4] = data.z; config_y[5] = data.w; - + data = read_node_float(kg, offset); config_y[6] = data.x; config_y[7] = data.y; config_y[8] = data.z; config_z[0] = data.w; - + data = read_node_float(kg, offset); config_z[1] = data.x; config_z[2] = data.y; config_z[3] = data.z; config_z[4] = data.w; - + data = read_node_float(kg, offset); config_z[5] = data.x; config_z[6] = data.y; config_z[7] = data.z; config_z[8] = data.w; - + float3 dir = stack_load_float3(stack, dir_offset); float3 f; @@ -183,4 +183,3 @@ ccl_device void svm_node_tex_sky(KernelGlobals *kg, ShaderData *sd, float *stack } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_tex_coord.h b/intern/cycles/kernel/svm/svm_tex_coord.h index 6ff39e5f587a..45c38d647633 100644 --- a/intern/cycles/kernel/svm/svm_tex_coord.h +++ b/intern/cycles/kernel/svm/svm_tex_coord.h @@ -323,7 +323,7 @@ ccl_device void svm_node_normal_map(KernelGlobals *kg, ShaderData *sd, float *st color.y = -color.y; color.z = -color.z; } - + /* object, world space */ N = color; @@ -345,6 +345,8 @@ ccl_device void svm_node_normal_map(KernelGlobals *kg, ShaderData *sd, float *st N = safe_normalize(sd->N + (N - sd->N)*strength); } + N = ensure_valid_reflection(sd->Ng, sd->I, N); + if(is_zero(N)) { N = sd->N; } @@ -392,4 +394,3 @@ ccl_device void svm_node_tangent(KernelGlobals *kg, ShaderData *sd, float *stack } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_texture.h b/intern/cycles/kernel/svm/svm_texture.h index dcb00f7dd556..57729817bdc6 100644 --- a/intern/cycles/kernel/svm/svm_texture.h +++ b/intern/cycles/kernel/svm/svm_texture.h @@ -61,4 +61,3 @@ ccl_device_noinline float noise_turbulence(float3 p, float octaves, int hard) } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_types.h b/intern/cycles/kernel/svm/svm_types.h index 54db18cd7bb3..910537a2539f 100644 --- a/intern/cycles/kernel/svm/svm_types.h +++ b/intern/cycles/kernel/svm/svm_types.h @@ -24,7 +24,7 @@ CCL_NAMESPACE_BEGIN /* SVM stack has a fixed size */ #define SVM_STACK_SIZE 255 /* SVM stack offsets with this value indicate that it's not on the stack */ -#define SVM_STACK_INVALID 255 +#define SVM_STACK_INVALID 255 #define SVM_BUMP_EVAL_STATE_SIZE 9 @@ -261,6 +261,10 @@ typedef enum NodeMath { NODE_MATH_MODULO, NODE_MATH_ABSOLUTE, NODE_MATH_ARCTAN2, + NODE_MATH_FLOOR, + NODE_MATH_CEIL, + NODE_MATH_FRACT, + NODE_MATH_SQRT, NODE_MATH_CLAMP /* used for the clamp UI option */ } NodeMath; @@ -334,6 +338,21 @@ typedef enum NodeVoronoiColoring { NODE_VORONOI_CELLS } NodeVoronoiColoring; +typedef enum NodeVoronoiDistanceMetric { + NODE_VORONOI_DISTANCE, + NODE_VORONOI_MANHATTAN, + NODE_VORONOI_CHEBYCHEV, + NODE_VORONOI_MINKOWSKI +} NodeVoronoiDistanceMetric; + +typedef enum NodeVoronoiFeature { + NODE_VORONOI_F1, + NODE_VORONOI_F2, + NODE_VORONOI_F3, + NODE_VORONOI_F4, + NODE_VORONOI_F2F1 +} NodeVoronoiFeature; + typedef enum NodeBlendWeightType { NODE_LAYER_WEIGHT_FRESNEL, NODE_LAYER_WEIGHT_FACING @@ -399,6 +418,13 @@ typedef enum ShaderType { SHADER_TYPE_BUMP, } ShaderType; +typedef enum NodePrincipledHairParametrization { + NODE_PRINCIPLED_HAIR_REFLECTANCE = 0, + NODE_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION = 1, + NODE_PRINCIPLED_HAIR_DIRECT_ABSORPTION = 2, + NODE_PRINCIPLED_HAIR_NUM, +} NodePrincipledHairParametrization; + /* Closure */ typedef enum ClosureType { @@ -445,6 +471,7 @@ typedef enum ClosureType { CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID, CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_FRESNEL_ID, CLOSURE_BSDF_SHARP_GLASS_ID, + CLOSURE_BSDF_HAIR_PRINCIPLED_ID, CLOSURE_BSDF_HAIR_TRANSMISSION_ID, /* Special cases */ @@ -476,7 +503,7 @@ typedef enum ClosureType { /* watch this, being lazy with memory usage */ #define CLOSURE_IS_BSDF(type) (type <= CLOSURE_BSDF_TRANSPARENT_ID) #define CLOSURE_IS_BSDF_DIFFUSE(type) (type >= CLOSURE_BSDF_DIFFUSE_ID && type <= CLOSURE_BSDF_DIFFUSE_TOON_ID) -#define CLOSURE_IS_BSDF_GLOSSY(type) (type >= CLOSURE_BSDF_REFLECTION_ID && type <= CLOSURE_BSDF_HAIR_REFLECTION_ID) +#define CLOSURE_IS_BSDF_GLOSSY(type) ((type >= CLOSURE_BSDF_REFLECTION_ID && type <= CLOSURE_BSDF_HAIR_REFLECTION_ID )|| (type == CLOSURE_BSDF_HAIR_PRINCIPLED_ID)) #define CLOSURE_IS_BSDF_TRANSMISSION(type) (type >= CLOSURE_BSDF_TRANSLUCENT_ID && type <= CLOSURE_BSDF_HAIR_TRANSMISSION_ID) #define CLOSURE_IS_BSDF_BSSRDF(type) (type == CLOSURE_BSDF_BSSRDF_ID || type == CLOSURE_BSDF_BSSRDF_PRINCIPLED_ID) #define CLOSURE_IS_BSDF_SINGULAR(type) (type == CLOSURE_BSDF_REFLECTION_ID || \ @@ -505,4 +532,3 @@ typedef enum ClosureType { CCL_NAMESPACE_END #endif /* __SVM_TYPES_H__ */ - diff --git a/intern/cycles/kernel/svm/svm_value.h b/intern/cycles/kernel/svm/svm_value.h index c1c2b539df34..062aee2956e0 100644 --- a/intern/cycles/kernel/svm/svm_value.h +++ b/intern/cycles/kernel/svm/svm_value.h @@ -33,4 +33,3 @@ ccl_device void svm_node_value_v(KernelGlobals *kg, ShaderData *sd, float *stack } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_vector_transform.h b/intern/cycles/kernel/svm/svm_vector_transform.h index 4e92f27acdb9..f6ec36ba41f6 100644 --- a/intern/cycles/kernel/svm/svm_vector_transform.h +++ b/intern/cycles/kernel/svm/svm_vector_transform.h @@ -22,20 +22,20 @@ ccl_device void svm_node_vector_transform(KernelGlobals *kg, ShaderData *sd, flo { uint itype, ifrom, ito; uint vector_in, vector_out; - + decode_node_uchar4(node.y, &itype, &ifrom, &ito, NULL); decode_node_uchar4(node.z, &vector_in, &vector_out, NULL, NULL); - + float3 in = stack_load_float3(stack, vector_in); - + NodeVectorTransformType type = (NodeVectorTransformType)itype; NodeVectorTransformConvertSpace from = (NodeVectorTransformConvertSpace)ifrom; NodeVectorTransformConvertSpace to = (NodeVectorTransformConvertSpace)ito; - + Transform tfm; bool is_object = (sd->object != OBJECT_NONE); bool is_direction = (type == NODE_VECTOR_TRANSFORM_TYPE_VECTOR || type == NODE_VECTOR_TRANSFORM_TYPE_NORMAL); - + /* From world */ if(from == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_WORLD) { if(to == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_CAMERA) { @@ -52,7 +52,7 @@ ccl_device void svm_node_vector_transform(KernelGlobals *kg, ShaderData *sd, flo object_inverse_position_transform(kg, sd, &in); } } - + /* From camera */ else if(from == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_CAMERA) { if(to == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_WORLD || to == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_OBJECT) { @@ -69,7 +69,7 @@ ccl_device void svm_node_vector_transform(KernelGlobals *kg, ShaderData *sd, flo object_inverse_position_transform(kg, sd, &in); } } - + /* From object */ else if(from == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_OBJECT) { if((to == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_WORLD || to == NODE_VECTOR_TRANSFORM_CONVERT_SPACE_CAMERA) && is_object) { @@ -86,11 +86,11 @@ ccl_device void svm_node_vector_transform(KernelGlobals *kg, ShaderData *sd, flo in = transform_point(&tfm, in); } } - + /* Normalize Normal */ if(type == NODE_VECTOR_TRANSFORM_TYPE_NORMAL) in = normalize(in); - + /* Output */ if(stack_valid(vector_out)) { stack_store_float3(stack, vector_out, in); @@ -98,4 +98,3 @@ ccl_device void svm_node_vector_transform(KernelGlobals *kg, ShaderData *sd, flo } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_voronoi.h b/intern/cycles/kernel/svm/svm_voronoi.h index d612d7e973f5..d661df54ead5 100644 --- a/intern/cycles/kernel/svm/svm_voronoi.h +++ b/intern/cycles/kernel/svm/svm_voronoi.h @@ -18,123 +18,143 @@ CCL_NAMESPACE_BEGIN /* Voronoi */ -ccl_device float voronoi_F1_distance(float3 p) +ccl_device void voronoi_neighbors(float3 p, NodeVoronoiDistanceMetric distance, float e, float da[4], float3 pa[4]) { - /* returns squared distance in da */ - float da = 1e10f; + /* Compute the distance to and the position of the closest neighbors to p. + * + * The neighbors are randomly placed, 1 each in a 3x3x3 grid (Worley pattern). + * The distances and points are returned in ascending order, i.e. da[0] and pa[0] will + * contain the distance to the closest point and its coordinates respectively. + */ -#ifndef __KERNEL_SSE2__ - int ix = floor_to_int(p.x), iy = floor_to_int(p.y), iz = floor_to_int(p.z); + da[0] = 1e10f; + da[1] = 1e10f; + da[2] = 1e10f; + da[3] = 1e10f; - for(int xx = -1; xx <= 1; xx++) { - for(int yy = -1; yy <= 1; yy++) { - for(int zz = -1; zz <= 1; zz++) { - float3 ip = make_float3(ix + xx, iy + yy, iz + zz); - float3 vp = ip + cellnoise_color(ip); - float d = len_squared(p - vp); - da = min(d, da); - } - } - } -#else - ssef vec_p = load4f(p); - ssei xyzi = quick_floor_sse(vec_p); - - for(int xx = -1; xx <= 1; xx++) { - for(int yy = -1; yy <= 1; yy++) { - for(int zz = -1; zz <= 1; zz++) { - ssef ip = ssef(xyzi + ssei(xx, yy, zz, 0)); - ssef vp = ip + cellnoise_color(ip); - float d = len_squared<1, 1, 1, 0>(vec_p - vp); - da = min(d, da); - } - } - } -#endif - - return da; -} + pa[0] = make_float3(0.0f, 0.0f, 0.0f); + pa[1] = make_float3(0.0f, 0.0f, 0.0f); + pa[2] = make_float3(0.0f, 0.0f, 0.0f); + pa[3] = make_float3(0.0f, 0.0f, 0.0f); -ccl_device float3 voronoi_F1_color(float3 p) -{ - /* returns color of the nearest point */ - float da = 1e10f; - -#ifndef __KERNEL_SSE2__ - float3 pa; - int ix = floor_to_int(p.x), iy = floor_to_int(p.y), iz = floor_to_int(p.z); + int3 xyzi = quick_floor_to_int3(p); for(int xx = -1; xx <= 1; xx++) { for(int yy = -1; yy <= 1; yy++) { for(int zz = -1; zz <= 1; zz++) { - float3 ip = make_float3(ix + xx, iy + yy, iz + zz); - float3 vp = ip + cellnoise_color(ip); - float d = len_squared(p - vp); - - if(d < da) { - da = d; - pa = vp; + int3 ip = xyzi + make_int3(xx, yy, zz); + float3 fp = make_float3(ip.x, ip.y, ip.z); + float3 vp = fp + cellnoise3(fp); + + float d; + switch(distance) { + case NODE_VORONOI_DISTANCE: + d = len_squared(p - vp); + break; + case NODE_VORONOI_MANHATTAN: + d = reduce_add(fabs(vp - p)); + break; + case NODE_VORONOI_CHEBYCHEV: + d = max3(fabs(vp - p)); + break; + case NODE_VORONOI_MINKOWSKI: { + float3 n = fabs(vp - p); + if(e == 0.5f) { + d = sqr(reduce_add(sqrt(n))); + } + else { + d = powf(reduce_add(pow3(n, e)), 1.0f/e); + } + break; + } } - } - } - } - return cellnoise_color(pa); -#else - ssef pa, vec_p = load4f(p); - ssei xyzi = quick_floor_sse(vec_p); - - for(int xx = -1; xx <= 1; xx++) { - for(int yy = -1; yy <= 1; yy++) { - for(int zz = -1; zz <= 1; zz++) { - ssef ip = ssef(xyzi + ssei(xx, yy, zz, 0)); - ssef vp = ip + cellnoise_color(ip); - float d = len_squared<1, 1, 1, 0>(vec_p - vp); + /* To keep the shortest four distances and associated points we have to keep them in sorted order. */ + if(d < da[0]) { + da[3] = da[2]; + da[2] = da[1]; + da[1] = da[0]; + da[0] = d; + + pa[3] = pa[2]; + pa[2] = pa[1]; + pa[1] = pa[0]; + pa[0] = vp; + } + else if(d < da[1]) { + da[3] = da[2]; + da[2] = da[1]; + da[1] = d; + + pa[3] = pa[2]; + pa[2] = pa[1]; + pa[1] = vp; + } + else if(d < da[2]) { + da[3] = da[2]; + da[2] = d; - if(d < da) { - da = d; - pa = vp; + pa[3] = pa[2]; + pa[2] = vp; + } + else if(d < da[3]) { + da[3] = d; + pa[3] = vp; } } } } - - ssef color = cellnoise_color(pa); - return (float3 &)color; -#endif -} - -ccl_device_noinline float4 svm_voronoi(NodeVoronoiColoring coloring, float3 p) -{ - if(coloring == NODE_VORONOI_INTENSITY) { - /* compute squared distance to the nearest neighbour */ - float fac = voronoi_F1_distance(p); - return make_float4(fac, fac, fac, fac); - } - else { - /* compute color of the nearest neighbour */ - float3 color = voronoi_F1_color(p); - return make_float4(color.x, color.y, color.z, average(color)); - } } ccl_device void svm_node_tex_voronoi(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node, int *offset) { - uint coloring = node.y; - uint scale_offset, co_offset, fac_offset, color_offset; + uint4 node2 = read_node(kg, offset); - decode_node_uchar4(node.z, &scale_offset, &co_offset, &fac_offset, &color_offset); + uint co_offset, coloring, distance, feature; + uint scale_offset, e_offset, fac_offset, color_offset; + + decode_node_uchar4(node.y, &co_offset, &coloring, &distance, &feature); + decode_node_uchar4(node.z, &scale_offset, &e_offset, &fac_offset, &color_offset); float3 co = stack_load_float3(stack, co_offset); - float scale = stack_load_float_default(stack, scale_offset, node.w); + float scale = stack_load_float_default(stack, scale_offset, node2.x); + float exponent = stack_load_float_default(stack, e_offset, node2.y); + + float dist[4]; + float3 neighbor[4]; + voronoi_neighbors(co*scale, (NodeVoronoiDistanceMetric)distance, exponent, dist, neighbor); - float4 result = svm_voronoi((NodeVoronoiColoring)coloring, co*scale); - float3 color = make_float3(result.x, result.y, result.z); - float f = result.w; + float3 color; + float fac; + if(coloring == NODE_VORONOI_INTENSITY) { + switch(feature) { + case NODE_VORONOI_F1: fac = dist[0]; break; + case NODE_VORONOI_F2: fac = dist[1]; break; + case NODE_VORONOI_F3: fac = dist[2]; break; + case NODE_VORONOI_F4: fac = dist[3]; break; + case NODE_VORONOI_F2F1: fac = dist[1] - dist[0]; break; + } - if(stack_valid(fac_offset)) stack_store_float(stack, fac_offset, f); + color = make_float3(fac, fac, fac); + } + else { + /* NODE_VORONOI_CELLS */ + switch(feature) { + case NODE_VORONOI_F1: color = neighbor[0]; break; + case NODE_VORONOI_F2: color = neighbor[1]; break; + case NODE_VORONOI_F3: color = neighbor[2]; break; + case NODE_VORONOI_F4: color = neighbor[3]; break; + /* Usefulness of this vector is questionable. Note F2 >= F1 but the + * individual vector components might not be. */ + case NODE_VORONOI_F2F1: color = fabs(neighbor[1] - neighbor[0]); break; + } + + color = cellnoise3(color); + fac = average(color); + } + + if(stack_valid(fac_offset)) stack_store_float(stack, fac_offset, fac); if(stack_valid(color_offset)) stack_store_float3(stack, color_offset, color); } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_wave.h b/intern/cycles/kernel/svm/svm_wave.h index 6ce69458a034..7b60ab6e6aec 100644 --- a/intern/cycles/kernel/svm/svm_wave.h +++ b/intern/cycles/kernel/svm/svm_wave.h @@ -63,4 +63,3 @@ ccl_device void svm_node_tex_wave(KernelGlobals *kg, ShaderData *sd, float *stac } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_wavelength.h b/intern/cycles/kernel/svm/svm_wavelength.h index 62e026278ac8..e935fd206905 100644 --- a/intern/cycles/kernel/svm/svm_wavelength.h +++ b/intern/cycles/kernel/svm/svm_wavelength.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2013, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -71,12 +71,12 @@ ccl_static_constant float cie_colour_match[81][3] = { }; ccl_device void svm_node_wavelength(KernelGlobals *kg, ShaderData *sd, float *stack, uint wavelength, uint color_out) -{ +{ float lambda_nm = stack_load_float(stack, wavelength); float ii = (lambda_nm-380.0f) * (1.0f/5.0f); // scaled 0..80 int i = float_to_int(ii); float3 color; - + if(i < 0 || i >= 80) { color = make_float3(0.0f, 0.0f, 0.0f); } @@ -85,10 +85,10 @@ ccl_device void svm_node_wavelength(KernelGlobals *kg, ShaderData *sd, float *st ccl_constant float *c = cie_colour_match[i]; color = interp(make_float3(c[0], c[1], c[2]), make_float3(c[3], c[4], c[5]), ii); } - + color = xyz_to_rgb(kg, color); color *= 1.0f/2.52f; // Empirical scale from lg to make all comps <= 1 - + /* Clamp to zero if values are smaller */ color = max(color, make_float3(0.0f, 0.0f, 0.0f)); @@ -96,4 +96,3 @@ ccl_device void svm_node_wavelength(KernelGlobals *kg, ShaderData *sd, float *st } CCL_NAMESPACE_END - diff --git a/intern/cycles/kernel/svm/svm_wireframe.h b/intern/cycles/kernel/svm/svm_wireframe.h index 3c6353c80014..35df9e8a0e7c 100644 --- a/intern/cycles/kernel/svm/svm_wireframe.h +++ b/intern/cycles/kernel/svm/svm_wireframe.h @@ -5,7 +5,7 @@ * All Rights Reserved. * * Modifications Copyright 2013, Blender Foundation. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -134,4 +134,3 @@ ccl_device void svm_node_wireframe(KernelGlobals *kg, } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/CMakeLists.txt b/intern/cycles/render/CMakeLists.txt index b7248354abdf..7d2220f37f9b 100644 --- a/intern/cycles/render/CMakeLists.txt +++ b/intern/cycles/render/CMakeLists.txt @@ -33,6 +33,7 @@ set(SRC session.cpp shader.cpp sobol.cpp + stats.cpp svm.cpp tables.cpp tile.cpp @@ -60,6 +61,7 @@ set(SRC_HEADERS session.h shader.h sobol.h + stats.h svm.h tables.h tile.h diff --git a/intern/cycles/render/attribute.cpp b/intern/cycles/render/attribute.cpp index 8c77687d9ccd..a7450849195b 100644 --- a/intern/cycles/render/attribute.cpp +++ b/intern/cycles/render/attribute.cpp @@ -202,7 +202,7 @@ bool Attribute::same_storage(TypeDesc a, TypeDesc b) { if(a == b) return true; - + if(a == TypeDesc::TypeColor || a == TypeDesc::TypePoint || a == TypeDesc::TypeVector || a == TypeDesc::TypeNormal) { @@ -292,7 +292,7 @@ const char *Attribute::standard_name(AttributeStandard std) case ATTR_STD_NUM: return ""; } - + return ""; } @@ -476,7 +476,7 @@ Attribute *AttributeSet::add(AttributeStandard std, ustring name) } attr->std = std; - + return attr; } @@ -682,7 +682,7 @@ bool AttributeRequestSet::find(ustring name) foreach(AttributeRequest& req, requests) if(req.name == name) return true; - + return false; } @@ -706,4 +706,3 @@ void AttributeRequestSet::clear() } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/attribute.h b/intern/cycles/render/attribute.h index 5cb6c75aab2a..40e5be2e1b2e 100644 --- a/intern/cycles/render/attribute.h +++ b/intern/cycles/render/attribute.h @@ -173,4 +173,3 @@ class AttributeRequestSet { CCL_NAMESPACE_END #endif /* __ATTRIBUTE_H__ */ - diff --git a/intern/cycles/render/background.cpp b/intern/cycles/render/background.cpp index df3b65be1105..d8a49bf6a5ef 100644 --- a/intern/cycles/render/background.cpp +++ b/intern/cycles/render/background.cpp @@ -62,7 +62,7 @@ void Background::device_update(Device *device, DeviceScene *dscene, Scene *scene { if(!need_update) return; - + device_free(device, dscene); Shader *bg_shader = shader; @@ -135,4 +135,3 @@ void Background::tag_update(Scene *scene) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/background.h b/intern/cycles/render/background.h index 145c05f1c18d..3f56dedb2c8f 100644 --- a/intern/cycles/render/background.h +++ b/intern/cycles/render/background.h @@ -60,4 +60,3 @@ class Background : public Node { CCL_NAMESPACE_END #endif /* __BACKGROUND_H__ */ - diff --git a/intern/cycles/render/bake.h b/intern/cycles/render/bake.h index fbb8686b8f68..a811eac3327a 100644 --- a/intern/cycles/render/bake.h +++ b/intern/cycles/render/bake.h @@ -84,4 +84,3 @@ class BakeManager { CCL_NAMESPACE_END #endif /* __BAKE_H__ */ - diff --git a/intern/cycles/render/buffers.cpp b/intern/cycles/render/buffers.cpp index 6f560380b403..4cd8b3726d3a 100644 --- a/intern/cycles/render/buffers.cpp +++ b/intern/cycles/render/buffers.cpp @@ -160,7 +160,7 @@ bool RenderBuffers::get_denoising_pass_rect(int offset, float exposure, int samp (offset == DENOISING_PASS_DEPTH_VAR) || (offset == DENOISING_PASS_COLOR_VAR); - if(offset == DENOISING_PASS_COLOR) { + if(offset == DENOISING_PASS_COLOR || offset == DENOISING_PASS_CLEAN) { scale *= exposure; } else if(offset == DENOISING_PASS_COLOR_VAR) { @@ -448,4 +448,3 @@ bool DisplayBuffer::draw_ready() } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/buffers.h b/intern/cycles/render/buffers.h index dfc98fe20619..1b06ffe33a6a 100644 --- a/intern/cycles/render/buffers.h +++ b/intern/cycles/render/buffers.h @@ -137,6 +137,7 @@ class RenderTile { int tile_index; device_ptr buffer; + int device_size; RenderBuffers *buffers; @@ -146,4 +147,3 @@ class RenderTile { CCL_NAMESPACE_END #endif /* __BUFFERS_H__ */ - diff --git a/intern/cycles/render/camera.cpp b/intern/cycles/render/camera.cpp index 734cdffd5c51..cc3dd1c923b4 100644 --- a/intern/cycles/render/camera.cpp +++ b/intern/cycles/render/camera.cpp @@ -246,7 +246,7 @@ void Camera::update(Scene *scene) cameratoscreen = projection_orthographic(nearclip, farclip); else cameratoscreen = projection_identity(); - + ProjectionTransform screentocamera = projection_inverse(cameratoscreen); rastertocamera = screentocamera * rastertoscreen; diff --git a/intern/cycles/render/camera.h b/intern/cycles/render/camera.h index 37d05c01bd93..323f2c61ca4d 100644 --- a/intern/cycles/render/camera.h +++ b/intern/cycles/render/camera.h @@ -181,7 +181,7 @@ class Camera : public Node { /* functions */ Camera(); ~Camera(); - + void compute_auto_viewplane(); void update(Scene *scene); @@ -213,4 +213,3 @@ class Camera : public Node { CCL_NAMESPACE_END #endif /* __CAMERA_H__ */ - diff --git a/intern/cycles/render/constant_fold.h b/intern/cycles/render/constant_fold.h index cc24d6142068..26fa4e8b1c89 100644 --- a/intern/cycles/render/constant_fold.h +++ b/intern/cycles/render/constant_fold.h @@ -71,4 +71,3 @@ class ConstantFolder { CCL_NAMESPACE_END #endif /* __CONSTANT_FOLD_H__ */ - diff --git a/intern/cycles/render/curves.cpp b/intern/cycles/render/curves.cpp index 4c085b928fb8..58b71d3e1224 100644 --- a/intern/cycles/render/curves.cpp +++ b/intern/cycles/render/curves.cpp @@ -188,4 +188,3 @@ void CurveSystemManager::tag_update_mesh() need_mesh_update = true; } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/curves.h b/intern/cycles/render/curves.h index 8834764bd63a..62066d8a8098 100644 --- a/intern/cycles/render/curves.h +++ b/intern/cycles/render/curves.h @@ -120,4 +120,3 @@ class CurveSystemManager { CCL_NAMESPACE_END #endif /* __CURVES_H__ */ - diff --git a/intern/cycles/render/film.cpp b/intern/cycles/render/film.cpp index 69828cc78da6..8f3596ade58b 100644 --- a/intern/cycles/render/film.cpp +++ b/intern/cycles/render/film.cpp @@ -175,11 +175,11 @@ bool Pass::equals(const array& A, const array& B) { if(A.size() != B.size()) return false; - + for(int i = 0; i < A.size(); i++) if(A[i].type != B[i].type) return false; - + return true; } @@ -188,7 +188,7 @@ bool Pass::contains(const array& passes, PassType type) for(size_t i = 0; i < passes.size(); i++) if(passes[i].type == type) return true; - + return false; } @@ -302,7 +302,7 @@ void Film::device_update(Device *device, DeviceScene *dscene, Scene *scene) { if(!need_update) return; - + device_free(device, dscene, scene); KernelFilm *kfilm = &dscene->data.film; @@ -510,4 +510,3 @@ void Film::tag_update(Scene * /*scene*/) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/film.h b/intern/cycles/render/film.h index 29b1e7e91577..6ab2eea79b82 100644 --- a/intern/cycles/render/film.h +++ b/intern/cycles/render/film.h @@ -93,4 +93,3 @@ class Film : public Node { CCL_NAMESPACE_END #endif /* __FILM_H__ */ - diff --git a/intern/cycles/render/graph.cpp b/intern/cycles/render/graph.cpp index 8b179f742c4b..eea1bed58dcf 100644 --- a/intern/cycles/render/graph.cpp +++ b/intern/cycles/render/graph.cpp @@ -245,7 +245,7 @@ void ShaderGraph::connect(ShaderOutput *from, ShaderInput *to) ShaderNode *convert; ShaderInput *convert_in; - if (to->type() == SocketType::CLOSURE) { + if(to->type() == SocketType::CLOSURE) { EmissionNode *emission = new EmissionNode(); emission->color = make_float3(1.0f, 1.0f, 1.0f); emission->strength = 1.0f; @@ -745,7 +745,7 @@ void ShaderGraph::clean(Scene *scene) vector visited(num_node_ids, false); vector on_stack(num_node_ids, false); - + /* break cycles */ break_cycles(output(), visited, on_stack); @@ -860,7 +860,7 @@ void ShaderGraph::refine_bump_nodes() copy_nodes(nodes_bump, nodes_dx); copy_nodes(nodes_bump, nodes_dy); - + /* mark nodes to indicate they are use for bump computation, so that any texture coordinates are shifted by dx/dy when sampling */ foreach(ShaderNode *node, nodes_bump) @@ -876,13 +876,13 @@ void ShaderGraph::refine_bump_nodes() connect(out_dx, node->input("SampleX")); connect(out_dy, node->input("SampleY")); - + /* add generated nodes */ foreach(NodePair& pair, nodes_dx) add(pair.second); foreach(NodePair& pair, nodes_dy) add(pair.second); - + /* connect what is connected is bump to samplecenter input*/ connect(out , node->input("SampleCenter")); @@ -941,7 +941,7 @@ void ShaderGraph::bump_from_displacement(bool use_object_space) * this for bump from displacement, this will be the only bump allowed to * overwrite the shader normal */ ShaderNode *set_normal = add(new SetNormalNode()); - + /* add bump node and connect copied graphs to it */ BumpNode *bump = (BumpNode*)add(new BumpNode()); bump->use_object_space = use_object_space; @@ -973,7 +973,7 @@ void ShaderGraph::bump_from_displacement(bool use_object_space) connect(dot_center->output("Value"), bump->input("SampleCenter")); connect(dot_dx->output("Value"), bump->input("SampleX")); connect(dot_dy->output("Value"), bump->input("SampleY")); - + /* connect the bump out to the set normal in: */ connect(bump->output("Normal"), set_normal->input("Direction")); @@ -996,7 +996,7 @@ void ShaderGraph::transform_multi_closure(ShaderNode *node, ShaderOutput *weight * the graph into nodes that feed weights into closure nodes. this is too * avoid building a closure tree and then flattening it, and instead write it * directly to an array */ - + if(node->special_type == SHADER_SPECIAL_TYPE_COMBINE_CLOSURE) { ShaderInput *fin = node->input("Fac"); ShaderInput *cl1in = node->input("Closure1"); @@ -1007,8 +1007,8 @@ void ShaderGraph::transform_multi_closure(ShaderNode *node, ShaderOutput *weight /* mix closure: add node to mix closure weights */ MixClosureWeightNode *mix_node = new MixClosureWeightNode(); add(mix_node); - ShaderInput *fac_in = mix_node->input("Fac"); - ShaderInput *weight_in = mix_node->input("Weight"); + ShaderInput *fac_in = mix_node->input("Fac"); + ShaderInput *weight_in = mix_node->input("Weight"); if(fin->link) connect(fin->link, fac_in); @@ -1091,6 +1091,9 @@ int ShaderGraph::get_num_closures() else if(CLOSURE_IS_VOLUME(closure_type)) { num_closures += VOLUME_STACK_SIZE; } + else if(closure_type == CLOSURE_BSDF_HAIR_PRINCIPLED_ID) { + num_closures += 4; + } else { ++num_closures; } @@ -1171,4 +1174,3 @@ void ShaderGraph::dump_graph(const char *filename) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/graph.h b/intern/cycles/render/graph.h index 5d986ae48277..426522066b30 100644 --- a/intern/cycles/render/graph.h +++ b/intern/cycles/render/graph.h @@ -165,7 +165,7 @@ class ShaderNode : public Node { int id; /* index in graph node array */ ShaderBump bump; /* for bump mapping utility */ - + ShaderNodeSpecialType special_type; /* special node type */ /* ** Selective nodes compilation ** */ @@ -294,4 +294,3 @@ class ShaderGraph { CCL_NAMESPACE_END #endif /* __GRAPH_H__ */ - diff --git a/intern/cycles/render/image.cpp b/intern/cycles/render/image.cpp index 9c6536edc4f2..e6ef19cc3be4 100644 --- a/intern/cycles/render/image.cpp +++ b/intern/cycles/render/image.cpp @@ -17,6 +17,7 @@ #include "device/device.h" #include "render/image.h" #include "render/scene.h" +#include "render/stats.h" #include "util/util_foreach.h" #include "util/util_logging.h" @@ -30,16 +31,58 @@ CCL_NAMESPACE_BEGIN +namespace { + /* Some helpers to silence warning in templated function. */ -static bool isfinite(uchar /*value*/) +bool isfinite(uchar /*value*/) { - return false; + return true; } -static bool isfinite(half /*value*/) +bool isfinite(half /*value*/) { - return false; + return true; +} +bool isfinite(uint16_t /*value*/) +{ + return true; +} + +/* The lower three bits of a device texture slot number indicate its type. + * These functions convert the slot ids from ImageManager "images" ones + * to device ones and vice verse. + */ +int type_index_to_flattened_slot(int slot, ImageDataType type) +{ + return (slot << IMAGE_DATA_TYPE_SHIFT) | (type); +} + +int flattened_slot_to_type_index(int flat_slot, ImageDataType *type) +{ + *type = (ImageDataType)(flat_slot & IMAGE_DATA_TYPE_MASK); + return flat_slot >> IMAGE_DATA_TYPE_SHIFT; } +const char* name_from_type(ImageDataType type) +{ + switch(type) { + case IMAGE_DATA_TYPE_FLOAT4: return "float4"; + case IMAGE_DATA_TYPE_BYTE4: return "byte4"; + case IMAGE_DATA_TYPE_HALF4: return "half4"; + case IMAGE_DATA_TYPE_FLOAT: return "float"; + case IMAGE_DATA_TYPE_BYTE: return "byte"; + case IMAGE_DATA_TYPE_HALF: return "half"; + case IMAGE_DATA_TYPE_USHORT4: return "ushort4"; + case IMAGE_DATA_TYPE_USHORT: return "ushort"; + case IMAGE_DATA_NUM_TYPES: + assert(!"System enumerator type, should never be used"); + return ""; + } + assert(!"Unhandled image data type"); + return ""; +} + +} // namespace + ImageManager::ImageManager(const DeviceInfo& info) { need_update = true; @@ -86,12 +129,12 @@ bool ImageManager::set_animation_frame_update(int frame) device_memory *ImageManager::image_memory(int flat_slot) { - ImageDataType type; - int slot = flattened_slot_to_type_index(flat_slot, &type); + ImageDataType type; + int slot = flattened_slot_to_type_index(flat_slot, &type); - Image *img = images[type][slot]; + Image *img = images[type][slot]; - return img->mem; + return img->mem; } bool ImageManager::get_image_metadata(int flat_slot, @@ -129,10 +172,12 @@ bool ImageManager::get_image_metadata(const string& filename, if(metadata.is_float) { metadata.is_linear = true; - metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_FLOAT4 : IMAGE_DATA_TYPE_FLOAT; + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_FLOAT4 + : IMAGE_DATA_TYPE_FLOAT; } else { - metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_BYTE4 : IMAGE_DATA_TYPE_BYTE; + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_BYTE4 + : IMAGE_DATA_TYPE_BYTE; } return true; @@ -144,7 +189,8 @@ bool ImageManager::get_image_metadata(const string& filename, return false; } if(path_is_directory(filename)) { - VLOG(1) << "File '" << filename << "' is a directory, can't use as image."; + VLOG(1) << "File '" << filename + << "' is a directory, can't use as image."; return false; } @@ -164,23 +210,27 @@ bool ImageManager::get_image_metadata(const string& filename, metadata.height = spec.height; metadata.depth = spec.depth; - /* check the main format, and channel formats; - * if any take up more than one byte, we'll need a float texture slot */ - if(spec.format.basesize() > 1) { + + /* Check the main format, and channel formats. */ + size_t channel_size = spec.format.basesize(); + + if(spec.format.is_floating_point()) { metadata.is_float = true; metadata.is_linear = true; } for(size_t channel = 0; channel < spec.channelformats.size(); channel++) { - if(spec.channelformats[channel].basesize() > 1) { + channel_size = max(channel_size, spec.channelformats[channel].basesize()); + if(spec.channelformats[channel].is_floating_point()) { metadata.is_float = true; metadata.is_linear = true; } } /* check if it's half float */ - if(spec.format == TypeDesc::HALF) + if(spec.format == TypeDesc::HALF) { metadata.is_half = true; + } /* basic color space detection, not great but better than nothing * before we do OpenColorIO integration */ @@ -203,13 +253,20 @@ bool ImageManager::get_image_metadata(const string& filename, metadata.channels = spec.nchannels; if(metadata.is_half) { - metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_HALF4 : IMAGE_DATA_TYPE_HALF; + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_HALF4 + : IMAGE_DATA_TYPE_HALF; } else if(metadata.is_float) { - metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_FLOAT4 : IMAGE_DATA_TYPE_FLOAT; + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_FLOAT4 + : IMAGE_DATA_TYPE_FLOAT; + } + else if(spec.format == TypeDesc::USHORT) { + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_USHORT4 + : IMAGE_DATA_TYPE_USHORT; } else { - metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_BYTE4 : IMAGE_DATA_TYPE_BYTE; + metadata.type = (metadata.channels > 1) ? IMAGE_DATA_TYPE_BYTE4 + : IMAGE_DATA_TYPE_BYTE; } in->close(); @@ -218,46 +275,6 @@ bool ImageManager::get_image_metadata(const string& filename, return true; } -int ImageManager::max_flattened_slot(ImageDataType type) -{ - if(tex_num_images[type] == 0) { - /* No textures for the type, no slots needs allocation. */ - return 0; - } - return type_index_to_flattened_slot(tex_num_images[type], type); -} - -/* The lower three bits of a device texture slot number indicate its type. - * These functions convert the slot ids from ImageManager "images" ones - * to device ones and vice verse. - */ -int ImageManager::type_index_to_flattened_slot(int slot, ImageDataType type) -{ - return (slot << IMAGE_DATA_TYPE_SHIFT) | (type); -} - -int ImageManager::flattened_slot_to_type_index(int flat_slot, ImageDataType *type) -{ - *type = (ImageDataType)(flat_slot & IMAGE_DATA_TYPE_MASK); - return flat_slot >> IMAGE_DATA_TYPE_SHIFT; -} - -string ImageManager::name_from_type(int type) -{ - if(type == IMAGE_DATA_TYPE_FLOAT4) - return "float4"; - else if(type == IMAGE_DATA_TYPE_FLOAT) - return "float"; - else if(type == IMAGE_DATA_TYPE_BYTE) - return "byte"; - else if(type == IMAGE_DATA_TYPE_HALF4) - return "half4"; - else if(type == IMAGE_DATA_TYPE_HALF) - return "half"; - else - return "byte4"; -} - static bool image_equals(ImageManager::Image *image, const string& filename, void *builtin_data, @@ -329,14 +346,16 @@ int ImageManager::add_image(const string& filename, } /* Count if we're over the limit. - * Very unlikely, since max_num_images is insanely big. But better safe than sorry. */ + * Very unlikely, since max_num_images is insanely big. But better safe + * than sorry. + */ int tex_count = 0; for(int type = 0; type < IMAGE_DATA_NUM_TYPES; type++) { tex_count += tex_num_images[type]; } if(tex_count > max_num_images) { - printf("ImageManager::add_image: Reached image limit (%d), skipping '%s'\n", - max_num_images, filename.c_str()); + printf("ImageManager::add_image: Reached image limit (%d), " + "skipping '%s'\n", max_num_images, filename.c_str()); return -1; } @@ -493,7 +512,6 @@ bool ImageManager::file_load_image(Image *img, int texture_limit, device_vector& tex_img) { - const StorageType alpha_one = (FileFormat == TypeDesc::UINT8)? 255 : 1; ImageInput *in = NULL; if(!file_load_image_generic(img, &in)) { return false; @@ -583,15 +601,22 @@ bool ImageManager::file_load_image(Image *img, */ bool is_rgba = (type == IMAGE_DATA_TYPE_FLOAT4 || type == IMAGE_DATA_TYPE_HALF4 || - type == IMAGE_DATA_TYPE_BYTE4); + type == IMAGE_DATA_TYPE_BYTE4 || + type == IMAGE_DATA_TYPE_USHORT4); if(is_rgba) { + const StorageType one = util_image_cast_from_float(1.0f); + if(cmyk) { /* CMYK */ for(size_t i = num_pixels-1, pixel = 0; pixel < num_pixels; pixel++, i--) { - pixels[i*4+2] = (pixels[i*4+2]*pixels[i*4+3])/255; - pixels[i*4+1] = (pixels[i*4+1]*pixels[i*4+3])/255; - pixels[i*4+0] = (pixels[i*4+0]*pixels[i*4+3])/255; - pixels[i*4+3] = alpha_one; + float c = util_image_cast_to_float(pixels[i*4+0]); + float m = util_image_cast_to_float(pixels[i*4+1]); + float y = util_image_cast_to_float(pixels[i*4+2]); + float k = util_image_cast_to_float(pixels[i*4+3]); + pixels[i*4+0] = util_image_cast_from_float((1.0f - c) * (1.0f - k)); + pixels[i*4+1] = util_image_cast_from_float((1.0f - m) * (1.0f - k)); + pixels[i*4+2] = util_image_cast_from_float((1.0f - y) * (1.0f - k)); + pixels[i*4+3] = one; } } else if(components == 2) { @@ -606,7 +631,7 @@ bool ImageManager::file_load_image(Image *img, else if(components == 3) { /* RGB */ for(size_t i = num_pixels-1, pixel = 0; pixel < num_pixels; pixel++, i--) { - pixels[i*4+3] = alpha_one; + pixels[i*4+3] = one; pixels[i*4+2] = pixels[i*3+2]; pixels[i*4+1] = pixels[i*3+1]; pixels[i*4+0] = pixels[i*3+0]; @@ -615,7 +640,7 @@ bool ImageManager::file_load_image(Image *img, else if(components == 1) { /* grayscale */ for(size_t i = num_pixels-1, pixel = 0; pixel < num_pixels; pixel++, i--) { - pixels[i*4+3] = alpha_one; + pixels[i*4+3] = one; pixels[i*4+2] = pixels[i]; pixels[i*4+1] = pixels[i]; pixels[i*4+0] = pixels[i]; @@ -623,7 +648,7 @@ bool ImageManager::file_load_image(Image *img, } if(img->use_alpha == false) { for(size_t i = num_pixels-1, pixel = 0; pixel < num_pixels; pixel++, i--) { - pixels[i*4+3] = alpha_one; + pixels[i*4+3] = one; } } } @@ -711,7 +736,8 @@ void ImageManager::device_load_image(Device *device, /* Slot assignment */ int flat_slot = type_index_to_flattened_slot(slot, type); - img->mem_name = string_printf("__tex_image_%s_%03d", name_from_type(type).c_str(), flat_slot); + img->mem_name = string_printf("__tex_image_%s_%03d", + name_from_type(type), flat_slot); /* Free previous texture in slot. */ if(img->mem) { @@ -843,14 +869,61 @@ void ImageManager::device_load_image(Device *device, thread_scoped_lock device_lock(device_mutex); tex_img->copy_to_device(); } + else if(type == IMAGE_DATA_TYPE_USHORT) { + device_vector *tex_img + = new device_vector(device, img->mem_name.c_str(), MEM_TEXTURE); + + if(!file_load_image(img, + type, + texture_limit, + *tex_img)) { + /* on failure to load, we set a 1x1 pixels pink image */ + thread_scoped_lock device_lock(device_mutex); + uint16_t *pixels = (uint16_t*)tex_img->alloc(1, 1); + + pixels[0] = (TEX_IMAGE_MISSING_R * 65535); + } + + img->mem = tex_img; + img->mem->interpolation = img->interpolation; + img->mem->extension = img->extension; + + thread_scoped_lock device_lock(device_mutex); + tex_img->copy_to_device(); + } + else if(type == IMAGE_DATA_TYPE_USHORT4) { + device_vector *tex_img + = new device_vector(device, img->mem_name.c_str(), MEM_TEXTURE); + + if(!file_load_image(img, + type, + texture_limit, + *tex_img)) { + /* on failure to load, we set a 1x1 pixels pink image */ + thread_scoped_lock device_lock(device_mutex); + uint16_t *pixels = (uint16_t*)tex_img->alloc(1, 1); + + pixels[0] = (TEX_IMAGE_MISSING_R * 65535); + pixels[1] = (TEX_IMAGE_MISSING_G * 65535); + pixels[2] = (TEX_IMAGE_MISSING_B * 65535); + pixels[3] = (TEX_IMAGE_MISSING_A * 65535); + } + + img->mem = tex_img; + img->mem->interpolation = img->interpolation; + img->mem->extension = img->extension; + + thread_scoped_lock device_lock(device_mutex); + tex_img->copy_to_device(); + } else if(type == IMAGE_DATA_TYPE_HALF) { device_vector *tex_img = new device_vector(device, img->mem_name.c_str(), MEM_TEXTURE); if(!file_load_image(img, - type, - texture_limit, - *tex_img)) { + type, + texture_limit, + *tex_img)) { /* on failure to load, we set a 1x1 pixels pink image */ thread_scoped_lock device_lock(device_mutex); half *pixels = (half*)tex_img->alloc(1, 1); @@ -865,7 +938,6 @@ void ImageManager::device_load_image(Device *device, thread_scoped_lock device_lock(device_mutex); tex_img->copy_to_device(); } - img->need_load = false; } @@ -971,5 +1043,15 @@ void ImageManager::device_free(Device *device) } } -CCL_NAMESPACE_END +void ImageManager::collect_statistics(RenderStats *stats) +{ + for(int type = 0; type < IMAGE_DATA_NUM_TYPES; type++) { + foreach(const Image *image, images[type]) { + stats->image.textures.add_entry( + NamedSizeEntry(path_filename(image->filename), + image->mem->memory_size())); + } + } +} +CCL_NAMESPACE_END diff --git a/intern/cycles/render/image.h b/intern/cycles/render/image.h index 4fd09adaa644..d94ebe564e35 100644 --- a/intern/cycles/render/image.h +++ b/intern/cycles/render/image.h @@ -29,6 +29,7 @@ CCL_NAMESPACE_BEGIN class Device; class Progress; +class RenderStats; class Scene; class ImageMetaData { @@ -89,6 +90,8 @@ class ImageManager { device_memory *image_memory(int flat_slot); + void collect_statistics(RenderStats *stats); + bool need_update; /* NOTE: Here pixels_size is a size of storage, which equals to @@ -149,16 +152,11 @@ class ImageManager { int texture_limit, device_vector& tex_img); - int max_flattened_slot(ImageDataType type); - int type_index_to_flattened_slot(int slot, ImageDataType type); - int flattened_slot_to_type_index(int flat_slot, ImageDataType *type); - string name_from_type(int type); - void device_load_image(Device *device, Scene *scene, ImageDataType type, int slot, - Progress *progess); + Progress *progress); void device_free_image(Device *device, ImageDataType type, int slot); @@ -167,4 +165,3 @@ class ImageManager { CCL_NAMESPACE_END #endif /* __IMAGE_H__ */ - diff --git a/intern/cycles/render/integrator.cpp b/intern/cycles/render/integrator.cpp index 9c276bcab31b..d86eb8fc5d32 100644 --- a/intern/cycles/render/integrator.cpp +++ b/intern/cycles/render/integrator.cpp @@ -118,7 +118,7 @@ void Integrator::device_update(Device *device, DeviceScene *dscene, Scene *scene } /* Transparent Shadows - * We only need to enable transparent shadows, if we actually have + * We only need to enable transparent shadows, if we actually have * transparent shaders in the scene. Otherwise we can disable it * to improve performance a bit. */ kintegrator->transparent_shadows = false; @@ -141,7 +141,7 @@ void Integrator::device_update(Device *device, DeviceScene *dscene, Scene *scene kintegrator->use_ambient_occlusion = ((Pass::contains(scene->film->passes, PASS_AO)) || dscene->data.background.ao_factor != 0.0f); - + kintegrator->sample_clamp_direct = (sample_clamp_direct == 0.0f)? FLT_MAX: sample_clamp_direct*3.0f; kintegrator->sample_clamp_indirect = (sample_clamp_indirect == 0.0f)? FLT_MAX: sample_clamp_indirect*3.0f; @@ -236,4 +236,3 @@ void Integrator::tag_update(Scene *scene) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/integrator.h b/intern/cycles/render/integrator.h index 3cb430d72b40..f68400ac416f 100644 --- a/intern/cycles/render/integrator.h +++ b/intern/cycles/render/integrator.h @@ -75,7 +75,7 @@ class Integrator : public Node { NUM_METHODS, }; - + Method method; SamplingPattern sampling_pattern; @@ -95,4 +95,3 @@ class Integrator : public Node { CCL_NAMESPACE_END #endif /* __INTEGRATOR_H__ */ - diff --git a/intern/cycles/render/light.cpp b/intern/cycles/render/light.cpp index 20c6a53e58fb..3580f4a8eebd 100644 --- a/intern/cycles/render/light.cpp +++ b/intern/cycles/render/light.cpp @@ -548,7 +548,7 @@ void LightManager::device_update_background(Device *device, /* get the resolution from the light's size (we stuff it in there) */ int2 res = make_int2(background_light->map_resolution, background_light->map_resolution/2); /* If the resolution isn't set manually, try to find an environment texture. */ - if (res.x == 0) { + if(res.x == 0) { Shader *shader = (scene->background->shader) ? scene->background->shader : scene->default_background; foreach(ShaderNode *node, shader->graph->nodes) { if(node->type == EnvironmentTextureNode::node_type) { @@ -560,12 +560,12 @@ void LightManager::device_update_background(Device *device, } } } - if (res.x > 0 && res.y > 0) { + if(res.x > 0 && res.y > 0) { VLOG(2) << "Automatically set World MIS resolution to " << res.x << " by " << res.y << "\n"; } } /* If it's still unknown, just use the default. */ - if (res.x == 0 || res.y == 0) { + if(res.x == 0 || res.y == 0) { res = make_int2(1024, 512); VLOG(2) << "Setting World MIS resolution to default\n"; } @@ -586,7 +586,7 @@ void LightManager::device_update_background(Device *device, double time_start = time_dt(); if(max(res.x, res.y) < 512) { /* Small enough resolution, faster to do single-threaded. */ - background_cdf(0, res.x, res.x, res.y, &pixels, cond_cdf); + background_cdf(0, res.y, res.x, res.y, &pixels, cond_cdf); } else { /* Threaded evaluation for large resolution. */ @@ -759,7 +759,7 @@ void LightManager::device_update_points(Device *, float area = len(axisu)*len(axisv); float invarea = (area > 0.0f)? 1.0f/area: 1.0f; float3 dir = light->dir; - + dir = safe_normalize(dir); if(light->use_mis && area > 0.0f) @@ -788,7 +788,7 @@ void LightManager::device_update_points(Device *, float spot_angle = cosf(light->spot_angle*0.5f); float spot_smooth = (1.0f - spot_angle)*light->spot_smooth; float3 dir = light->dir; - + dir = safe_normalize(dir); if(light->use_mis && radius > 0.0f) @@ -1027,4 +1027,3 @@ void LightManager::device_update_ies(DeviceScene *dscene) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/light.h b/intern/cycles/render/light.h index 5f8677ee2f24..32a911dc2560 100644 --- a/intern/cycles/render/light.h +++ b/intern/cycles/render/light.h @@ -140,4 +140,3 @@ class LightManager { CCL_NAMESPACE_END #endif /* __LIGHT_H__ */ - diff --git a/intern/cycles/render/mesh.cpp b/intern/cycles/render/mesh.cpp index 7a9d604244df..ade575a52d6e 100644 --- a/intern/cycles/render/mesh.cpp +++ b/intern/cycles/render/mesh.cpp @@ -27,6 +27,7 @@ #include "render/nodes.h" #include "render/object.h" #include "render/scene.h" +#include "render/stats.h" #include "kernel/osl/osl_globals.h" @@ -2015,8 +2016,8 @@ void MeshManager::device_update_displacement_images(Device *device, } void MeshManager::device_update_volume_images(Device *device, - Scene *scene, - Progress& progress) + Scene *scene, + Progress& progress) { progress.set_status("Updating Volume Images"); TaskPool pool; @@ -2043,11 +2044,11 @@ void MeshManager::device_update_volume_images(Device *device, foreach(int slot, volume_images) { pool.push(function_bind(&ImageManager::device_update_slot, - image_manager, - device, - scene, - slot, - &progress)); + image_manager, + device, + scene, + slot, + &progress)); } pool.wait_work(); } @@ -2276,6 +2277,15 @@ void MeshManager::tag_update(Scene *scene) scene->object_manager->need_update = true; } +void MeshManager::collect_statistics(const Scene *scene, RenderStats *stats) +{ + foreach(Mesh *mesh, scene->meshes) { + stats->mesh.geometry.add_entry( + NamedSizeEntry(string(mesh->name.c_str()), + mesh->get_total_size_in_bytes())); + } +} + bool Mesh::need_attribute(Scene *scene, AttributeStandard std) { if(std == ATTR_STD_NONE) diff --git a/intern/cycles/render/mesh.h b/intern/cycles/render/mesh.h index e370f8a2021f..444f03a3664c 100644 --- a/intern/cycles/render/mesh.h +++ b/intern/cycles/render/mesh.h @@ -38,6 +38,7 @@ class Device; class DeviceScene; class Mesh; class Progress; +class RenderStats; class Scene; class SceneParams; class AttributeRequest; @@ -351,6 +352,8 @@ class MeshManager { void create_volume_mesh(Scene *scene, Mesh *mesh, Progress &progress); + void collect_statistics(const Scene *scene, RenderStats *stats); + protected: /* Calculate verts/triangles/curves offsets in global arrays. */ void mesh_calc_offset(Scene *scene); @@ -381,11 +384,10 @@ class MeshManager { Progress& progress); void device_update_volume_images(Device *device, - Scene *scene, - Progress& progress); + Scene *scene, + Progress& progress); }; CCL_NAMESPACE_END #endif /* __MESH_H__ */ - diff --git a/intern/cycles/render/mesh_displace.cpp b/intern/cycles/render/mesh_displace.cpp index ad2a5713bcb5..53b9bfa34513 100644 --- a/intern/cycles/render/mesh_displace.cpp +++ b/intern/cycles/render/mesh_displace.cpp @@ -89,7 +89,7 @@ bool MeshManager::displace(Device *device, DeviceScene *dscene, Scene *scene, Me int object = object_index; int prim = mesh->tri_offset + i; float u, v; - + switch(j) { case 0: u = 1.0f; @@ -113,7 +113,7 @@ bool MeshManager::displace(Device *device, DeviceScene *dscene, Scene *scene, Me if(d_input_size == 0) return false; - + /* run device task */ device_vector d_output(device, "displace_output", MEM_READ_WRITE); d_output.alloc(d_input_size); @@ -319,4 +319,3 @@ bool MeshManager::displace(Device *device, DeviceScene *dscene, Scene *scene, Me } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/mesh_subdivision.cpp b/intern/cycles/render/mesh_subdivision.cpp index 9dd81eb67003..13fda99e9cca 100644 --- a/intern/cycles/render/mesh_subdivision.cpp +++ b/intern/cycles/render/mesh_subdivision.cpp @@ -613,4 +613,3 @@ void Mesh::tessellate(DiagSplit *split) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/mesh_volume.cpp b/intern/cycles/render/mesh_volume.cpp index d1c49b456ffc..3ee4124ba0f7 100644 --- a/intern/cycles/render/mesh_volume.cpp +++ b/intern/cycles/render/mesh_volume.cpp @@ -87,23 +87,31 @@ const float3 quads_normals[6] = { make_float3(0.0f, 0.0f, 1.0f), }; -static void create_quad(int3 corners[8], vector &vertices, vector &quads, int face_index) +static int add_vertex(int3 v, vector &vertices, int3 res, unordered_map &used_verts) { - size_t vertex_offset = vertices.size(); + size_t vert_key = v.x + v.y * (res.x+1) + v.z * (res.x+1)*(res.y+1); + unordered_map::iterator it = used_verts.find(vert_key); + if(it != used_verts.end()) { + return it->second; + } + + int vertex_offset = vertices.size(); + used_verts[vert_key] = vertex_offset; + vertices.push_back(v); + return vertex_offset; +} + +static void create_quad(int3 corners[8], vector &vertices, vector &quads, int3 res, unordered_map &used_verts, int face_index) +{ QuadData quad; - quad.v0 = vertex_offset + 0; - quad.v1 = vertex_offset + 1; - quad.v2 = vertex_offset + 2; - quad.v3 = vertex_offset + 3; + quad.v0 = add_vertex(corners[quads_indices[face_index][0]], vertices, res, used_verts); + quad.v1 = add_vertex(corners[quads_indices[face_index][1]], vertices, res, used_verts); + quad.v2 = add_vertex(corners[quads_indices[face_index][2]], vertices, res, used_verts); + quad.v3 = add_vertex(corners[quads_indices[face_index][3]], vertices, res, used_verts); quad.normal = quads_normals[face_index]; quads.push_back(quad); - - vertices.push_back(corners[quads_indices[face_index][0]]); - vertices.push_back(corners[quads_indices[face_index][1]]); - vertices.push_back(corners[quads_indices[face_index][2]]); - vertices.push_back(corners[quads_indices[face_index][3]]); } struct VolumeParams { @@ -159,9 +167,6 @@ class VolumeMeshBuilder { void generate_vertices_and_quads(vector &vertices_is, vector &quads); - void deduplicate_vertices(vector &vertices, - vector &quads); - void convert_object_space(const vector &vertices, vector &out_vertices); @@ -234,8 +239,6 @@ void VolumeMeshBuilder::create_mesh(vector &vertices, generate_vertices_and_quads(vertices_is, quads); - deduplicate_vertices(vertices_is, quads); - convert_object_space(vertices_is, vertices); convert_quads_to_tris(quads, indices, face_normals); @@ -245,10 +248,7 @@ void VolumeMeshBuilder::generate_vertices_and_quads( vector &vertices_is, vector &quads) { - /* Overallocation, we could count the number of quads and vertices to create - * in a pre-pass if memory becomes an issue. */ - vertices_is.reserve(number_of_nodes*8); - quads.reserve(number_of_nodes*6); + unordered_map used_verts; for(int z = 0; z < res.z; ++z) { for(int y = 0; y < res.y; ++y) { @@ -283,77 +283,38 @@ void VolumeMeshBuilder::generate_vertices_and_quads( voxel_index = compute_voxel_index(res, x - 1, y, z); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_X_MIN); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_X_MIN); } voxel_index = compute_voxel_index(res, x + 1, y, z); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_X_MAX); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_X_MAX); } voxel_index = compute_voxel_index(res, x, y - 1, z); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_Y_MIN); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_Y_MIN); } voxel_index = compute_voxel_index(res, x, y + 1, z); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_Y_MAX); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_Y_MAX); } voxel_index = compute_voxel_index(res, x, y, z - 1); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_Z_MIN); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_Z_MIN); } voxel_index = compute_voxel_index(res, x, y, z + 1); if(voxel_index == -1 || grid[voxel_index] == 0) { - create_quad(corners, vertices_is, quads, QUAD_Z_MAX); + create_quad(corners, vertices_is, quads, res, used_verts, QUAD_Z_MAX); } } } } } -void VolumeMeshBuilder::deduplicate_vertices(vector &vertices, - vector &quads) -{ - vector sorted_vertices = vertices; - std::sort(sorted_vertices.begin(), sorted_vertices.end()); - vector::iterator it = std::unique(sorted_vertices.begin(), sorted_vertices.end()); - sorted_vertices.resize(std::distance(sorted_vertices.begin(), it)); - - vector new_quads = quads; - - for(size_t i = 0; i < vertices.size(); ++i) { - for(size_t j = 0; j < sorted_vertices.size(); ++j) { - if(vertices[i] != sorted_vertices[j]) { - continue; - } - - for(int k = 0; k < quads.size(); ++k) { - if(quads[k].v0 == i) { - new_quads[k].v0 = j; - } - else if(quads[k].v1 == i) { - new_quads[k].v1 = j; - } - else if(quads[k].v2 == i) { - new_quads[k].v2 = j; - } - else if(quads[k].v3 == i) { - new_quads[k].v3 = j; - } - } - - break; - } - } - - vertices = sorted_vertices; - quads = new_quads; -} - void VolumeMeshBuilder::convert_object_space(const vector &vertices, vector &out_vertices) { diff --git a/intern/cycles/render/nodes.cpp b/intern/cycles/render/nodes.cpp index 680174f6d989..1943f8c3e2b2 100644 --- a/intern/cycles/render/nodes.cpp +++ b/intern/cycles/render/nodes.cpp @@ -82,7 +82,7 @@ Transform TextureMapping::compute_transform() mmat[1][y_mapping-1] = 1.0f; if(z_mapping != NONE) mmat[2][z_mapping-1] = 1.0f; - + float3 scale_clamped = scale; if(type == TEXTURE || type == NORMAL) { @@ -94,7 +94,7 @@ Transform TextureMapping::compute_transform() if(fabsf(scale.z) < 1e-5f) scale_clamped.z = signf(scale.z)*1e-5f; } - + Transform smat = transform_scale(scale_clamped); Transform rmat = transform_euler(rotation); Transform tmat = transform_translate(translation); @@ -137,12 +137,12 @@ bool TextureMapping::skip() return false; if(scale != make_float3(1.0f, 1.0f, 1.0f)) return false; - + if(x_mapping != X || y_mapping != Y || z_mapping != Z) return false; if(use_minmax) return false; - + return true; } @@ -520,7 +520,7 @@ void EnvironmentTextureNode::compile(SVMCompiler& compiler) compiler.stack_assign_if_linked(alpha_out), srgb), projection); - + tex_mapping.compile_end(compiler, vector_in, vector_offset); } else { @@ -612,7 +612,7 @@ static void sky_texture_precompute_old(SunSky *sunsky, float3 dir, float turbidi * zenith_Y/x/y is now radiance_x/y/z * perez_Y/x/y is now config_x/y/z */ - + float2 spherical = sky_spherical_coordinates(dir); float theta = spherical.x; float phi = spherical.y; @@ -676,12 +676,12 @@ static void sky_texture_precompute_new(SunSky *sunsky, float3 dir, float turbidi float2 spherical = sky_spherical_coordinates(dir); float theta = spherical.x; float phi = spherical.y; - + /* Clamp Turbidity */ - turbidity = clamp(turbidity, 0.0f, 10.0f); - + turbidity = clamp(turbidity, 0.0f, 10.0f); + /* Clamp to Horizon */ - theta = clamp(theta, 0.0f, M_PI_2_F); + theta = clamp(theta, 0.0f, M_PI_2_F); sunsky->theta = theta; sunsky->phi = phi; @@ -773,7 +773,7 @@ void SkyTextureNode::compile(OSLCompiler& compiler) sky_texture_precompute_new(&sunsky, sun_direction, turbidity, ground_albedo); else assert(false); - + compiler.parameter(this, "type"); compiler.parameter("theta", sunsky.theta); compiler.parameter("phi", sunsky.phi); @@ -913,7 +913,23 @@ NODE_DEFINE(VoronoiTextureNode) coloring_enum.insert("cells", NODE_VORONOI_CELLS); SOCKET_ENUM(coloring, "Coloring", coloring_enum, NODE_VORONOI_INTENSITY); + static NodeEnum metric; + metric.insert("distance", NODE_VORONOI_DISTANCE); + metric.insert("manhattan", NODE_VORONOI_MANHATTAN); + metric.insert("chebychev", NODE_VORONOI_CHEBYCHEV); + metric.insert("minkowski", NODE_VORONOI_MINKOWSKI); + SOCKET_ENUM(metric, "Distance Metric", metric, NODE_VORONOI_INTENSITY); + + static NodeEnum feature_enum; + feature_enum.insert("F1", NODE_VORONOI_F1); + feature_enum.insert("F2", NODE_VORONOI_F2); + feature_enum.insert("F3", NODE_VORONOI_F3); + feature_enum.insert("F4", NODE_VORONOI_F4); + feature_enum.insert("F2F1", NODE_VORONOI_F2F1); + SOCKET_ENUM(feature, "Feature", feature_enum, NODE_VORONOI_INTENSITY); + SOCKET_IN_FLOAT(scale, "Scale", 1.0f); + SOCKET_IN_FLOAT(exponent, "Exponent", 0.5f); SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED); SOCKET_OUT_COLOR(color, "Color"); @@ -931,19 +947,32 @@ void VoronoiTextureNode::compile(SVMCompiler& compiler) { ShaderInput *scale_in = input("Scale"); ShaderInput *vector_in = input("Vector"); + ShaderInput *exponent_in = input("Exponent"); ShaderOutput *color_out = output("Color"); ShaderOutput *fac_out = output("Fac"); + if(vector_in->link) compiler.stack_assign(vector_in); + if(scale_in->link) compiler.stack_assign(scale_in); + if(exponent_in->link) compiler.stack_assign(exponent_in); + int vector_offset = tex_mapping.compile_begin(compiler, vector_in); compiler.add_node(NODE_TEX_VORONOI, - coloring, compiler.encode_uchar4( - compiler.stack_assign_if_linked(scale_in), vector_offset, + coloring, + metric, + feature + ), + compiler.encode_uchar4( + compiler.stack_assign_if_linked(scale_in), + compiler.stack_assign_if_linked(exponent_in), compiler.stack_assign(fac_out), - compiler.stack_assign(color_out)), - __float_as_int(scale)); + compiler.stack_assign(color_out) + )); + compiler.add_node( + __float_as_int(scale), + __float_as_int(exponent)); tex_mapping.compile_end(compiler, vector_in, vector_offset); } @@ -953,6 +982,8 @@ void VoronoiTextureNode::compile(OSLCompiler& compiler) tex_mapping.compile(compiler); compiler.parameter(this, "coloring"); + compiler.parameter(this, "metric"); + compiler.parameter(this, "feature"); compiler.add(this, "node_voronoi_texture"); } @@ -1296,7 +1327,7 @@ void CheckerTextureNode::compile(SVMCompiler& compiler) ShaderInput *color1_in = input("Color1"); ShaderInput *color2_in = input("Color2"); ShaderInput *scale_in = input("Scale"); - + ShaderOutput *color_out = output("Color"); ShaderOutput *fac_out = output("Fac"); @@ -1371,7 +1402,7 @@ void BrickTextureNode::compile(SVMCompiler& compiler) ShaderInput *bias_in = input("Bias"); ShaderInput *brick_width_in = input("Brick Width"); ShaderInput *row_height_in = input("Row Height"); - + ShaderOutput *color_out = output("Color"); ShaderOutput *fac_out = output("Fac"); @@ -1393,7 +1424,7 @@ void BrickTextureNode::compile(SVMCompiler& compiler) compiler.stack_assign_if_linked(color_out), compiler.stack_assign_if_linked(fac_out), compiler.stack_assign_if_linked(mortar_smooth_in))); - + compiler.add_node(compiler.encode_uchar4(offset_frequency, squash_frequency), __float_as_int(scale), __float_as_int(mortar_size), @@ -2310,7 +2341,7 @@ ToonBsdfNode::ToonBsdfNode() void ToonBsdfNode::compile(SVMCompiler& compiler) { closure = component; - + BsdfNode::compile(compiler, input("Size"), input("Smooth")); } @@ -2795,14 +2826,14 @@ NODE_DEFINE(AmbientOcclusionNode) { NodeType* type = NodeType::add("ambient_occlusion", create, NodeType::SHADER); - SOCKET_INT(samples, "Samples", 8); + SOCKET_INT(samples, "Samples", 16); - SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f)); + SOCKET_IN_COLOR(color, "Color", make_float3(1.0f, 1.0f, 1.0f)); SOCKET_IN_FLOAT(distance, "Distance", 1.0f); SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL); SOCKET_BOOLEAN(inside, "Inside", false); - SOCKET_BOOLEAN(only_local, "Only Local", true); + SOCKET_BOOLEAN(only_local, "Only Local", false); SOCKET_OUT_COLOR(color, "Color"); SOCKET_OUT_FLOAT(ao, "AO"); @@ -2825,7 +2856,7 @@ void AmbientOcclusionNode::compile(SVMCompiler& compiler) int flags = (inside? NODE_AO_INSIDE : 0) | (only_local? NODE_AO_ONLY_LOCAL : 0); - if (!distance_in->link && distance == 0.0f) { + if(!distance_in->link && distance == 0.0f) { flags |= NODE_AO_GLOBAL_RADIUS; } @@ -2864,7 +2895,7 @@ void VolumeNode::compile(SVMCompiler& compiler, ShaderInput *param1, ShaderInput compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in)); else compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color); - + compiler.add_node(NODE_CLOSURE_VOLUME, compiler.encode_uchar4(closure, (param1)? compiler.stack_assign(param1): SVM_STACK_INVALID, @@ -3061,6 +3092,139 @@ void PrincipledVolumeNode::compile(OSLCompiler& compiler) compiler.add(this, "node_principled_volume"); } +/* Principled Hair BSDF Closure */ + +NODE_DEFINE(PrincipledHairBsdfNode) +{ + NodeType* type = NodeType::add("principled_hair_bsdf", create, NodeType::SHADER); + + /* Color parametrization specified as enum. */ + static NodeEnum parametrization_enum; + parametrization_enum.insert("Direct coloring", NODE_PRINCIPLED_HAIR_REFLECTANCE); + parametrization_enum.insert("Melanin concentration", NODE_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION); + parametrization_enum.insert("Absorption coefficient", NODE_PRINCIPLED_HAIR_DIRECT_ABSORPTION); + SOCKET_ENUM(parametrization, "Parametrization", parametrization_enum, NODE_PRINCIPLED_HAIR_REFLECTANCE); + + /* Initialize sockets to their default values. */ + SOCKET_IN_COLOR(color, "Color", make_float3(0.017513f, 0.005763f, 0.002059f)); + SOCKET_IN_FLOAT(melanin, "Melanin", 0.8f); + SOCKET_IN_FLOAT(melanin_redness, "Melanin Redness", 1.0f); + SOCKET_IN_COLOR(tint, "Tint", make_float3(1.f, 1.f, 1.f)); + SOCKET_IN_VECTOR(absorption_coefficient, "Absorption Coefficient", make_float3(0.245531f, 0.52f, 1.365f), SocketType::VECTOR); + + SOCKET_IN_FLOAT(offset, "Offset", 2.f*M_PI_F/180.f); + SOCKET_IN_FLOAT(roughness, "Roughness", 0.3f); + SOCKET_IN_FLOAT(radial_roughness, "Radial Roughness", 0.3f); + SOCKET_IN_FLOAT(coat, "Coat", 0.0f); + SOCKET_IN_FLOAT(ior, "IOR", 1.55f); + + SOCKET_IN_FLOAT(random_roughness, "Random Roughness", 0.0f); + SOCKET_IN_FLOAT(random_color, "Random Color", 0.0f); + SOCKET_IN_FLOAT(random, "Random", 0.0f); + + SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL); + SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL); + + SOCKET_OUT_CLOSURE(BSDF, "BSDF"); + + return type; +} + +PrincipledHairBsdfNode::PrincipledHairBsdfNode() +: BsdfBaseNode(node_type) +{ + closure = CLOSURE_BSDF_HAIR_PRINCIPLED_ID; +} + +/* Enable retrieving Hair Info -> Random if Random isn't linked. */ +void PrincipledHairBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes) +{ + if(!input("Random")->link) { + attributes->add(ATTR_STD_CURVE_RANDOM); + } + ShaderNode::attributes(shader, attributes); +} + +/* Prepares the input data for the SVM shader. */ +void PrincipledHairBsdfNode::compile(SVMCompiler& compiler) +{ + compiler.add_node(NODE_CLOSURE_SET_WEIGHT, make_float3(1.0f, 1.0f, 1.0f)); + + ShaderInput *roughness_in = input("Roughness"); + ShaderInput *radial_roughness_in = input("Radial Roughness"); + ShaderInput *random_roughness_in = input("Random Roughness"); + ShaderInput *offset_in = input("Offset"); + ShaderInput *coat_in = input("Coat"); + ShaderInput *ior_in = input("IOR"); + ShaderInput *melanin_in = input("Melanin"); + ShaderInput *melanin_redness_in = input("Melanin Redness"); + ShaderInput *random_color_in = input("Random Color"); + + int color_ofs = compiler.stack_assign(input("Color")); + int tint_ofs = compiler.stack_assign(input("Tint")); + int absorption_coefficient_ofs = compiler.stack_assign(input("Absorption Coefficient")); + + ShaderInput *random_in = input("Random"); + int attr_random = random_in->link ? SVM_STACK_INVALID : compiler.attribute(ATTR_STD_CURVE_RANDOM); + + /* Encode all parameters into data nodes. */ + compiler.add_node(NODE_CLOSURE_BSDF, + /* Socket IDs can be packed 4 at a time into a single data packet */ + compiler.encode_uchar4(closure, + compiler.stack_assign_if_linked(roughness_in), + compiler.stack_assign_if_linked(radial_roughness_in), + compiler.closure_mix_weight_offset()), + /* The rest are stored as unsigned integers */ + __float_as_uint(roughness), + __float_as_uint(radial_roughness)); + + compiler.add_node(compiler.stack_assign_if_linked(input("Normal")), + compiler.encode_uchar4( + compiler.stack_assign_if_linked(offset_in), + compiler.stack_assign_if_linked(ior_in), + color_ofs, + parametrization), + __float_as_uint(offset), + __float_as_uint(ior)); + + compiler.add_node( + compiler.encode_uchar4( + compiler.stack_assign_if_linked(coat_in), + compiler.stack_assign_if_linked(melanin_in), + compiler.stack_assign_if_linked(melanin_redness_in), + absorption_coefficient_ofs), + __float_as_uint(coat), + __float_as_uint(melanin), + __float_as_uint(melanin_redness)); + + compiler.add_node( + compiler.encode_uchar4( + tint_ofs, + compiler.stack_assign_if_linked(random_in), + compiler.stack_assign_if_linked(random_color_in), + compiler.stack_assign_if_linked(random_roughness_in)), + __float_as_uint(random), + __float_as_uint(random_color), + __float_as_uint(random_roughness)); + + compiler.add_node( + compiler.encode_uchar4( + SVM_STACK_INVALID, + SVM_STACK_INVALID, + SVM_STACK_INVALID, + SVM_STACK_INVALID), + attr_random, + SVM_STACK_INVALID, + SVM_STACK_INVALID); +} + +/* Prepares the input data for the OSL shader. */ +void PrincipledHairBsdfNode::compile(OSLCompiler& compiler) +{ + compiler.parameter(this, "parametrization"); + compiler.add(this, "node_principled_hair_bsdf"); +} + /* Hair BSDF Closure */ NODE_DEFINE(HairBsdfNode) @@ -3158,7 +3322,7 @@ void GeometryNode::compile(SVMCompiler& compiler) geom_node = NODE_GEOMETRY_BUMP_DY; attr_node = NODE_ATTR_BUMP_DY; } - + out = output("Position"); if(!out->links.empty()) { compiler.add_node(geom_node, NODE_GEOM_P, compiler.stack_assign(out)); @@ -3287,7 +3451,7 @@ void TextureCoordinateNode::compile(SVMCompiler& compiler) attr_node = NODE_ATTR_BUMP_DY; geom_node = NODE_GEOMETRY_BUMP_DY; } - + out = output("Generated"); if(!out->links.empty()) { if(compiler.background) { @@ -3363,7 +3527,7 @@ void TextureCoordinateNode::compile(OSLCompiler& compiler) compiler.parameter("bump_offset", "dy"); else compiler.parameter("bump_offset", "center"); - + if(compiler.background) compiler.parameter("is_background", true); if(compiler.output_type() == SHADER_TYPE_VOLUME) @@ -3525,7 +3689,7 @@ void LightPathNode::compile(SVMCompiler& compiler) if(!out->links.empty()) { compiler.add_node(NODE_LIGHT_PATH, NODE_LP_transmission, compiler.stack_assign(out)); } - + out = output("Is Volume Scatter Ray"); if(!out->links.empty()) { compiler.add_node(NODE_LIGHT_PATH, NODE_LP_volume_scatter, compiler.stack_assign(out)); @@ -3535,7 +3699,7 @@ void LightPathNode::compile(SVMCompiler& compiler) if(!out->links.empty()) { compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_length, compiler.stack_assign(out)); } - + out = output("Ray Depth"); if(!out->links.empty()) { compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_depth, compiler.stack_assign(out)); @@ -3728,7 +3892,7 @@ void ParticleInfoNode::attributes(Shader *shader, AttributeRequestSet *attribute void ParticleInfoNode::compile(SVMCompiler& compiler) { ShaderOutput *out; - + out = output("Index"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_INDEX, compiler.stack_assign(out)); @@ -3738,22 +3902,22 @@ void ParticleInfoNode::compile(SVMCompiler& compiler) if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_RANDOM, compiler.stack_assign(out)); } - + out = output("Age"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_AGE, compiler.stack_assign(out)); } - + out = output("Lifetime"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_LIFETIME, compiler.stack_assign(out)); } - + out = output("Location"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_LOCATION, compiler.stack_assign(out)); } - + /* quaternion data is not yet supported by Cycles */ #if 0 out = output("Rotation"); @@ -3761,17 +3925,17 @@ void ParticleInfoNode::compile(SVMCompiler& compiler) compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_ROTATION, compiler.stack_assign(out)); } #endif - + out = output("Size"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_SIZE, compiler.stack_assign(out)); } - + out = output("Velocity"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_VELOCITY, compiler.stack_assign(out)); } - + out = output("Angular Velocity"); if(!out->links.empty()) { compiler.add_node(NODE_PARTICLE_INFO, NODE_INFO_PAR_ANGULAR_VELOCITY, compiler.stack_assign(out)); @@ -3824,7 +3988,7 @@ void HairInfoNode::attributes(Shader *shader, AttributeRequestSet *attributes) void HairInfoNode::compile(SVMCompiler& compiler) { ShaderOutput *out; - + out = output("Is Strand"); if(!out->links.empty()) { compiler.add_node(NODE_HAIR_INFO, NODE_INFO_CURVE_IS_STRAND, compiler.stack_assign(out)); @@ -4747,7 +4911,7 @@ void AttributeNode::compile(OSLCompiler& compiler) compiler.parameter("bump_offset", "dy"); else compiler.parameter("bump_offset", "center"); - + if(Attribute::name_standard(attribute.c_str()) != ATTR_STD_NONE) compiler.parameter("name", (string("geom:") + attribute.c_str()).c_str()); else @@ -5071,6 +5235,10 @@ NODE_DEFINE(MathNode) type_enum.insert("modulo", NODE_MATH_MODULO); type_enum.insert("absolute", NODE_MATH_ABSOLUTE); type_enum.insert("arctan2", NODE_MATH_ARCTAN2); + type_enum.insert("floor", NODE_MATH_FLOOR); + type_enum.insert("ceil", NODE_MATH_CEIL); + type_enum.insert("fract", NODE_MATH_FRACT); + type_enum.insert("sqrt", NODE_MATH_SQRT); SOCKET_ENUM(type, "Type", type_enum, NODE_MATH_ADD); SOCKET_BOOLEAN(use_clamp, "Use Clamp", false); @@ -5553,7 +5721,7 @@ void RGBRampNode::compile(OSLCompiler& compiler) compiler.parameter_color_array("ramp_color", ramp); compiler.parameter_array("ramp_alpha", ramp_alpha.data(), ramp_alpha.size()); compiler.parameter(this, "interpolate"); - + compiler.add(this, "node_rgb_ramp"); } @@ -5586,7 +5754,7 @@ void SetNormalNode::compile(SVMCompiler& compiler) void SetNormalNode::compile(OSLCompiler& compiler) { - compiler.add(this, "node_set_normal"); + compiler.add(this, "node_set_normal"); } /* OSLNode */ @@ -5707,7 +5875,7 @@ void NormalMapNode::attributes(Shader *shader, AttributeRequestSet *attributes) attributes->add(ATTR_STD_VERTEX_NORMAL); } - + ShaderNode::attributes(shader, attributes); } @@ -5752,7 +5920,7 @@ void NormalMapNode::compile(OSLCompiler& compiler) } compiler.parameter(this, "space"); - compiler.add(this, "node_normal_map"); + compiler.add(this, "node_normal_map"); } /* Tangent */ @@ -5797,7 +5965,7 @@ void TangentNode::attributes(Shader *shader, AttributeRequestSet *attributes) else attributes->add(ATTR_STD_GENERATED); } - + ShaderNode::attributes(shader, attributes); } @@ -5833,7 +6001,7 @@ void TangentNode::compile(OSLCompiler& compiler) compiler.parameter(this, "direction_type"); compiler.parameter(this, "axis"); - compiler.add(this, "node_tangent"); + compiler.add(this, "node_tangent"); } /* Bevel */ diff --git a/intern/cycles/render/nodes.h b/intern/cycles/render/nodes.h index be52cf40a17b..28bbe2de05ae 100644 --- a/intern/cycles/render/nodes.h +++ b/intern/cycles/render/nodes.h @@ -189,7 +189,9 @@ class VoronoiTextureNode : public TextureNode { virtual int get_group() { return NODE_GROUP_LEVEL_2; } NodeVoronoiColoring coloring; - float scale; + NodeVoronoiDistanceMetric metric; + NodeVoronoiFeature feature; + float scale, exponent; float3 vector; }; @@ -606,6 +608,45 @@ class PrincipledVolumeNode : public VolumeNode { float temperature; }; +/* Interface between the I/O sockets and the SVM/OSL backend. */ +class PrincipledHairBsdfNode : public BsdfBaseNode { +public: + SHADER_NODE_CLASS(PrincipledHairBsdfNode) + void attributes(Shader *shader, AttributeRequestSet *attributes); + + /* Longitudinal roughness. */ + float roughness; + /* Azimuthal roughness. */ + float radial_roughness; + /* Randomization factor for roughnesses. */ + float random_roughness; + /* Longitudinal roughness factor for only the diffuse bounce (shiny undercoat). */ + float coat; + /* Index of reflection. */ + float ior; + /* Cuticle tilt angle. */ + float offset; + /* Direct coloring's color. */ + float3 color; + /* Melanin concentration. */ + float melanin; + /* Melanin redness ratio. */ + float melanin_redness; + /* Dye color. */ + float3 tint; + /* Randomization factor for melanin quantities. */ + float random_color; + /* Absorption coefficient (unfiltered). */ + float3 absorption_coefficient; + + float3 normal; + float surface_mix_weight; + /* If linked, here will be the given random number. */ + float random; + /* Selected coloring parametrization. */ + NodePrincipledHairParametrization parametrization; +}; + class HairBsdfNode : public BsdfNode { public: SHADER_NODE_CLASS(HairBsdfNode) @@ -1121,4 +1162,3 @@ class VectorDisplacementNode : public ShaderNode { CCL_NAMESPACE_END #endif /* __NODES_H__ */ - diff --git a/intern/cycles/render/object.cpp b/intern/cycles/render/object.cpp index 4d64d8412065..e3f35c366d62 100644 --- a/intern/cycles/render/object.cpp +++ b/intern/cycles/render/object.cpp @@ -183,7 +183,7 @@ void Object::apply_transform(bool apply_to_motion) { if(!mesh || tfm == transform_identity()) return; - + /* triangles */ if(mesh->verts.size()) { /* store matrix to transform later. when accessing these as attributes we @@ -194,7 +194,7 @@ void Object::apply_transform(bool apply_to_motion) /* apply to mesh vertices */ for(size_t i = 0; i < mesh->verts.size(); i++) mesh->verts[i] = transform_point(&tfm, mesh->verts[i]); - + if(apply_to_motion) { Attribute *attr = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION); @@ -840,4 +840,3 @@ void ObjectManager::tag_update(Scene *scene) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/object.h b/intern/cycles/render/object.h index c7212ae25f91..b80c4aef70ba 100644 --- a/intern/cycles/render/object.h +++ b/intern/cycles/render/object.h @@ -129,4 +129,3 @@ class ObjectManager { CCL_NAMESPACE_END #endif /* __OBJECT_H__ */ - diff --git a/intern/cycles/render/osl.cpp b/intern/cycles/render/osl.cpp index dde622bff8ab..496e9d9491a2 100644 --- a/intern/cycles/render/osl.cpp +++ b/intern/cycles/render/osl.cpp @@ -66,6 +66,14 @@ OSLShaderManager::~OSLShaderManager() { shading_system_free(); texture_system_free(); +#ifdef OSL_HAS_BLENDER_CLEANUP_FIX + /* There is a problem with llvm+osl: The order global destructors across + * different compilation units run cannot be guaranteed, on windows this means + * that the llvm destructors run before the osl destructors, causing a crash + * when the process exits. the OSL in svn has a special cleanup hack to + * sidestep this behavior */ + OSL::pvt::LLVM_Util::Cleanup(); +#endif } void OSLShaderManager::reset(Scene * /*scene*/) @@ -122,7 +130,7 @@ void OSLShaderManager::device_update(Device *device, DeviceScene *dscene, Scene shader->need_update = false; need_update = false; - + /* set texture system */ scene->image_manager->set_osl_texture_system((void*)ts); @@ -578,7 +586,7 @@ string OSLCompiler::compatible_name(ShaderNode *node, ShaderInput *input) /* strip whitespace */ while((i = sname.find(" ")) != string::npos) sname.replace(i, 1, ""); - + /* if output exists with the same name, add "In" suffix */ foreach(ShaderOutput *output, node->outputs) { if(input->name() == output->name()) { @@ -586,7 +594,7 @@ string OSLCompiler::compatible_name(ShaderNode *node, ShaderInput *input) break; } } - + return sname; } @@ -598,7 +606,7 @@ string OSLCompiler::compatible_name(ShaderNode *node, ShaderOutput *output) /* strip whitespace */ while((i = sname.find(" ")) != string::npos) sname.replace(i, 1, ""); - + /* if input exists with the same name, add "Out" suffix */ foreach(ShaderInput *input, node->inputs) { if(input->name() == output->name()) { @@ -606,7 +614,7 @@ string OSLCompiler::compatible_name(ShaderNode *node, ShaderOutput *output) break; } } - + return sname; } @@ -614,7 +622,7 @@ bool OSLCompiler::node_skip_input(ShaderNode *node, ShaderInput *input) { /* exception for output node, only one input is actually used * depending on the current shader type */ - + if(input->flags() & SocketType::SVM_INTERNAL) return true; @@ -704,7 +712,7 @@ void OSLCompiler::add(ShaderNode *node, const char *name, bool isfilepath) ss->Shader("displacement", name, id(node).c_str()); else assert(0); - + /* link inputs to other nodes */ foreach(ShaderInput *input, node->inputs) { if(input->link) { @@ -1250,4 +1258,3 @@ void OSLCompiler::parameter_color_array(const char * /*name*/, const array #include #include #include @@ -171,4 +172,3 @@ class OSLCompiler { CCL_NAMESPACE_END #endif /* __OSL_H__ */ - diff --git a/intern/cycles/render/particles.cpp b/intern/cycles/render/particles.cpp index e4be3306d7e4..0583556c8a9f 100644 --- a/intern/cycles/render/particles.cpp +++ b/intern/cycles/render/particles.cpp @@ -61,12 +61,12 @@ void ParticleSystemManager::device_update_particles(Device *, DeviceScene *dscen int num_particles = 1; for(size_t j = 0; j < scene->particle_systems.size(); j++) num_particles += scene->particle_systems[j]->particles.size(); - + KernelParticle *kparticles = dscene->particles.alloc(num_particles); - + /* dummy particle */ memset(kparticles, 0, sizeof(KernelParticle)); - + int i = 1; for(size_t j = 0; j < scene->particle_systems.size(); j++) { ParticleSystem *psys = scene->particle_systems[j]; @@ -74,7 +74,7 @@ void ParticleSystemManager::device_update_particles(Device *, DeviceScene *dscen for(size_t k = 0; k < psys->particles.size(); k++) { /* pack in texture */ Particle& pa = psys->particles[k]; - + kparticles[i].index = pa.index; kparticles[i].age = pa.age; kparticles[i].lifetime = pa.lifetime; @@ -83,13 +83,13 @@ void ParticleSystemManager::device_update_particles(Device *, DeviceScene *dscen kparticles[i].location = float3_to_float4(pa.location); kparticles[i].velocity = float3_to_float4(pa.velocity); kparticles[i].angular_velocity = float3_to_float4(pa.angular_velocity); - + i++; - + if(progress.get_cancel()) return; } } - + dscene->particles.copy_to_device(); } @@ -105,9 +105,9 @@ void ParticleSystemManager::device_update(Device *device, DeviceScene *dscene, S progress.set_status("Updating Particle Systems", "Copying Particles to device"); device_update_particles(device, dscene, scene, progress); - + if(progress.get_cancel()) return; - + need_update = false; } @@ -122,4 +122,3 @@ void ParticleSystemManager::tag_update(Scene * /*scene*/) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/particles.h b/intern/cycles/render/particles.h index 66d46114b3e1..7e7afd5d054b 100644 --- a/intern/cycles/render/particles.h +++ b/intern/cycles/render/particles.h @@ -69,4 +69,3 @@ class ParticleSystemManager { CCL_NAMESPACE_END #endif /* __PARTICLES_H__ */ - diff --git a/intern/cycles/render/scene.cpp b/intern/cycles/render/scene.cpp index c0f1ae0445e7..9f93fed139cb 100644 --- a/intern/cycles/render/scene.cpp +++ b/intern/cycles/render/scene.cpp @@ -319,7 +319,7 @@ bool Scene::need_global_attribute(AttributeStandard std) return need_motion() != MOTION_NONE; else if(std == ATTR_STD_MOTION_VERTEX_NORMAL) return need_motion() == MOTION_BLUR; - + return false; } @@ -379,5 +379,10 @@ void Scene::device_free() free_memory(false); } -CCL_NAMESPACE_END +void Scene::collect_statistics(RenderStats *stats) +{ + mesh_manager->collect_statistics(this, stats); + image_manager->collect_statistics(stats); +} +CCL_NAMESPACE_END diff --git a/intern/cycles/render/scene.h b/intern/cycles/render/scene.h index 6c67433c9fcb..dd8069537eb7 100644 --- a/intern/cycles/render/scene.h +++ b/intern/cycles/render/scene.h @@ -56,6 +56,7 @@ class ShaderManager; class Progress; class BakeManager; class BakeData; +class RenderStats; /* Scene Device Data */ @@ -255,6 +256,8 @@ class Scene { void reset(); void device_free(); + void collect_statistics(RenderStats *stats); + protected: /* Check if some heavy data worth logging was updated. * Mainly used to suppress extra annoying logging. @@ -267,4 +270,3 @@ class Scene { CCL_NAMESPACE_END #endif /* __SCENE_H__ */ - diff --git a/intern/cycles/render/session.cpp b/intern/cycles/render/session.cpp index bb636dd962ab..d0aa985b0350 100644 --- a/intern/cycles/render/session.cpp +++ b/intern/cycles/render/session.cpp @@ -364,7 +364,7 @@ bool Session::acquire_tile(Device *tile_device, RenderTile& rtile) if(!tile_manager.next_tile(tile, device_num)) return false; - + /* fill render tile */ rtile.x = tile_manager.state.buffer.full_x + tile->x; rtile.y = tile_manager.state.buffer.full_y + tile->y; @@ -502,6 +502,9 @@ void Session::map_neighbor_tiles(RenderTile *tiles, Device *tile_device) assert(tiles[4].buffers); device->map_neighbor_tiles(tile_device, tiles); + + /* The denoised result is written back to the original tile. */ + tiles[9] = tiles[4]; } void Session::unmap_neighbor_tiles(RenderTile *tiles, Device *tile_device) @@ -913,7 +916,7 @@ void Session::update_status_time(bool show_pause, bool show_done) substatus = string_printf("Path Tracing Sample %d/%d", progressive_sample+1, num_samples); - + if(show_pause) { status = "Paused"; } @@ -938,7 +941,7 @@ void Session::render() /* Add path trace task. */ DeviceTask task(DeviceTask::RENDER); - + task.acquire_tile = function_bind(&Session::acquire_tile, this, _1, _2); task.release_tile = function_bind(&Session::release_tile, this, _1); task.map_neighbor_tiles = function_bind(&Session::map_neighbor_tiles, this, _1, _2); diff --git a/intern/cycles/render/session.h b/intern/cycles/render/session.h index e63cad0d9777..61f62f8e7127 100644 --- a/intern/cycles/render/session.h +++ b/intern/cycles/render/session.h @@ -237,4 +237,3 @@ class Session { CCL_NAMESPACE_END #endif /* __SESSION_H__ */ - diff --git a/intern/cycles/render/shader.cpp b/intern/cycles/render/shader.cpp index 46e7d1b1d7bb..ac605305b946 100644 --- a/intern/cycles/render/shader.cpp +++ b/intern/cycles/render/shader.cpp @@ -313,7 +313,7 @@ void Shader::tag_update(Scene *scene) if(has_displacement && displacement_method == DISPLACE_BOTH) { attributes.add(ATTR_STD_POSITION_UNDISPLACED); } - + /* compare if the attributes changed, mesh manager will check * need_update_mesh, update the relevant meshes and clear it. */ if(attributes.modified(prev_attributes)) { @@ -398,7 +398,7 @@ ShaderManager *ShaderManager::create(Scene *scene, int shadingsystem) { manager = new SVMShaderManager(); } - + add_default(scene); return manager; @@ -413,7 +413,7 @@ uint ShaderManager::get_attribute_id(ustring name) if(it != unique_attribute_id.end()) return it->second; - + uint id = (uint)ATTR_STD_NUM + unique_attribute_id.size(); unique_attribute_id[name] = id; return id; @@ -432,10 +432,10 @@ int ShaderManager::get_shader_id(Shader *shader, bool smooth) /* smooth flag */ if(smooth) id |= SHADER_SMOOTH_NORMAL; - + /* default flags */ id |= SHADER_CAST_SHADOW|SHADER_AREA_LIGHT; - + return id; } @@ -696,4 +696,3 @@ float ShaderManager::linear_rgb_to_gray(float3 c) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/shader.h b/intern/cycles/render/shader.h index 0353da90013a..58314a1e3101 100644 --- a/intern/cycles/render/shader.h +++ b/intern/cycles/render/shader.h @@ -155,7 +155,7 @@ class Shader : public Node { }; /* Shader Manager virtual base class - * + * * From this the SVM and OSL shader managers are derived, that do the actual * shader compiling and device updating. */ @@ -223,4 +223,3 @@ class ShaderManager { CCL_NAMESPACE_END #endif /* __SHADER_H__ */ - diff --git a/intern/cycles/render/sobol.cpp b/intern/cycles/render/sobol.cpp index 6906667ac194..01dfafa2ed95 100644 --- a/intern/cycles/render/sobol.cpp +++ b/intern/cycles/render/sobol.cpp @@ -7,7 +7,7 @@ * http://web.maths.unsw.edu.au/~fkuo/sobol/ * * From these papers: - * + * * S. Joe and F. Y. Kuo, Remark on Algorithm 659: Implementing Sobol's quasirandom * sequence generator, ACM Trans. Math. Softw. 29, 49-57 (2003) * @@ -18,22 +18,22 @@ /* Copyright (c) 2008, Frances Y. Kuo and Stephen Joe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the names of the copyright holders nor the names of the * University of New South Wales and the University of Waikato * and its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE @@ -21284,21 +21284,20 @@ void sobol_generate_direction_vectors(uint vectors[][SOBOL_BITS], int dimensions if(L <= s) { for(uint i = 0; i < L; i++) - v[i] = m[i] << (31-i); + v[i] = m[i] << (31-i); } else { for(uint i = 0; i < s; i++) - v[i] = m[i] << (31-i); + v[i] = m[i] << (31-i); for(uint i = s; i < L; i++) { - v[i] = v[i-s] ^ (v[i-s] >> s); + v[i] = v[i-s] ^ (v[i-s] >> s); - for(uint k = 1; k < s; k++) - v[i] ^= (((a >> (s-1-k)) & 1) * v[i-k]); + for(uint k = 1; k < s; k++) + v[i] ^= (((a >> (s-1-k)) & 1) * v[i-k]); } } } } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/sobol.h b/intern/cycles/render/sobol.h index 9fbce4e14a54..d38857d2b351 100644 --- a/intern/cycles/render/sobol.h +++ b/intern/cycles/render/sobol.h @@ -29,4 +29,3 @@ void sobol_generate_direction_vectors(uint vectors[][SOBOL_BITS], int dimensions CCL_NAMESPACE_END #endif /* __SOBOL_H__ */ - diff --git a/intern/cycles/render/stats.cpp b/intern/cycles/render/stats.cpp new file mode 100644 index 000000000000..101d33fcf653 --- /dev/null +++ b/intern/cycles/render/stats.cpp @@ -0,0 +1,119 @@ +/* + * Copyright 2011-2018 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "render/stats.h" +#include "util/util_algorithm.h" +#include "util/util_foreach.h" +#include "util/util_string.h" + +CCL_NAMESPACE_BEGIN + +static int kIndentNumSpaces = 2; + +/* Named size entry. */ + +namespace { + +bool namedSizeEntryComparator(const NamedSizeEntry& a, const NamedSizeEntry& b) +{ + /* We sort in descending order. */ + return a.size > b.size; +} + +} // namespace + +NamedSizeEntry::NamedSizeEntry() + : name(""), + size(0) { +} + +NamedSizeEntry::NamedSizeEntry(const string& name, size_t size) + : name(name), + size(size) { +} + +/* Named size statistics. */ + +NamedSizeStats::NamedSizeStats() + : total_size(0) { +} + +void NamedSizeStats::add_entry(const NamedSizeEntry& entry) { + total_size += entry.size; + entries.push_back(entry); +} + +string NamedSizeStats::full_report(int indent_level) +{ + const string indent(indent_level * kIndentNumSpaces, ' '); + const string double_indent = indent + indent; + string result = ""; + result += string_printf("%sTotal memory: %s (%s)\n", + indent.c_str(), + string_human_readable_size(total_size).c_str(), + string_human_readable_number(total_size).c_str()); + sort(entries.begin(), entries.end(), namedSizeEntryComparator); + foreach(const NamedSizeEntry& entry, entries) { + result += string_printf( + "%s%-32s %s (%s)\n", + double_indent.c_str(), + entry.name.c_str(), + string_human_readable_size(entry.size).c_str(), + string_human_readable_number(entry.size).c_str()); + } + return result; +} + +/* Mesh statistics. */ + +MeshStats::MeshStats() { +} + +string MeshStats::full_report(int indent_level) +{ + const string indent(indent_level * kIndentNumSpaces, ' '); + string result = ""; + result += indent + "Geometry:\n" + geometry.full_report(indent_level + 1); + return result; +} + +/* Image statistics. */ + +ImageStats::ImageStats() { +} + +string ImageStats::full_report(int indent_level) +{ + const string indent(indent_level * kIndentNumSpaces, ' '); + string result = ""; + result += indent + "Textures:\n" + textures.full_report(indent_level + 1); + return result; +} + +/* Overall statistics. */ + +RenderStats::RenderStats() { +} + +string RenderStats::full_report() +{ + string result = ""; + result += "Mesh statistics:\n" + mesh.full_report(1); + result += "Image statistics:\n" + image.full_report(1); + return result; +} + +CCL_NAMESPACE_END diff --git a/intern/cycles/render/stats.h b/intern/cycles/render/stats.h new file mode 100644 index 000000000000..72d5f1dd93d6 --- /dev/null +++ b/intern/cycles/render/stats.h @@ -0,0 +1,104 @@ +/* + * Copyright 2011-2018 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __RENDER_STATS_H__ +#define __RENDER_STATS_H__ + +#include "util/util_string.h" +#include "util/util_vector.h" + +CCL_NAMESPACE_BEGIN + +/* Named statistics entry, which corresponds to a size. There is no real + * semantic around the units of size, it just should be the same for all + * entries. + * + * This is a generic entry foi all size-related statistics, which helps + * avoiding duplicating code for things like sorting. + */ +class NamedSizeEntry { +public: + NamedSizeEntry(); + NamedSizeEntry(const string& name, size_t size); + + string name; + size_t size; +}; + +/* Container of named size entries. Used, for example, to store per-mesh memory + * usage statistics. But also keeps track of overall memory usage of the + * container. + */ +class NamedSizeStats { +public: + NamedSizeStats(); + + /* Add entry to the statistics. */ + void add_entry(const NamedSizeEntry& entry); + + /* Generate full human-readable report. */ + string full_report(int indent_level = 0); + + /* Total size of all entries. */ + size_t total_size; + + /* NOTE: Is fine to read directly, but for adding use add_entry(), which + * makes sure all accumulating values are properly updated. + */ + vector entries; +}; + +/* Statistics about mesh in the render database. */ +class MeshStats { +public: + MeshStats(); + + /* Generate full human-readable report. */ + string full_report(int indent_level = 0); + + /* Input geometry statistics, this is what is coming as an input to render + * from. say, Blender. This does not include runtime or engine specific + * memory like BVH. + */ + NamedSizeStats geometry; +}; + +/* Statistics about images held in memory. */ +class ImageStats { +public: + ImageStats(); + + /* Generate full human-readable report. */ + string full_report(int indent_level = 0); + + NamedSizeStats textures; +}; + +/* Render process statistics. */ +class RenderStats { +public: + RenderStats(); + + /* Return full report as string. */ + string full_report(); + + MeshStats mesh; + ImageStats image; +}; + +CCL_NAMESPACE_END + +#endif /* __RENDER_STATS_H__ */ diff --git a/intern/cycles/render/svm.cpp b/intern/cycles/render/svm.cpp index 626f160786f5..44b7eeec6db4 100644 --- a/intern/cycles/render/svm.cpp +++ b/intern/cycles/render/svm.cpp @@ -71,12 +71,12 @@ void SVMShaderManager::device_update_shader(Scene *scene, scene->light_manager->need_update = true; } - /* The copy needs to be done inside the lock, if another thread resizes the array - * while memcpy is running, it'll be copying into possibly invalid/freed ram. + /* The copy needs to be done inside the lock, if another thread resizes the array + * while memcpy is running, it'll be copying into possibly invalid/freed ram. */ size_t global_nodes_size = global_svm_nodes->size(); global_svm_nodes->resize(global_nodes_size + svm_nodes.size()); - + /* Offset local SVM nodes to a global address space. */ int4& jump_node = (*global_svm_nodes)[shader->id]; jump_node.y = svm_nodes[0].y + global_nodes_size - 1; @@ -173,7 +173,7 @@ SVMCompiler::SVMCompiler(ShaderManager *shader_manager_, int SVMCompiler::stack_size(SocketType::Type type) { int size = 0; - + switch(type) { case SocketType::FLOAT: case SocketType::INT: @@ -192,14 +192,14 @@ int SVMCompiler::stack_size(SocketType::Type type) assert(0); break; } - + return size; } int SVMCompiler::stack_find_offset(int size) { int offset = -1; - + /* find free space in stack & mark as used */ for(int i = 0, num_unused = 0; i < SVM_STACK_SIZE; i++) { if(active_stack.users[i]) num_unused = 0; @@ -413,7 +413,7 @@ bool SVMCompiler::node_skip_input(ShaderNode * /*node*/, ShaderInput *input) /* nasty exception .. */ if(current_type == SHADER_TYPE_DISPLACEMENT && input->link && input->link->parent->special_type == SHADER_SPECIAL_TYPE_BUMP) return true; - + return false; } @@ -715,7 +715,7 @@ void SVMCompiler::compile_type(Shader *shader, ShaderGraph *graph, ShaderType ty /* get input in output node */ ShaderNode *node = graph->output(); ShaderInput *clin = NULL; - + switch(type) { case SHADER_TYPE_SURFACE: clin = node->input("Surface"); @@ -756,9 +756,9 @@ void SVMCompiler::compile_type(Shader *shader, ShaderGraph *graph, ShaderType ty if(shader->used) { if(clin->link) { bool generate = false; - + switch(type) { - case SHADER_TYPE_SURFACE: /* generate surface shader */ + case SHADER_TYPE_SURFACE: /* generate surface shader */ generate = true; shader->has_surface = true; break; @@ -936,4 +936,3 @@ SVMCompiler::CompilerState::CompilerState(ShaderGraph *graph) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/svm.h b/intern/cycles/render/svm.h index 7cf1e4ad7914..1d0613bbfdc2 100644 --- a/intern/cycles/render/svm.h +++ b/intern/cycles/render/svm.h @@ -224,4 +224,3 @@ class SVMCompiler { CCL_NAMESPACE_END #endif /* __SVM_H__ */ - diff --git a/intern/cycles/render/tables.cpp b/intern/cycles/render/tables.cpp index 536fdd0775e8..ddbb138f059f 100644 --- a/intern/cycles/render/tables.cpp +++ b/intern/cycles/render/tables.cpp @@ -115,4 +115,3 @@ void LookupTables::remove_table(size_t *offset) } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/tables.h b/intern/cycles/render/tables.h index bc261c2a74d2..09d961a9c3c2 100644 --- a/intern/cycles/render/tables.h +++ b/intern/cycles/render/tables.h @@ -51,4 +51,3 @@ class LookupTables { CCL_NAMESPACE_END #endif /* __TABLES_H__ */ - diff --git a/intern/cycles/render/tile.cpp b/intern/cycles/render/tile.cpp index a388f5dfc8b1..dc863b067b09 100644 --- a/intern/cycles/render/tile.cpp +++ b/intern/cycles/render/tile.cpp @@ -535,4 +535,3 @@ int TileManager::get_num_effective_samples() } CCL_NAMESPACE_END - diff --git a/intern/cycles/render/tile.h b/intern/cycles/render/tile.h index 2692c7cf9f06..f72f653f4c25 100644 --- a/intern/cycles/render/tile.h +++ b/intern/cycles/render/tile.h @@ -155,4 +155,3 @@ class TileManager { CCL_NAMESPACE_END #endif /* __TILE_H__ */ - diff --git a/intern/cycles/subd/subd_dice.cpp b/intern/cycles/subd/subd_dice.cpp index 8c426da4acff..c5ac54cfcc84 100644 --- a/intern/cycles/subd/subd_dice.cpp +++ b/intern/cycles/subd/subd_dice.cpp @@ -348,4 +348,3 @@ void QuadDice::dice(SubPatch& sub, EdgeFactors& ef) } CCL_NAMESPACE_END - diff --git a/intern/cycles/subd/subd_dice.h b/intern/cycles/subd/subd_dice.h index c0e32be18c4a..4617c782b3ad 100644 --- a/intern/cycles/subd/subd_dice.h +++ b/intern/cycles/subd/subd_dice.h @@ -81,7 +81,7 @@ class EdgeDice { * Edge tessellation factors and subpatch coordinates are as follows: * * tu1 - * P01 --------- P11 + * P01 --------- P11 * | | * tv0 | | tv1 * | | @@ -135,4 +135,3 @@ class QuadDice : public EdgeDice { CCL_NAMESPACE_END #endif /* __SUBD_DICE_H__ */ - diff --git a/intern/cycles/subd/subd_patch.cpp b/intern/cycles/subd/subd_patch.cpp index fa2fe2bf1131..f8f5aa25d19d 100644 --- a/intern/cycles/subd/subd_patch.cpp +++ b/intern/cycles/subd/subd_patch.cpp @@ -80,7 +80,7 @@ BoundBox LinearQuadPatch::bound() for(int i = 0; i < 4; i++) bbox.grow(hull[i]); - + return bbox; } @@ -110,9 +110,8 @@ BoundBox BicubicPatch::bound() for(int i = 0; i < 16; i++) bbox.grow(hull[i]); - + return bbox; } CCL_NAMESPACE_END - diff --git a/intern/cycles/subd/subd_patch.h b/intern/cycles/subd/subd_patch.h index 1bb81588835b..64ec8f709511 100644 --- a/intern/cycles/subd/subd_patch.h +++ b/intern/cycles/subd/subd_patch.h @@ -57,4 +57,3 @@ class BicubicPatch : public Patch { CCL_NAMESPACE_END #endif /* __SUBD_PATCH_H__ */ - diff --git a/intern/cycles/subd/subd_patch_table.cpp b/intern/cycles/subd/subd_patch_table.cpp index 63bf673a90bd..13a6f2845428 100644 --- a/intern/cycles/subd/subd_patch_table.cpp +++ b/intern/cycles/subd/subd_patch_table.cpp @@ -294,4 +294,3 @@ void PackedPatchTable::copy_adjusting_offsets(uint* dest, int doffset) } CCL_NAMESPACE_END - diff --git a/intern/cycles/subd/subd_patch_table.h b/intern/cycles/subd/subd_patch_table.h index 907f2dd6c28b..45be7051992e 100644 --- a/intern/cycles/subd/subd_patch_table.h +++ b/intern/cycles/subd/subd_patch_table.h @@ -60,4 +60,3 @@ struct PackedPatchTable { CCL_NAMESPACE_END #endif /* __SUBD_PATCH_TABLE_H__ */ - diff --git a/intern/cycles/subd/subd_split.cpp b/intern/cycles/subd/subd_split.cpp index d3bed6a5c53e..762612433593 100644 --- a/intern/cycles/subd/subd_split.cpp +++ b/intern/cycles/subd/subd_split.cpp @@ -86,7 +86,7 @@ int DiagSplit::T(Patch *patch, float2 Pstart, float2 Pend) if(tmax - tmin > params.split_threshold) return DSPLIT_NON_UNIFORM; - + return tmax; } @@ -258,4 +258,3 @@ void DiagSplit::split_quad(Patch *patch, QuadDice::SubPatch *subpatch) } CCL_NAMESPACE_END - diff --git a/intern/cycles/subd/subd_split.h b/intern/cycles/subd/subd_split.h index f869cc6a48e5..7a276b353824 100644 --- a/intern/cycles/subd/subd_split.h +++ b/intern/cycles/subd/subd_split.h @@ -57,4 +57,3 @@ class DiagSplit { CCL_NAMESPACE_END #endif /* __SUBD_SPLIT_H__ */ - diff --git a/intern/cycles/test/CMakeLists.txt b/intern/cycles/test/CMakeLists.txt index 46c525eb3bb1..332e0d8cc783 100644 --- a/intern/cycles/test/CMakeLists.txt +++ b/intern/cycles/test/CMakeLists.txt @@ -91,7 +91,8 @@ link_directories(${OPENIMAGEIO_LIBPATH} ${JPEG_LIBPATH} ${ZLIB_LIBPATH} ${TIFF_LIBPATH} - ${OPENEXR_LIBPATH}) + ${OPENEXR_LIBPATH} + ${OPENCOLORIO_LIBPATH}) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${PLATFORM_LINKFLAGS}") set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} ${PLATFORM_LINKFLAGS_DEBUG}") diff --git a/intern/cycles/util/CMakeLists.txt b/intern/cycles/util/CMakeLists.txt index 3b690860d53b..291f9a9fcaef 100644 --- a/intern/cycles/util/CMakeLists.txt +++ b/intern/cycles/util/CMakeLists.txt @@ -78,6 +78,7 @@ set(SRC_HEADERS util_sky_model.h util_sky_model_data.h util_avxf.h + util_avxb.h util_sseb.h util_ssef.h util_ssei.h @@ -98,7 +99,9 @@ set(SRC_HEADERS util_types_float3_impl.h util_types_float4.h util_types_float4_impl.h - util_types_int2.h + util_types_float8.h + util_types_float8_impl.h + util_types_int2.h util_types_int2_impl.h util_types_int3.h util_types_int3_impl.h @@ -116,6 +119,7 @@ set(SRC_HEADERS util_types_uint3_impl.h util_types_uint4.h util_types_uint4_impl.h + util_types_ushort4.h util_types_vector3.h util_types_vector3_impl.h util_vector.h diff --git a/intern/cycles/util/util_algorithm.h b/intern/cycles/util/util_algorithm.h index 5c79c00cc983..eb874713d439 100644 --- a/intern/cycles/util/util_algorithm.h +++ b/intern/cycles/util/util_algorithm.h @@ -30,4 +30,3 @@ using std::remove; CCL_NAMESPACE_END #endif /* __UTIL_ALGORITHM_H__ */ - diff --git a/intern/cycles/util/util_args.h b/intern/cycles/util/util_args.h index a53fc061758b..be6f2c2b9f11 100644 --- a/intern/cycles/util/util_args.h +++ b/intern/cycles/util/util_args.h @@ -29,4 +29,3 @@ OIIO_NAMESPACE_USING CCL_NAMESPACE_END #endif /* __UTIL_ARGS_H__ */ - diff --git a/intern/cycles/util/util_avxb.h b/intern/cycles/util/util_avxb.h new file mode 100644 index 000000000000..60d9bb442566 --- /dev/null +++ b/intern/cycles/util/util_avxb.h @@ -0,0 +1,191 @@ +/* + * Copyright 2011-2013 Intel Corporation + * Modifications Copyright 2014, Blender Foundation. + * + * Licensed under the Apache License, Version 2.0(the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UTIL_AVXB_H__ +#define __UTIL_AVXB_H__ + +CCL_NAMESPACE_BEGIN + +struct avxf; + +/*! 4-wide SSE bool type. */ +struct avxb +{ + typedef avxb Mask; // mask type + typedef avxf Float; // float type + + enum { size = 8 }; // number of SIMD elements + union { __m256 m256; int32_t v[8]; }; // data + + //////////////////////////////////////////////////////////////////////////////// + /// Constructors, Assignment & Cast Operators + //////////////////////////////////////////////////////////////////////////////// + + __forceinline avxb ( ) {} + __forceinline avxb ( const avxb& other ) { m256 = other.m256; } + __forceinline avxb& operator=( const avxb& other ) { m256 = other.m256; return *this; } + + __forceinline avxb( const __m256 input ) : m256(input) {} + __forceinline operator const __m256&( void ) const { return m256; } + __forceinline operator const __m256i( void ) const { return _mm256_castps_si256(m256); } + __forceinline operator const __m256d( void ) const { return _mm256_castps_pd(m256); } + + //__forceinline avxb ( bool a ) + // : m256(_mm_lookupmask_ps[(size_t(a) << 3) | (size_t(a) << 2) | (size_t(a) << 1) | size_t(a)]) {} + //__forceinline avxb ( bool a, bool b) + // : m256(_mm_lookupmask_ps[(size_t(b) << 3) | (size_t(a) << 2) | (size_t(b) << 1) | size_t(a)]) {} + //__forceinline avxb ( bool a, bool b, bool c, bool d) + // : m256(_mm_lookupmask_ps[(size_t(d) << 3) | (size_t(c) << 2) | (size_t(b) << 1) | size_t(a)]) {} + //__forceinline avxb(int mask) { + // assert(mask >= 0 && mask < 16); + // m128 = _mm_lookupmask_ps[mask]; + //} + + //////////////////////////////////////////////////////////////////////////////// + /// Constants + //////////////////////////////////////////////////////////////////////////////// + + __forceinline avxb( FalseTy ) : m256(_mm256_setzero_ps()) {} + __forceinline avxb( TrueTy ) : m256(_mm256_castsi256_ps(_mm256_cmpeq_epi32(_mm256_setzero_si256(), _mm256_setzero_si256()))) {} + + //////////////////////////////////////////////////////////////////////////////// + /// Array Access + //////////////////////////////////////////////////////////////////////////////// + + __forceinline bool operator []( const size_t i ) const { assert(i < 8); return (_mm256_movemask_ps(m256) >> i) & 1; } + __forceinline int32_t& operator []( const size_t i ) { assert(i < 8); return v[i]; } +}; + +//////////////////////////////////////////////////////////////////////////////// +/// Unary Operators +//////////////////////////////////////////////////////////////////////////////// + +__forceinline const avxb operator !( const avxb& a ) { return _mm256_xor_ps(a, avxb(True)); } + +//////////////////////////////////////////////////////////////////////////////// +/// Binary Operators +//////////////////////////////////////////////////////////////////////////////// + +__forceinline const avxb operator &( const avxb& a, const avxb& b ) { return _mm256_and_ps(a, b); } +__forceinline const avxb operator |( const avxb& a, const avxb& b ) { return _mm256_or_ps (a, b); } +__forceinline const avxb operator ^( const avxb& a, const avxb& b ) { return _mm256_xor_ps(a, b); } + +//////////////////////////////////////////////////////////////////////////////// +/// Assignment Operators +//////////////////////////////////////////////////////////////////////////////// + +__forceinline const avxb operator &=( avxb& a, const avxb& b ) { return a = a & b; } +__forceinline const avxb operator |=( avxb& a, const avxb& b ) { return a = a | b; } +__forceinline const avxb operator ^=( avxb& a, const avxb& b ) { return a = a ^ b; } + +//////////////////////////////////////////////////////////////////////////////// +/// Comparison Operators + Select +//////////////////////////////////////////////////////////////////////////////// + +__forceinline const avxb operator !=( const avxb& a, const avxb& b ) { return _mm256_xor_ps(a, b); } +__forceinline const avxb operator ==( const avxb& a, const avxb& b ) { return _mm256_castsi256_ps(_mm256_cmpeq_epi32(a, b)); } + +__forceinline const avxb select( const avxb& m, const avxb& t, const avxb& f ) { +#if defined(__KERNEL_SSE41__) + return _mm256_blendv_ps(f, t, m); +#else + return _mm256_or_ps(_mm256_and_ps(m, t), _mm256_andnot_ps(m, f)); +#endif +} + +//////////////////////////////////////////////////////////////////////////////// +/// Movement/Shifting/Shuffling Functions +//////////////////////////////////////////////////////////////////////////////// + +__forceinline const avxb unpacklo( const avxb& a, const avxb& b ) { return _mm256_unpacklo_ps(a, b); } +__forceinline const avxb unpackhi( const avxb& a, const avxb& b ) { return _mm256_unpackhi_ps(a, b); } + +#define _MM256_SHUFFLE(fp7,fp6,fp5,fp4,fp3,fp2,fp1,fp0) (((fp7) << 14) | ((fp6) << 12) | ((fp5) << 10) | ((fp4) << 8) | \ + ((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) + +template +__forceinline const avxb shuffle( const avxb& a ) { + return _mm256_cvtepi32_ps(_mm256_shuffle_epi32(a, _MM256_SHUFFLE(i7, i6, i5, i4, i3, i2, i1, i0))); +} + +/* +template<> __forceinline const avxb shuffle<0, 1, 0, 1, 0, 1, 0, 1>( const avxb& a ) { + return _mm_movelh_ps(a, a); +} + +template<> __forceinline const sseb shuffle<2, 3, 2, 3>( const sseb& a ) { + return _mm_movehl_ps(a, a); +} + +template __forceinline const sseb shuffle( const sseb& a, const sseb& b ) { + return _mm_shuffle_ps(a, b, _MM_SHUFFLE(i3, i2, i1, i0)); +} + +template<> __forceinline const sseb shuffle<0, 1, 0, 1>( const sseb& a, const sseb& b ) { + return _mm_movelh_ps(a, b); +} + +template<> __forceinline const sseb shuffle<2, 3, 2, 3>( const sseb& a, const sseb& b ) { + return _mm_movehl_ps(b, a); +} + +#if defined(__KERNEL_SSE3__) +template<> __forceinline const sseb shuffle<0, 0, 2, 2>( const sseb& a ) { return _mm_moveldup_ps(a); } +template<> __forceinline const sseb shuffle<1, 1, 3, 3>( const sseb& a ) { return _mm_movehdup_ps(a); } +#endif + +#if defined(__KERNEL_SSE41__) +template __forceinline const sseb insert( const sseb& a, const sseb& b ) { return _mm_insert_ps(a, b, (dst << 4) | (src << 6) | clr); } +template __forceinline const sseb insert( const sseb& a, const sseb& b ) { return insert(a, b); } +template __forceinline const sseb insert( const sseb& a, const bool b ) { return insert(a, sseb(b)); } +#endif +*/ + +//////////////////////////////////////////////////////////////////////////////// +/// Reduction Operations +//////////////////////////////////////////////////////////////////////////////// + +#if defined(__KERNEL_SSE41__) +__forceinline size_t popcnt( const avxb& a ) { return __popcnt(_mm256_movemask_ps(a)); } +#else +__forceinline size_t popcnt( const avxb& a ) { return bool(a[0])+bool(a[1])+bool(a[2])+bool(a[3])+bool(a[4])+ + bool(a[5])+bool(a[6])+bool(a[7]); } +#endif + +__forceinline bool reduce_and( const avxb& a ) { return _mm256_movemask_ps(a) == 0xf; } +__forceinline bool reduce_or ( const avxb& a ) { return _mm256_movemask_ps(a) != 0x0; } +__forceinline bool all ( const avxb& b ) { return _mm256_movemask_ps(b) == 0xf; } +__forceinline bool any ( const avxb& b ) { return _mm256_movemask_ps(b) != 0x0; } +__forceinline bool none ( const avxb& b ) { return _mm256_movemask_ps(b) == 0x0; } + +__forceinline size_t movemask( const avxb& a ) { return _mm256_movemask_ps(a); } + +//////////////////////////////////////////////////////////////////////////////// +/// Debug Functions +//////////////////////////////////////////////////////////////////////////////// + +ccl_device_inline void print_avxb(const char *label, const avxb &a) +{ + printf("%s: %df %df %df %df %df %df %df %d\n", + label, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]); +} + +#endif + +CCL_NAMESPACE_END + +//#endif diff --git a/intern/cycles/util/util_avxf.h b/intern/cycles/util/util_avxf.h index 2451213963ae..5596702ca203 100644 --- a/intern/cycles/util/util_avxf.h +++ b/intern/cycles/util/util_avxf.h @@ -19,7 +19,8 @@ CCL_NAMESPACE_BEGIN -#ifdef __KERNEL_AVX__ +struct avxb; + struct avxf { typedef avxf Float; @@ -53,6 +54,9 @@ struct avxf __forceinline avxf(float a7, float a6, float a5, float a4, float a3, float a2, float a1, float a0) : m256(_mm256_set_ps(a7, a6, a5, a4, a3, a2, a1, a0)) {} + __forceinline avxf(float3 a) : + m256(_mm256_set_ps(a.w, a.z, a.y, a.x, a.w, a.z, a.y, a.x)) {} + __forceinline avxf(int a3, int a2, int a1, int a0) { @@ -73,8 +77,24 @@ struct avxf m256 = _mm256_insertf128_ps(foo, b, 1); } + __forceinline const float& operator [](const size_t i) const { assert(i < 8); return f[i]; } + __forceinline float& operator [](const size_t i) { assert(i < 8); return f[i]; } }; +__forceinline avxf cross(const avxf& a, const avxf& b) +{ + avxf r(0.0, a[4]*b[5] - a[5]*b[4], a[6]*b[4] - a[4]*b[6], a[5]*b[6] - a[6]*b[5], + 0.0, a[0]*b[1] - a[1]*b[0], a[2]*b[0] - a[0]*b[2], a[1]*b[2] - a[2]*b[1]); + return r; +} + +__forceinline void dot3(const avxf& a, const avxf& b, float &den, float &den2) +{ + const avxf t = _mm256_mul_ps(a.m256, b.m256); + den = ((float*)&t)[0] + ((float*)&t)[1] + ((float*)&t)[2]; + den2 = ((float*)&t)[4] + ((float*)&t)[5] + ((float*)&t)[6]; +} + //////////////////////////////////////////////////////////////////////////////// /// Unary Operators //////////////////////////////////////////////////////////////////////////////// @@ -107,6 +127,9 @@ __forceinline const avxf operator^(const avxf& a, const avxf& b) { return _mm256 __forceinline const avxf operator&(const avxf& a, const avxf& b) { return _mm256_and_ps(a.m256,b.m256); } +__forceinline const avxf max(const avxf& a, const avxf& b) { return _mm256_max_ps(a.m256, b.m256); } +__forceinline const avxf min(const avxf& a, const avxf& b) { return _mm256_min_ps(a.m256, b.m256); } + //////////////////////////////////////////////////////////////////////////////// /// Movement/Shifting/Shuffling Functions //////////////////////////////////////////////////////////////////////////////// @@ -160,6 +183,18 @@ ccl_device_inline const avxf blend(const avxf &a, const avxf &b) return blend(a,b); } +//#if defined(__KERNEL_SSE41__) +__forceinline avxf maxi(const avxf& a, const avxf& b) { + const avxf ci = _mm256_max_ps(a, b); + return ci; +} + +__forceinline avxf mini(const avxf& a, const avxf& b) { + const avxf ci = _mm256_min_ps(a, b); + return ci; +} +//#endif + //////////////////////////////////////////////////////////////////////////////// /// Ternary Operators //////////////////////////////////////////////////////////////////////////////// @@ -178,6 +213,19 @@ __forceinline const avxf nmadd(const avxf& a, const avxf& b, const avxf& c) { return c-(a*b); #endif } +__forceinline const avxf msub(const avxf& a, const avxf& b, const avxf& c) { + return _mm256_fmsub_ps(a, b, c); +} + +//////////////////////////////////////////////////////////////////////////////// +/// Comparison Operators +//////////////////////////////////////////////////////////////////////////////// +#ifdef __KERNEL_AVX2__ +__forceinline const avxb operator <=(const avxf& a, const avxf& b) { + return _mm256_cmp_ps(a.m256, b.m256, _CMP_LE_OS); +} +#endif + #endif #ifndef _mm256_set_m128 @@ -189,5 +237,3 @@ __forceinline const avxf nmadd(const avxf& a, const avxf& b, const avxf& c) { _mm256_set_m128(_mm_loadu_ps(hiaddr), _mm_loadu_ps(loaddr)) CCL_NAMESPACE_END - -#endif diff --git a/intern/cycles/util/util_boundbox.h b/intern/cycles/util/util_boundbox.h index ed94ca20211d..b1bd5be0df34 100644 --- a/intern/cycles/util/util_boundbox.h +++ b/intern/cycles/util/util_boundbox.h @@ -55,7 +55,7 @@ class BoundBox { } - __forceinline void grow(const float3& pt) + __forceinline void grow(const float3& pt) { /* the order of arguments to min is such that if pt is nan, it will not * influence the resulting bounding box */ @@ -63,7 +63,7 @@ class BoundBox max = ccl::max(pt, max); } - __forceinline void grow(const float3& pt, float border) + __forceinline void grow(const float3& pt, float border) { float3 shift = make_float3(border, border, border); min = ccl::min(pt - shift, min); @@ -76,7 +76,7 @@ class BoundBox grow(bbox.max); } - __forceinline void grow_safe(const float3& pt) + __forceinline void grow_safe(const float3& pt) { /* the order of arguments to min is such that if pt is nan, it will not * influence the resulting bounding box */ @@ -86,7 +86,7 @@ class BoundBox } } - __forceinline void grow_safe(const float3& pt, float border) + __forceinline void grow_safe(const float3& pt, float border) { if(isfinite(pt.x) && isfinite(pt.y) && isfinite(pt.z) && isfinite(border)) { float3 shift = make_float3(border, border, border); @@ -101,7 +101,7 @@ class BoundBox grow_safe(bbox.max); } - __forceinline void intersect(const BoundBox& bbox) + __forceinline void intersect(const BoundBox& bbox) { min = ccl::max(min, bbox.min); max = ccl::min(max, bbox.max); @@ -283,4 +283,3 @@ class BoundBox2D { CCL_NAMESPACE_END #endif /* __UTIL_BOUNDBOX_H__ */ - diff --git a/intern/cycles/util/util_color.h b/intern/cycles/util/util_color.h index 62a9bf8e47dc..826db469d251 100644 --- a/intern/cycles/util/util_color.h +++ b/intern/cycles/util/util_color.h @@ -241,4 +241,3 @@ ccl_device float4 color_srgb_to_linear_v4(float4 c) CCL_NAMESPACE_END #endif /* __UTIL_COLOR_H__ */ - diff --git a/intern/cycles/util/util_debug.cpp b/intern/cycles/util/util_debug.cpp index 9a66a3728220..68e6f2610573 100644 --- a/intern/cycles/util/util_debug.cpp +++ b/intern/cycles/util/util_debug.cpp @@ -57,7 +57,19 @@ void DebugFlags::CPU::reset() #undef STRINGIFY #undef CHECK_CPU_FLAGS - bvh_layout = BVH_LAYOUT_DEFAULT; + if(getenv("CYCLES_BVH2") != NULL) { + bvh_layout = BVH_LAYOUT_BVH2; + } + else if(getenv("CYCLES_BVH4") != NULL) { + bvh_layout = BVH_LAYOUT_BVH4; + } + else if(getenv("CYCLES_BVH8") != NULL) { + bvh_layout = BVH_LAYOUT_BVH8; + } + else { + bvh_layout = BVH_LAYOUT_DEFAULT; + } + split_kernel = false; } diff --git a/intern/cycles/util/util_defines.h b/intern/cycles/util/util_defines.h index 98944a19022b..8bce4aca6999 100644 --- a/intern/cycles/util/util_defines.h +++ b/intern/cycles/util/util_defines.h @@ -87,12 +87,8 @@ # define UNLIKELY(x) (x) #endif -#if defined(__cplusplus) && ((__cplusplus >= 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1800)) -# define HAS_CPP11_FEATURES -#endif - #if defined(__GNUC__) || defined(__clang__) -# if defined(HAS_CPP11_FEATURES) +# if defined(__cplusplus) /* Some magic to be sure we don't have reference in the type. */ template static inline T decltype_helper(T x) { return x; } # define TYPEOF(x) decltype(decltype_helper(x)) @@ -133,4 +129,3 @@ template static inline T decltype_helper(T x) { return x; } #endif #endif /* __UTIL_DEFINES_H__ */ - diff --git a/intern/cycles/util/util_foreach.h b/intern/cycles/util/util_foreach.h index 4f7337107b32..2a74ff0a55d7 100644 --- a/intern/cycles/util/util_foreach.h +++ b/intern/cycles/util/util_foreach.h @@ -17,14 +17,8 @@ #ifndef __UTIL_FOREACH_H__ #define __UTIL_FOREACH_H__ -/* Use Boost to get nice foreach() loops for STL data structures. */ +/* Nice foreach() loops for STL data structures. */ -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# define foreach(x, y) for(x : y) -#else -# include -# define foreach BOOST_FOREACH -#endif +#define foreach(x, y) for(x : y) #endif /* __UTIL_FOREACH_H__ */ - diff --git a/intern/cycles/util/util_function.h b/intern/cycles/util/util_function.h index 6d0f0b444a91..f3cc00329ade 100644 --- a/intern/cycles/util/util_function.h +++ b/intern/cycles/util/util_function.h @@ -17,18 +17,12 @@ #ifndef __UTIL_FUNCTION_H__ #define __UTIL_FUNCTION_H__ -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# include -#else -# include -# include -#endif +#include CCL_NAMESPACE_BEGIN -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# define function_bind std::bind -# define function_null nullptr +#define function_bind std::bind +#define function_null nullptr using std::function; using std::placeholders::_1; using std::placeholders::_2; @@ -39,12 +33,7 @@ using std::placeholders::_6; using std::placeholders::_7; using std::placeholders::_8; using std::placeholders::_9; -#else -using boost::function; -# define function_bind boost::bind -# define function_null NULL -#endif + CCL_NAMESPACE_END #endif /* __UTIL_FUNCTION_H__ */ - diff --git a/intern/cycles/util/util_half.h b/intern/cycles/util/util_half.h index 612228dd1c1a..53b7f2472bda 100644 --- a/intern/cycles/util/util_half.h +++ b/intern/cycles/util/util_half.h @@ -36,7 +36,16 @@ CCL_NAMESPACE_BEGIN /* CUDA has its own half data type, no need to define then */ #ifndef __KERNEL_CUDA__ -typedef unsigned short half; +/* Implementing this as a class rather than a typedef so that the compiler can tell it apart from unsigned shorts. */ +class half { +public: + half() : v(0) {} + half(const unsigned short& i) : v(i) {} + operator unsigned short() { return v; } + half& operator =(const unsigned short& i) { v = i; return *this; } +private: + unsigned short v; +}; #endif struct half4 { half x, y, z, w; }; @@ -140,4 +149,3 @@ ccl_device_inline half float_to_half(float f) CCL_NAMESPACE_END #endif /* __UTIL_HALF_H__ */ - diff --git a/intern/cycles/util/util_hash.h b/intern/cycles/util/util_hash.h index 2307ca158f0e..a8a5076fbb35 100644 --- a/intern/cycles/util/util_hash.h +++ b/intern/cycles/util/util_hash.h @@ -69,4 +69,3 @@ ccl_device_inline float hash_int_01(uint k) CCL_NAMESPACE_END #endif /* __UTIL_HASH_H__ */ - diff --git a/intern/cycles/util/util_image.h b/intern/cycles/util/util_image.h index 18876841b5bb..85bdb0d80505 100644 --- a/intern/cycles/util/util_image.h +++ b/intern/cycles/util/util_image.h @@ -38,6 +38,68 @@ void util_image_resize_pixels(const vector& input_pixels, size_t *output_height, size_t *output_depth); +/* Cast input pixel from unknown storage to float. */ +template +inline float util_image_cast_to_float(T value); + +template<> +inline float util_image_cast_to_float(float value) +{ + return value; +} +template<> +inline float util_image_cast_to_float(uchar value) +{ + return (float)value / 255.0f; +} +template<> +inline float util_image_cast_to_float(uint16_t value) +{ + return (float)value / 65535.0f; +} +template<> +inline float util_image_cast_to_float(half value) +{ + return half_to_float(value); +} + +/* Cast float value to output pixel type. */ +template +inline T util_image_cast_from_float(float value); + +template<> +inline float util_image_cast_from_float(float value) +{ + return value; +} +template<> +inline uchar util_image_cast_from_float(float value) +{ + if(value < 0.0f) { + return 0; + } + else if(value > (1.0f - 0.5f / 255.0f)) { + return 255; + } + return (uchar)((255.0f * value) + 0.5f); +} +template<> +inline uint16_t util_image_cast_from_float(float value) +{ + if(value < 0.0f) { + return 0; + } + else if(value > (1.0f - 0.5f / 65535.0f)) { + return 65535; + } + return (uint16_t)((65535.0f * value) + 0.5f); +} +template<> +inline half util_image_cast_from_float(float value) +{ + return float_to_half(value); +} + CCL_NAMESPACE_END #endif /* __UTIL_IMAGE_H__ */ diff --git a/intern/cycles/util/util_image_impl.h b/intern/cycles/util/util_image_impl.h index 751f52aaa867..5bc1c7275955 100644 --- a/intern/cycles/util/util_image_impl.h +++ b/intern/cycles/util/util_image_impl.h @@ -38,52 +38,6 @@ const T *util_image_read(const vector& pixels, return &pixels[index]; } -/* Cast input pixel from unknown storage to float. */ -template -inline float cast_to_float(T value); - -template<> -inline float cast_to_float(float value) -{ - return value; -} -template<> -inline float cast_to_float(uchar value) -{ - return (float)value / 255.0f; -} -template<> -inline float cast_to_float(half value) -{ - return half_to_float(value); -} - -/* Cast float value to output pixel type. */ -template -inline T cast_from_float(float value); - -template<> -inline float cast_from_float(float value) -{ - return value; -} -template<> -inline uchar cast_from_float(float value) -{ - if(value < 0.0f) { - return 0; - } - else if(value > (1.0f - 0.5f / 255.0f)) { - return 255; - } - return (uchar)((255.0f * value) + 0.5f); -} -template<> -inline half cast_from_float(float value) -{ - return float_to_half(value); -} - template void util_image_downscale_sample(const vector& pixels, const size_t width, @@ -117,7 +71,7 @@ void util_image_downscale_sample(const vector& pixels, components, nx, ny, nz); for(size_t k = 0; k < components; ++k) { - accum[k] += cast_to_float(pixel[k]); + accum[k] += util_image_cast_to_float(pixel[k]); } ++count; } @@ -126,7 +80,7 @@ void util_image_downscale_sample(const vector& pixels, if(count != 0) { const float inv_count = 1.0f / (float)count; for(size_t k = 0; k < components; ++k) { - result[k] = cast_from_float(accum[k] * inv_count); + result[k] = util_image_cast_from_float(accum[k] * inv_count); } } else { diff --git a/intern/cycles/util/util_list.h b/intern/cycles/util/util_list.h index 6cb27e6defe7..f555b001186b 100644 --- a/intern/cycles/util/util_list.h +++ b/intern/cycles/util/util_list.h @@ -26,4 +26,3 @@ using std::list; CCL_NAMESPACE_END #endif /* __UTIL_LIST_H__ */ - diff --git a/intern/cycles/util/util_map.h b/intern/cycles/util/util_map.h index 46c2885f8b06..3c9288417cf2 100644 --- a/intern/cycles/util/util_map.h +++ b/intern/cycles/util/util_map.h @@ -18,40 +18,14 @@ #define __UTIL_MAP_H__ #include - -#if defined(CYCLES_TR1_UNORDERED_MAP) -# include -#endif - -#if defined(CYCLES_STD_UNORDERED_MAP) || defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) -# include -#endif - -#if !defined(CYCLES_NO_UNORDERED_MAP) && !defined(CYCLES_TR1_UNORDERED_MAP) && \ - !defined(CYCLES_STD_UNORDERED_MAP) && !defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) // NOLINT -# error One of: CYCLES_NO_UNORDERED_MAP, CYCLES_TR1_UNORDERED_MAP,\ - CYCLES_STD_UNORDERED_MAP, CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE must be defined! // NOLINT -#endif - +#include CCL_NAMESPACE_BEGIN using std::map; using std::pair; - -#if defined(CYCLES_NO_UNORDERED_MAP) -typedef std::map unordered_map; -#endif - -#if defined(CYCLES_TR1_UNORDERED_MAP) || defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) -using std::tr1::unordered_map; -#endif - -#if defined(CYCLES_STD_UNORDERED_MAP) using std::unordered_map; -#endif CCL_NAMESPACE_END #endif /* __UTIL_MAP_H__ */ - diff --git a/intern/cycles/util/util_math.h b/intern/cycles/util/util_math.h index fd3199f209f5..52aeb8d85995 100644 --- a/intern/cycles/util/util_math.h +++ b/intern/cycles/util/util_math.h @@ -55,6 +55,15 @@ CCL_NAMESPACE_BEGIN #ifndef M_2_PI_F # define M_2_PI_F (0.6366197723675813f) /* 2/pi */ #endif +#ifndef M_1_2PI_F +# define M_1_2PI_F (0.1591549430918953f) /* 1/(2*pi) */ +#endif +#ifndef M_SQRT_PI_8_F +# define M_SQRT_PI_8_F (0.6266570686577501f) /* sqrt(pi/8) */ +#endif +#ifndef M_LN_2PI_F +# define M_LN_2PI_F (1.8378770664093454f) /* ln(2*pi) */ +#endif /* Multiplication */ #ifndef M_2PI_F @@ -266,6 +275,11 @@ ccl_device_inline int floor_to_int(float f) return float_to_int(floorf(f)); } +ccl_device_inline int quick_floor_to_int(float x) +{ + return float_to_int(x) - ((x < 0) ? 1 : 0); +} + ccl_device_inline int ceil_to_int(float f) { return float_to_int(ceilf(f)); @@ -536,6 +550,16 @@ ccl_device_inline float sqr(float a) return a * a; } +ccl_device_inline float pow20(float a) +{ + return sqr(sqr(sqr(sqr(a))*a)); +} + +ccl_device_inline float pow22(float a) +{ + return sqr(a*sqr(sqr(sqr(a))*a)); +} + ccl_device_inline float beta(float x, float y) { #ifndef __KERNEL_OPENCL__ @@ -550,6 +574,11 @@ ccl_device_inline float xor_signmask(float x, int y) return __int_as_float(__float_as_int(x) ^ y); } +ccl_device float bits_to_01(uint bits) +{ + return bits * (1.0f/(float)0xFFFFFFFF); +} + /* projections */ ccl_device_inline float2 map_to_tube(const float3 co) { diff --git a/intern/cycles/util/util_math_float3.h b/intern/cycles/util/util_math_float3.h index f5149fe13ede..75265c1c9a22 100644 --- a/intern/cycles/util/util_math_float3.h +++ b/intern/cycles/util/util_math_float3.h @@ -377,6 +377,33 @@ ccl_device_inline bool isequal_float3(const float3 a, const float3 b) #endif } +ccl_device_inline float3 pow3(float3 v, float e) +{ + return make_float3(powf(v.x, e), powf(v.y, e), powf(v.z, e)); +} + +ccl_device_inline float3 exp3(float3 v) +{ + return make_float3(expf(v.x), expf(v.y), expf(v.z)); +} + +ccl_device_inline float3 log3(float3 v) +{ + return make_float3(logf(v.x), logf(v.y), logf(v.z)); +} + +ccl_device_inline int3 quick_floor_to_int3(const float3 a) +{ +#ifdef __KERNEL_SSE__ + int3 b = int3(_mm_cvttps_epi32(a.m128)); + int3 isneg = int3(_mm_castps_si128(_mm_cmplt_ps(a.m128, _mm_set_ps1(0.0f)))); + /* Unsaturated add 0xffffffff is the same as subtract -1. */ + return b + isneg; +#else + return make_int3(quick_floor_to_int(a.x), quick_floor_to_int(a.y), quick_floor_to_int(a.z)); +#endif +} + ccl_device_inline bool isfinite3_safe(float3 v) { return isfinite_safe(v.x) && isfinite_safe(v.y) && isfinite_safe(v.z); diff --git a/intern/cycles/util/util_math_int3.h b/intern/cycles/util/util_math_int3.h index 6eef8517665e..81b10f31f4a8 100644 --- a/intern/cycles/util/util_math_int3.h +++ b/intern/cycles/util/util_math_int3.h @@ -91,6 +91,24 @@ ccl_device_inline bool operator<(const int3 &a, const int3 &b) { return a.x < b.x && a.y < b.y && a.z < b.z; } + +ccl_device_inline int3 operator+(const int3 &a, const int3 &b) +{ +#ifdef __KERNEL_SSE__ + return int3(_mm_add_epi32(a.m128, b.m128)); +#else + return make_int3(a.x + b.x, a.y + b.y, a.z + b.z); +#endif +} + +ccl_device_inline int3 operator-(const int3 &a, const int3 &b) +{ +#ifdef __KERNEL_SSE__ + return int3(_mm_sub_epi32(a.m128, b.m128)); +#else + return make_int3(a.x - b.x, a.y - b.y, a.z - b.z); +#endif +} #endif /* !__KERNEL_OPENCL__ */ CCL_NAMESPACE_END diff --git a/intern/cycles/util/util_math_intersect.h b/intern/cycles/util/util_math_intersect.h index 61ddcc38f506..b5fbb24091fc 100644 --- a/intern/cycles/util/util_math_intersect.h +++ b/intern/cycles/util/util_math_intersect.h @@ -136,10 +136,10 @@ ccl_device_forceinline bool ray_triangle_intersect( #if defined(__KERNEL_SSE2__) && defined (__KERNEL_SSE__) int uvw_sign = movemask(UVWW) & 0x7; - if (uvw_sign != 0) - { - if (uvw_sign != 0x7) + if(uvw_sign != 0) { + if(uvw_sign != 0x7) { return false; + } } #else const float minUVW = min(U, min(V, W)); diff --git a/intern/cycles/util/util_md5.cpp b/intern/cycles/util/util_md5.cpp index 749760d84f05..7cdd28a4793e 100644 --- a/intern/cycles/util/util_md5.cpp +++ b/intern/cycles/util/util_md5.cpp @@ -338,7 +338,7 @@ bool MD5Hash::append_file(const string& filepath) bool success = (ferror(f) == 0); fclose(f); - + return success; } @@ -376,7 +376,7 @@ string MD5Hash::get_hex() for(int i = 0; i < 16; i++) sprintf(buf + i*2, "%02X", (unsigned int)digest[i]); buf[sizeof(buf)-1] = '\0'; - + return string(buf); } @@ -388,4 +388,3 @@ string util_md5_string(const string& str) } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_md5.h b/intern/cycles/util/util_md5.h index b043b591e674..9023ccee4c2c 100644 --- a/intern/cycles/util/util_md5.h +++ b/intern/cycles/util/util_md5.h @@ -59,4 +59,3 @@ string util_md5_string(const string& str); CCL_NAMESPACE_END #endif /* __UTIL_MD5_H__ */ - diff --git a/intern/cycles/util/util_optimization.h b/intern/cycles/util/util_optimization.h index 3c5785c4807b..3b3627242d5f 100644 --- a/intern/cycles/util/util_optimization.h +++ b/intern/cycles/util/util_optimization.h @@ -69,4 +69,3 @@ #endif #endif /* __UTIL_OPTIMIZATION_H__ */ - diff --git a/intern/cycles/util/util_param.h b/intern/cycles/util/util_param.h index 69bcbf80a781..246b5cb7d637 100644 --- a/intern/cycles/util/util_param.h +++ b/intern/cycles/util/util_param.h @@ -31,4 +31,3 @@ OIIO_NAMESPACE_USING CCL_NAMESPACE_END #endif /* __UTIL_PARAM_H__ */ - diff --git a/intern/cycles/util/util_path.cpp b/intern/cycles/util/util_path.cpp index 0e0371928ab8..51b7944705e2 100644 --- a/intern/cycles/util/util_path.cpp +++ b/intern/cycles/util/util_path.cpp @@ -987,4 +987,3 @@ void path_cache_clear_except(const string& name, const set& except) } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_path.h b/intern/cycles/util/util_path.h index 0e5e2d2c837d..738dba946475 100644 --- a/intern/cycles/util/util_path.h +++ b/intern/cycles/util/util_path.h @@ -76,4 +76,3 @@ void path_cache_clear_except(const string& name, const set& except); CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_progress.h b/intern/cycles/util/util_progress.h index 134383e88db3..3ef15c5c09a6 100644 --- a/intern/cycles/util/util_progress.h +++ b/intern/cycles/util/util_progress.h @@ -366,4 +366,3 @@ class Progress { CCL_NAMESPACE_END #endif /* __UTIL_PROGRESS_H__ */ - diff --git a/intern/cycles/util/util_projection.h b/intern/cycles/util/util_projection.h index dbcb9877a48d..26b4843928cc 100644 --- a/intern/cycles/util/util_projection.h +++ b/intern/cycles/util/util_projection.h @@ -174,4 +174,3 @@ ccl_device_inline ProjectionTransform projection_orthographic(float znear, float CCL_NAMESPACE_END #endif /* __UTIL_PROJECTION_H__ */ - diff --git a/intern/cycles/util/util_queue.h b/intern/cycles/util/util_queue.h index f4c802785f9e..622f4fe3e470 100644 --- a/intern/cycles/util/util_queue.h +++ b/intern/cycles/util/util_queue.h @@ -26,4 +26,3 @@ using std::queue; CCL_NAMESPACE_END #endif /* __UTIL_LIST_H__ */ - diff --git a/intern/cycles/util/util_rect.h b/intern/cycles/util/util_rect.h index 17a55a14d0ba..d13baefe85e3 100644 --- a/intern/cycles/util/util_rect.h +++ b/intern/cycles/util/util_rect.h @@ -70,4 +70,3 @@ ccl_device_inline int rect_size(int4 rect) CCL_NAMESPACE_END #endif /* __UTIL_RECT_H__ */ - diff --git a/intern/cycles/util/util_set.h b/intern/cycles/util/util_set.h index c19fa071b374..298e1f7729a6 100644 --- a/intern/cycles/util/util_set.h +++ b/intern/cycles/util/util_set.h @@ -18,24 +18,7 @@ #define __UTIL_SET_H__ #include -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# include -#else -# if defined(CYCLES_TR1_UNORDERED_MAP) -# include -# endif -# if defined(CYCLES_STD_UNORDERED_MAP) || \ - defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) -# include -# endif -# if !defined(CYCLES_NO_UNORDERED_MAP) && \ - !defined(CYCLES_TR1_UNORDERED_MAP) && \ - !defined(CYCLES_STD_UNORDERED_MAP) && \ - !defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) -# error One of: CYCLES_NO_UNORDERED_MAP, CYCLES_TR1_UNORDERED_MAP,\ - CYCLES_STD_UNORDERED_MAP, CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE must be defined! // NOLINT -# endif -#endif +#include #if defined(_MSC_VER) && (_MSC_VER >= 1900) # include @@ -44,20 +27,8 @@ CCL_NAMESPACE_BEGIN using std::set; -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -using std::unordered_set; -#else -# if defined(CYCLES_NO_UNORDERED_MAP) -typedef std::set unordered_set; -# endif -# if defined(CYCLES_TR1_UNORDERED_MAP) || defined(CYCLES_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) -using std::tr1::unordered_set; -# endif -# if defined(CYCLES_STD_UNORDERED_MAP) using std::unordered_set; -# endif -#endif + CCL_NAMESPACE_END #endif /* __UTIL_SET_H__ */ - diff --git a/intern/cycles/util/util_simd.h b/intern/cycles/util/util_simd.h index 04341451afbc..cc7f436c8fe0 100644 --- a/intern/cycles/util/util_simd.h +++ b/intern/cycles/util/util_simd.h @@ -111,7 +111,7 @@ __forceinline size_t __popcnt(size_t in) { #endif __forceinline int __bsf(int v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u32(v); #else unsigned long r = 0; _BitScanForward(&r,v); return r; @@ -119,7 +119,7 @@ __forceinline int __bsf(int v) { } __forceinline unsigned int __bsf(unsigned int v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u32(v); #else unsigned long r = 0; _BitScanForward(&r,v); return r; @@ -143,7 +143,7 @@ __forceinline int __btr(int v, int i) { } __forceinline int bitscan(int v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u32(v); #else return __bsf(v); @@ -156,18 +156,18 @@ __forceinline int clz(const int x) return _lzcnt_u32(x); #else if(UNLIKELY(x == 0)) return 32; - return 31 - __bsr(x); + return 31 - __bsr(x); #endif } -__forceinline int __bscf(int& v) +__forceinline int __bscf(int& v) { int i = __bsf(v); v &= v-1; return i; } -__forceinline unsigned int __bscf(unsigned int& v) +__forceinline unsigned int __bscf(unsigned int& v) { unsigned int i = __bsf(v); v &= v-1; @@ -177,7 +177,7 @@ __forceinline unsigned int __bscf(unsigned int& v) #if defined(__KERNEL_64_BIT__) __forceinline size_t __bsf(size_t v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u64(v); #else unsigned long r = 0; _BitScanForward64(&r,v); return r; @@ -212,7 +212,7 @@ __forceinline size_t bitscan(size_t v) { #endif } -__forceinline size_t __bscf(size_t& v) +__forceinline size_t __bscf(size_t& v) { size_t i = __bsf(v); v &= v-1; @@ -274,7 +274,7 @@ __forceinline size_t __btr(size_t v, size_t i) { } __forceinline int bitscan(int v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u32(v); #else return __bsf(v); @@ -282,7 +282,7 @@ __forceinline int bitscan(int v) { } __forceinline unsigned int bitscan(unsigned int v) { -#if defined(__KERNEL_AVX2__) +#if defined(__KERNEL_AVX2__) return _tzcnt_u32(v); #else return __bsf(v); @@ -309,11 +309,11 @@ __forceinline int clz(const int x) return _lzcnt_u32(x); #else if(UNLIKELY(x == 0)) return 32; - return 31 - __bsr(x); + return 31 - __bsr(x); #endif } -__forceinline int __bscf(int& v) +__forceinline int __bscf(int& v) { int i = bitscan(v); #if defined(__KERNEL_AVX2__) @@ -324,7 +324,7 @@ __forceinline int __bscf(int& v) return i; } -__forceinline unsigned int __bscf(unsigned int& v) +__forceinline unsigned int __bscf(unsigned int& v) { unsigned int i = bitscan(v); v &= v-1; @@ -332,7 +332,7 @@ __forceinline unsigned int __bscf(unsigned int& v) } #if (defined(__KERNEL_64_BIT__) || defined(__APPLE__)) && !(defined(__ILP32__) && defined(__x86_64__)) -__forceinline size_t __bscf(size_t& v) +__forceinline size_t __bscf(size_t& v) { size_t i = bitscan(v); #if defined(__KERNEL_AVX2__) @@ -375,28 +375,28 @@ __forceinline __m128 _mm_blendv_ps_emu( __m128 value, __m128 input, __m128 mask) #define _mm_blend_ps _mm_blend_ps_emu __forceinline __m128 _mm_blend_ps_emu( __m128 value, __m128 input, const int mask) { - assert(mask < 0x10); return _mm_blendv_ps(value, input, _mm_lookupmask_ps[mask]); + assert(mask < 0x10); return _mm_blendv_ps(value, input, _mm_lookupmask_ps[mask]); } #undef _mm_blendv_epi8 #define _mm_blendv_epi8 _mm_blendv_epi8_emu __forceinline __m128i _mm_blendv_epi8_emu( __m128i value, __m128i input, __m128i mask) { - return _mm_or_si128(_mm_and_si128(mask, input), _mm_andnot_si128(mask, value)); + return _mm_or_si128(_mm_and_si128(mask, input), _mm_andnot_si128(mask, value)); } #undef _mm_min_epi32 #define _mm_min_epi32 _mm_min_epi32_emu __forceinline __m128i _mm_min_epi32_emu( __m128i value, __m128i input) { - return _mm_blendv_epi8(input, value, _mm_cmplt_epi32(value, input)); + return _mm_blendv_epi8(input, value, _mm_cmplt_epi32(value, input)); } #undef _mm_max_epi32 #define _mm_max_epi32 _mm_max_epi32_emu __forceinline __m128i _mm_max_epi32_emu( __m128i value, __m128i input) { - return _mm_blendv_epi8(value, input, _mm_cmplt_epi32(value, input)); + return _mm_blendv_epi8(value, input, _mm_cmplt_epi32(value, input)); } #undef _mm_extract_epi32 @@ -416,7 +416,7 @@ __forceinline int _mm_extract_epi32_emu( __m128i input, const int index) #define _mm_insert_epi32 _mm_insert_epi32_emu __forceinline __m128i _mm_insert_epi32_emu( __m128i value, int input, const int index) { - assert(index >= 0 && index < 4); ((int*)&value)[index] = input; return value; + assert(index >= 0 && index < 4); ((int*)&value)[index] = input; return value; } #undef _mm_insert_ps @@ -487,4 +487,3 @@ CCL_NAMESPACE_END #endif /* __KERNEL_GPU__ */ #endif /* __UTIL_SIMD_TYPES_H__ */ - diff --git a/intern/cycles/util/util_sky_model.cpp b/intern/cycles/util/util_sky_model.cpp index 6dda84699077..526bce4ff880 100644 --- a/intern/cycles/util/util_sky_model.cpp +++ b/intern/cycles/util/util_sky_model.cpp @@ -367,4 +367,3 @@ ArHosekSkyModelState * arhosek_xyz_skymodelstate_alloc_init( } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_sseb.h b/intern/cycles/util/util_sseb.h index 977976c3fc03..115b133c6627 100644 --- a/intern/cycles/util/util_sseb.h +++ b/intern/cycles/util/util_sseb.h @@ -38,7 +38,7 @@ struct sseb //////////////////////////////////////////////////////////////////////////////// /// Constructors, Assignment & Cast Operators //////////////////////////////////////////////////////////////////////////////// - + __forceinline sseb ( ) {} __forceinline sseb ( const sseb& other ) { m128 = other.m128; } __forceinline sseb& operator=( const sseb& other ) { m128 = other.m128; return *this; } @@ -47,10 +47,10 @@ struct sseb __forceinline operator const __m128&( void ) const { return m128; } __forceinline operator const __m128i( void ) const { return _mm_castps_si128(m128); } __forceinline operator const __m128d( void ) const { return _mm_castps_pd(m128); } - + __forceinline sseb ( bool a ) : m128(_mm_lookupmask_ps[(size_t(a) << 3) | (size_t(a) << 2) | (size_t(a) << 1) | size_t(a)]) {} - __forceinline sseb ( bool a, bool b) + __forceinline sseb ( bool a, bool b) : m128(_mm_lookupmask_ps[(size_t(b) << 3) | (size_t(a) << 2) | (size_t(b) << 1) | size_t(a)]) {} __forceinline sseb ( bool a, bool b, bool c, bool d) : m128(_mm_lookupmask_ps[(size_t(d) << 3) | (size_t(c) << 2) | (size_t(b) << 1) | size_t(a)]) {} @@ -103,11 +103,11 @@ __forceinline const sseb operator ^=( sseb& a, const sseb& b ) { return a = a ^ __forceinline const sseb operator !=( const sseb& a, const sseb& b ) { return _mm_xor_ps(a, b); } __forceinline const sseb operator ==( const sseb& a, const sseb& b ) { return _mm_castsi128_ps(_mm_cmpeq_epi32(a, b)); } -__forceinline const sseb select( const sseb& m, const sseb& t, const sseb& f ) { +__forceinline const sseb select( const sseb& m, const sseb& t, const sseb& f ) { #if defined(__KERNEL_SSE41__) - return _mm_blendv_ps(f, t, m); + return _mm_blendv_ps(f, t, m); #else - return _mm_or_ps(_mm_and_ps(m, t), _mm_andnot_ps(m, f)); + return _mm_or_ps(_mm_and_ps(m, t), _mm_andnot_ps(m, f)); #endif } @@ -186,4 +186,3 @@ ccl_device_inline void print_sseb(const char *label, const sseb &a) CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_ssef.h b/intern/cycles/util/util_ssef.h index bb007ff84a92..b5623860e33b 100644 --- a/intern/cycles/util/util_ssef.h +++ b/intern/cycles/util/util_ssef.h @@ -31,14 +31,14 @@ struct ssef typedef sseb Mask; // mask type typedef ssei Int; // int type typedef ssef Float; // float type - + enum { size = 4 }; // number of SIMD elements union { __m128 m128; float f[4]; int i[4]; }; // data //////////////////////////////////////////////////////////////////////////////// /// Constructors, Assignment & Cast Operators //////////////////////////////////////////////////////////////////////////////// - + __forceinline ssef () {} __forceinline ssef (const ssef& other) { m128 = other.m128; } __forceinline ssef& operator=(const ssef& other) { m128 = other.m128; return *this; } @@ -143,7 +143,7 @@ __forceinline ssef mini(const ssef& a, const ssef& b) { return _mm_castsi128_ps(ci); } #endif - + #if defined(__KERNEL_SSE41__) __forceinline ssef maxi(const ssef& a, const ssef& b) { const ssei ai = _mm_castps_si128(a); @@ -229,7 +229,7 @@ __forceinline const ssef select(const ssef& m, const ssef& t, const ssef& f) { #endif } -__forceinline const ssef select(const int mask, const ssef& t, const ssef& f) { +__forceinline const ssef select(const int mask, const ssef& t, const ssef& f) { #if defined(__KERNEL_SSE41__) && ((!defined(__clang__) && !defined(_MSC_VER)) || defined(__INTEL_COMPILER)) return _mm_blend_ps(f, t, mask); #else @@ -298,8 +298,8 @@ template<> __forceinline const ssef shuffle<2, 3, 2, 3>(const ssef& a, const sse } #if defined(__KERNEL_SSSE3__) -__forceinline const ssef shuffle8(const ssef& a, const ssei& shuf) { - return _mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128(a), shuf)); +__forceinline const ssef shuffle8(const ssef& a, const ssei& shuf) { + return _mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128(a), shuf)); } #endif @@ -333,7 +333,7 @@ template __forceinline const ssef insert(const ssef& a, /// Transpose //////////////////////////////////////////////////////////////////////////////// -__forceinline void transpose(const ssef& r0, const ssef& r1, const ssef& r2, const ssef& r3, ssef& c0, ssef& c1, ssef& c2, ssef& c3) +__forceinline void transpose(const ssef& r0, const ssef& r1, const ssef& r2, const ssef& r3, ssef& c0, ssef& c1, ssef& c2, ssef& c3) { ssef l02 = unpacklo(r0,r2); ssef h02 = unpackhi(r0,r2); @@ -345,7 +345,7 @@ __forceinline void transpose(const ssef& r0, const ssef& r1, const ssef& r2, con c3 = unpackhi(h02,h13); } -__forceinline void transpose(const ssef& r0, const ssef& r1, const ssef& r2, const ssef& r3, ssef& c0, ssef& c1, ssef& c2) +__forceinline void transpose(const ssef& r0, const ssef& r1, const ssef& r2, const ssef& r3, ssef& c0, ssef& c1, ssef& c2) { ssef l02 = unpacklo(r0,r2); ssef h02 = unpackhi(r0,r2); @@ -382,22 +382,22 @@ __forceinline size_t movemask( const ssef& a ) { return _mm_movemask_ps(a); } __forceinline ssef load4f(const float4& a) { #ifdef __KERNEL_WITH_SSE_ALIGN__ - return _mm_load_ps(&a.x); + return _mm_load_ps(&a.x); #else - return _mm_loadu_ps(&a.x); + return _mm_loadu_ps(&a.x); #endif } __forceinline ssef load4f(const float3& a) { #ifdef __KERNEL_WITH_SSE_ALIGN__ - return _mm_load_ps(&a.x); + return _mm_load_ps(&a.x); #else - return _mm_loadu_ps(&a.x); + return _mm_loadu_ps(&a.x); #endif } __forceinline ssef load4f(const void* const a) { - return _mm_load_ps((float*)a); + return _mm_load_ps((float*)a); } __forceinline ssef load1f_first(const float a) { @@ -409,14 +409,14 @@ __forceinline void store4f(void* ptr, const ssef& v) { } __forceinline ssef loadu4f(const void* const a) { - return _mm_loadu_ps((float*)a); + return _mm_loadu_ps((float*)a); } __forceinline void storeu4f(void* ptr, const ssef& v) { _mm_storeu_ps((float*)ptr,v); } -__forceinline void store4f(const sseb& mask, void* ptr, const ssef& f) { +__forceinline void store4f(const sseb& mask, void* ptr, const ssef& f) { #if defined(__KERNEL_AVX__) _mm_maskstore_ps((float*)ptr,(__m128i)mask,f); #else @@ -428,7 +428,7 @@ __forceinline ssef load4f_nt(void* ptr) { #if defined(__KERNEL_SSE41__) return _mm_castsi128_ps(_mm_stream_load_si128((__m128i*)ptr)); #else - return _mm_load_ps((float*)ptr); + return _mm_load_ps((float*)ptr); #endif } @@ -449,7 +449,7 @@ __forceinline float dot(const ssef& a, const ssef& b) { } /* calculate shuffled cross product, useful when order of components does not matter */ -__forceinline ssef cross_zxy(const ssef& a, const ssef& b) +__forceinline ssef cross_zxy(const ssef& a, const ssef& b) { const ssef a0 = a; const ssef b0 = shuffle<1,2,0,3>(b); @@ -458,7 +458,7 @@ __forceinline ssef cross_zxy(const ssef& a, const ssef& b) return msub(a0,b0,a1*b1); } -__forceinline ssef cross(const ssef& a, const ssef& b) +__forceinline ssef cross(const ssef& a, const ssef& b) { return shuffle<1,2,0,3>(cross_zxy(a, b)); } @@ -606,7 +606,7 @@ ccl_device_inline const ssef uint32_to_float(const ssei &in) template ccl_device_inline const ssef set_sign_bit(const ssef &a) { - return a ^ cast(ssei(S1 << 31, S2 << 31, S3 << 31, S4 << 31)); + return cast(cast(a) ^ ssei(S1 << 31, S2 << 31, S3 << 31, S4 << 31)); } //////////////////////////////////////////////////////////////////////////////// @@ -628,4 +628,3 @@ ccl_device_inline void print_ssef(const char *label, const ssef &a) CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_ssei.h b/intern/cycles/util/util_ssei.h index ef2a9e68b7db..ba0389cd114c 100644 --- a/intern/cycles/util/util_ssei.h +++ b/intern/cycles/util/util_ssei.h @@ -38,7 +38,7 @@ struct ssei //////////////////////////////////////////////////////////////////////////////// /// Constructors, Assignment & Cast Operators //////////////////////////////////////////////////////////////////////////////// - + __forceinline ssei ( ) {} __forceinline ssei ( const ssei& a ) { m128 = a.m128; } __forceinline ssei& operator=( const ssei& a ) { m128 = a.m128; return *this; } @@ -173,15 +173,15 @@ __forceinline const sseb operator <=( const ssei& a, const ssei& b ) { return !( __forceinline const sseb operator <=( const ssei& a, const int32_t& b ) { return a <= ssei(b); } __forceinline const sseb operator <=( const int32_t& a, const ssei& b ) { return ssei(a) <= b; } -__forceinline const ssei select( const sseb& m, const ssei& t, const ssei& f ) { +__forceinline const ssei select( const sseb& m, const ssei& t, const ssei& f ) { #ifdef __KERNEL_SSE41__ - return _mm_castps_si128(_mm_blendv_ps(_mm_castsi128_ps(f), _mm_castsi128_ps(t), m)); + return _mm_castps_si128(_mm_blendv_ps(_mm_castsi128_ps(f), _mm_castsi128_ps(t), m)); #else - return _mm_or_si128(_mm_and_si128(m, t), _mm_andnot_si128(m, f)); + return _mm_or_si128(_mm_and_si128(m, t), _mm_andnot_si128(m, f)); #endif } -__forceinline const ssei select( const int mask, const ssei& t, const ssei& f ) { +__forceinline const ssei select( const int mask, const ssei& t, const ssei& f ) { #if defined(__KERNEL_SSE41__) && ((!defined(__clang__) && !defined(_MSC_VER)) || defined(__INTEL_COMPILER)) return _mm_castps_si128(_mm_blend_ps(_mm_castsi128_ps(f), _mm_castsi128_ps(t), mask)); #else @@ -249,8 +249,8 @@ __forceinline int reduce_add(const ssei& v) { return v[0]+v[1]+v[2]+v[3]; } /// Memory load and store operations //////////////////////////////////////////////////////////////////////////////// -__forceinline ssei load4i( const void* const a ) { - return _mm_load_si128((__m128i*)a); +__forceinline ssei load4i( const void* const a ) { + return _mm_load_si128((__m128i*)a); } __forceinline void store4i(void* ptr, const ssei& v) { @@ -261,7 +261,7 @@ __forceinline void storeu4i(void* ptr, const ssei& v) { _mm_storeu_si128((__m128i*)ptr,v); } -__forceinline void store4i( const sseb& mask, void* ptr, const ssei& i ) { +__forceinline void store4i( const sseb& mask, void* ptr, const ssei& i ) { #if defined (__KERNEL_AVX__) _mm_maskstore_ps((float*)ptr,(__m128i)mask,_mm_castsi128_ps(i)); #else @@ -269,17 +269,17 @@ __forceinline void store4i( const sseb& mask, void* ptr, const ssei& i ) { #endif } -__forceinline ssei load4i_nt (void* ptr) { +__forceinline ssei load4i_nt (void* ptr) { #if defined(__KERNEL_SSE41__) - return _mm_stream_load_si128((__m128i*)ptr); + return _mm_stream_load_si128((__m128i*)ptr); #else - return _mm_load_si128((__m128i*)ptr); + return _mm_load_si128((__m128i*)ptr); #endif } -__forceinline void store4i_nt(void* ptr, const ssei& v) { +__forceinline void store4i_nt(void* ptr, const ssei& v) { #if defined(__KERNEL_SSE41__) - _mm_stream_ps((float*)ptr,_mm_castsi128_ps(v)); + _mm_stream_ps((float*)ptr,_mm_castsi128_ps(v)); #else _mm_store_si128((__m128i*)ptr,v); #endif @@ -300,4 +300,3 @@ ccl_device_inline void print_ssei(const char *label, const ssei &a) CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_static_assert.h b/intern/cycles/util/util_static_assert.h index e90049254de5..dc3cb3f6ecc7 100644 --- a/intern/cycles/util/util_static_assert.h +++ b/intern/cycles/util/util_static_assert.h @@ -22,27 +22,7 @@ CCL_NAMESPACE_BEGIN /* TODO(sergey): In theory CUDA might work with own static assert * implementation since it's just pure C++. */ -#ifndef __KERNEL_GPU__ -# if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -/* C++11 has built-in static_assert() */ -# elif defined(static_assert) -/* Some platforms might have static_assert() defined even tho their - * C++ support wouldn't be declared to be C++11. - */ -# else /* C++11 or MSVC2015 */ -template class StaticAssertFailure; -template <> class StaticAssertFailure {}; -# define _static_assert_private_glue_impl(A, B) A ## B -# define _static_assert_glue(A, B) _static_assert_private_glue_impl(A, B) -# ifdef __COUNTER__ -# define static_assert(condition, message) \ - enum {_static_assert_glue(q_static_assert_result, __COUNTER__) = sizeof(StaticAssertFailure)} // NOLINT -# else /* __COUNTER__ */ -# define static_assert(condition, message) \ - enum {_static_assert_glue(q_static_assert_result, __LINE__) = sizeof(StaticAssertFailure)} // NOLINT -# endif /* __COUNTER__ */ -# endif /* C++11 or MSVC2015 */ -#else /* __KERNEL_GPU__ */ +#ifdef __KERNEL_GPU__ # ifndef static_assert # define static_assert(statement, message) # endif diff --git a/intern/cycles/util/util_string.cpp b/intern/cycles/util/util_string.cpp index 94ad512982cc..47119e90a450 100644 --- a/intern/cycles/util/util_string.cpp +++ b/intern/cycles/util/util_string.cpp @@ -168,6 +168,11 @@ string string_from_bool(bool var) return "False"; } +string to_string(const char *str) +{ + return string(str); +} + /* Wide char strings helpers for Windows. */ #ifdef _WIN32 @@ -293,4 +298,3 @@ string string_human_readable_number(size_t num) } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_string.h b/intern/cycles/util/util_string.h index e2c105db9c14..3a4f4398158f 100644 --- a/intern/cycles/util/util_string.h +++ b/intern/cycles/util/util_string.h @@ -29,6 +29,7 @@ using std::string; using std::stringstream; using std::ostringstream; using std::istringstream; +using std::to_string; #ifdef __GNUC__ #define PRINTF_ATTRIBUTE __attribute__((format(printf, 1, 2))) @@ -49,6 +50,7 @@ bool string_endswith(const string& s, const char *end); string string_strip(const string& s); string string_remove_trademark(const string& s); string string_from_bool(const bool var); +string to_string(const char *str); /* Wide char strings are only used on Windows to deal with non-ascii * characters in file names and such. No reason to use such strings @@ -73,4 +75,3 @@ string string_human_readable_number(size_t num); CCL_NAMESPACE_END #endif /* __UTIL_STRING_H__ */ - diff --git a/intern/cycles/util/util_system.cpp b/intern/cycles/util/util_system.cpp index 5f5211228c5c..1b039888452b 100644 --- a/intern/cycles/util/util_system.cpp +++ b/intern/cycles/util/util_system.cpp @@ -107,25 +107,26 @@ unsigned short system_cpu_process_groups(unsigned short max_groups, #if !defined(_WIN32) || defined(FREE_WINDOWS) static void __cpuid(int data[4], int selector) { -#ifdef __x86_64__ +#if defined(__x86_64__) asm("cpuid" : "=a" (data[0]), "=b" (data[1]), "=c" (data[2]), "=d" (data[3]) : "a"(selector)); -#else -#ifdef __i386__ +#elif defined(__i386__) asm("pushl %%ebx \n\t" - "cpuid \n\t" - "movl %%ebx, %1 \n\t" - "popl %%ebx \n\t" : "=a" (data[0]), "=r" (data[1]), "=c" (data[2]), "=d" (data[3]) : "a"(selector)); + "cpuid \n\t" + "movl %%ebx, %1 \n\t" + "popl %%ebx \n\t" + : "=a" (data[0]), "=r" (data[1]), "=c" (data[2]), "=d" (data[3]) + : "a"(selector) + : "ebx"); #else data[0] = data[1] = data[2] = data[3] = 0; #endif -#endif } #endif string system_cpu_brand_string() { - char buf[48]; - int result[4]; + char buf[48] = {0}; + int result[4] = {0}; __cpuid(result, 0x80000000); @@ -300,7 +301,7 @@ size_t system_physical_ram() #elif defined(__APPLE__) uint64_t ram = 0; size_t len = sizeof(ram); - if (sysctlbyname("hw.memsize", &ram, &len, NULL, 0) == 0) { + if(sysctlbyname("hw.memsize", &ram, &len, NULL, 0) == 0) { return ram; } return 0; @@ -312,4 +313,3 @@ size_t system_physical_ram() } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_system.h b/intern/cycles/util/util_system.h index e55dd6dd136d..42ad72356b99 100644 --- a/intern/cycles/util/util_system.h +++ b/intern/cycles/util/util_system.h @@ -47,4 +47,3 @@ size_t system_physical_ram(); CCL_NAMESPACE_END #endif /* __UTIL_SYSTEM_H__ */ - diff --git a/intern/cycles/util/util_task.cpp b/intern/cycles/util/util_task.cpp index 9df1096de8a8..2d21d6b5a18f 100644 --- a/intern/cycles/util/util_task.cpp +++ b/intern/cycles/util/util_task.cpp @@ -122,7 +122,7 @@ void TaskPool::cancel() do_cancel = true; TaskScheduler::clear(this); - + { thread_scoped_lock num_lock(num_mutex); @@ -210,7 +210,7 @@ void TaskScheduler::init(int num_threads) int current_group_threads = 0; if(num_groups > 1) { process_groups.resize(num_groups); - num_process_groups = system_cpu_process_groups(num_groups, + num_process_groups = system_cpu_process_groups(num_groups, &process_groups[0]); if(num_process_groups == 1) { current_group_threads = system_cpu_group_thread_count(process_groups[0]); @@ -251,7 +251,7 @@ void TaskScheduler::init(int num_threads) } } } - + users++; } @@ -295,7 +295,7 @@ bool TaskScheduler::thread_wait_pop(Entry& entry) assert(do_exit); return false; } - + entry = queue.front(); queue.pop_front(); @@ -518,4 +518,3 @@ string TaskPool::Summary::full_report() const } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_task.h b/intern/cycles/util/util_task.h index 3ebfb007e401..15f0d341be70 100644 --- a/intern/cycles/util/util_task.h +++ b/intern/cycles/util/util_task.h @@ -118,7 +118,7 @@ class TaskPool }; /* Task Scheduler - * + * * Central scheduler that holds running threads ready to execute tasks. A singe * queue holds the task from all pools. */ @@ -207,4 +207,3 @@ class DedicatedTaskPool CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_texture.h b/intern/cycles/util/util_texture.h index 4b5f630427d4..f752e81128d5 100644 --- a/intern/cycles/util/util_texture.h +++ b/intern/cycles/util/util_texture.h @@ -53,6 +53,8 @@ typedef enum ImageDataType { IMAGE_DATA_TYPE_FLOAT = 3, IMAGE_DATA_TYPE_BYTE = 4, IMAGE_DATA_TYPE_HALF = 5, + IMAGE_DATA_TYPE_USHORT4 = 6, + IMAGE_DATA_TYPE_USHORT = 7, IMAGE_DATA_NUM_TYPES } ImageDataType; diff --git a/intern/cycles/util/util_thread.cpp b/intern/cycles/util/util_thread.cpp index c66aa484264c..16a8591a8a95 100644 --- a/intern/cycles/util/util_thread.cpp +++ b/intern/cycles/util/util_thread.cpp @@ -26,11 +26,7 @@ thread::thread(function run_cb, int group) joined_(false), group_(group) { -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) thread_ = std::thread(&thread::run, this); -#else - pthread_create(&pthread_id_, NULL, run, (void*)this); -#endif } thread::~thread() @@ -64,7 +60,6 @@ void *thread::run(void *arg) bool thread::join() { joined_ = true; -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) try { thread_.join(); return true; @@ -72,9 +67,6 @@ bool thread::join() catch (const std::system_error&) { return false; } -#else - return pthread_join(pthread_id_, NULL) == 0; -#endif } CCL_NAMESPACE_END diff --git a/intern/cycles/util/util_thread.h b/intern/cycles/util/util_thread.h index 4d8f464359cf..f39fcfb4279b 100644 --- a/intern/cycles/util/util_thread.h +++ b/intern/cycles/util/util_thread.h @@ -17,15 +17,10 @@ #ifndef __UTIL_THREAD_H__ #define __UTIL_THREAD_H__ -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# include -# include -# include -# include -#else -# include -# include -#endif +#include +#include +#include +#include #include #ifdef _WIN32 @@ -42,16 +37,9 @@ CCL_NAMESPACE_BEGIN -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) typedef std::mutex thread_mutex; typedef std::unique_lock thread_scoped_lock; typedef std::condition_variable thread_condition_variable; -#else -/* use boost for mutexes */ -typedef boost::mutex thread_mutex; -typedef boost::mutex::scoped_lock thread_scoped_lock; -typedef boost::condition_variable thread_condition_variable; -#endif /* own pthread based implementation, to avoid boost version conflicts with * dynamically loaded blender plugins */ @@ -66,11 +54,7 @@ class thread { protected: function run_cb_; -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) std::thread thread_; -#else - pthread_t pthread_id_; -#endif bool joined_; int group_; }; @@ -155,4 +139,3 @@ class thread_scoped_spin_lock { CCL_NAMESPACE_END #endif /* __UTIL_THREAD_H__ */ - diff --git a/intern/cycles/util/util_time.cpp b/intern/cycles/util/util_time.cpp index 7c39aa294bf6..bc6ac4e20996 100644 --- a/intern/cycles/util/util_time.cpp +++ b/intern/cycles/util/util_time.cpp @@ -77,4 +77,3 @@ void time_sleep(double t) CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_time.h b/intern/cycles/util/util_time.h index f03aa590e9b1..13281bf188b8 100644 --- a/intern/cycles/util/util_time.h +++ b/intern/cycles/util/util_time.h @@ -59,4 +59,3 @@ class scoped_timer { CCL_NAMESPACE_END #endif - diff --git a/intern/cycles/util/util_transform.cpp b/intern/cycles/util/util_transform.cpp index 206c3da23ebd..c72e729a2e5d 100644 --- a/intern/cycles/util/util_transform.cpp +++ b/intern/cycles/util/util_transform.cpp @@ -16,10 +16,10 @@ /* * Adapted from code with license: - * + * * Copyright (c) 2002, Industrial Light & Magic, a division of Lucas * Digital Ltd. LLC. All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -31,8 +31,8 @@ * distribution. * * Neither the name of Industrial Light & Magic nor the names of its * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * + * from this software without specific prior written permission. + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -236,7 +236,7 @@ static void transform_decompose(DecomposedTransform *decomp, const Transform *tf for(int i = 0; i < 3; i++) for(int j = 0; j < 4; j++) Rnext[i][j] = 0.5f * (R[i][j] + Rit[i][j]); - + norm = 0.0f; for(int i = 0; i < 3; i++) { norm = max(norm, diff --git a/intern/cycles/util/util_transform.h b/intern/cycles/util/util_transform.h index 987f4dac7779..e781f85dded5 100644 --- a/intern/cycles/util/util_transform.h +++ b/intern/cycles/util/util_transform.h @@ -258,7 +258,7 @@ ccl_device_inline bool transform_uniform_scale(const Transform& tfm, float& scal /* the epsilon here is quite arbitrary, but this function is only used for * surface area and bump, where we expect it to not be so sensitive */ float eps = 1e-6f; - + float sx = len_squared(float4_to_float3(tfm.x)); float sy = len_squared(float4_to_float3(tfm.y)); float sz = len_squared(float4_to_float3(tfm.z)); @@ -471,4 +471,3 @@ OPENCL_TRANSFORM_ADDRSPACE_DECLARE(transform_direction_transposed) CCL_NAMESPACE_END #endif /* __UTIL_TRANSFORM_H__ */ - diff --git a/intern/cycles/util/util_types.h b/intern/cycles/util/util_types.h index 84206a7ba5a3..96c549b9be50 100644 --- a/intern/cycles/util/util_types.h +++ b/intern/cycles/util/util_types.h @@ -116,9 +116,12 @@ CCL_NAMESPACE_END #include "util/util_types_uint3.h" #include "util/util_types_uint4.h" +#include "util/util_types_ushort4.h" + #include "util/util_types_float2.h" #include "util/util_types_float3.h" #include "util/util_types_float4.h" +#include "util/util_types_float8.h" #include "util/util_types_vector3.h" @@ -138,6 +141,7 @@ CCL_NAMESPACE_END #include "util/util_types_float2_impl.h" #include "util/util_types_float3_impl.h" #include "util/util_types_float4_impl.h" +#include "util/util_types_float8_impl.h" #include "util/util_types_vector3_impl.h" @@ -146,8 +150,10 @@ CCL_NAMESPACE_END # include "util/util_sseb.h" # include "util/util_ssei.h" # include "util/util_ssef.h" +#if defined(__KERNEL_AVX__) || defined(__KERNEL_AVX2__) +# include "util/util_avxb.h" # include "util/util_avxf.h" #endif +#endif #endif /* __UTIL_TYPES_H__ */ - diff --git a/intern/cycles/util/util_types_float4_impl.h b/intern/cycles/util/util_types_float4_impl.h index 09f45f47d384..a49fac65b100 100644 --- a/intern/cycles/util/util_types_float4_impl.h +++ b/intern/cycles/util/util_types_float4_impl.h @@ -102,7 +102,7 @@ ccl_device_inline float4 make_float4(const int4& i) ccl_device_inline void print_float4(const char *label, const float4& a) { printf("%s: %.8f %.8f %.8f %.8f\n", - label, + label, (double)a.x, (double)a.y, (double)a.z, (double)a.w); } #endif /* __KERNEL_GPU__ */ diff --git a/intern/cycles/util/util_types_float8.h b/intern/cycles/util/util_types_float8.h new file mode 100644 index 000000000000..64ec5a713558 --- /dev/null +++ b/intern/cycles/util/util_types_float8.h @@ -0,0 +1,71 @@ +/* +* Original code Copyright 2017, Intel Corporation +* Modifications Copyright 2018, Blender Foundation. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Intel Corporation nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef __UTIL_TYPES_FLOAT8_H__ +#define __UTIL_TYPES_FLOAT8_H__ + +#ifndef __UTIL_TYPES_H__ +# error "Do not include this file directly, include util_types.h instead." +#endif + +CCL_NAMESPACE_BEGIN + +#ifndef __KERNEL_GPU__ + +struct ccl_try_align(16) float8 { +#ifdef __KERNEL_AVX2__ + union { + __m256 m256; + struct { float a, b, c, d, e, f, g, h; }; + }; + + __forceinline float8(); + __forceinline float8(const float8& a); + __forceinline explicit float8(const __m256& a); + + __forceinline operator const __m256&(void) const; + __forceinline operator __m256&(void); + + __forceinline float8& operator =(const float8& a); + +#else /* __KERNEL_AVX2__ */ + float a, b, c, d, e, f, g, h; +#endif /* __KERNEL_AVX2__ */ + + __forceinline float operator[](int i) const; + __forceinline float& operator[](int i); +}; + +ccl_device_inline float8 make_float8(float f); +ccl_device_inline float8 make_float8(float a, float b, float c, float d, + float e, float f, float g, float h); +#endif /* __KERNEL_GPU__ */ + +CCL_NAMESPACE_END + +#endif /* __UTIL_TYPES_FLOAT8_H__ */ diff --git a/intern/cycles/util/util_types_float8_impl.h b/intern/cycles/util/util_types_float8_impl.h new file mode 100644 index 000000000000..ebf8260bc7c0 --- /dev/null +++ b/intern/cycles/util/util_types_float8_impl.h @@ -0,0 +1,114 @@ +/* +* Original code Copyright 2017, Intel Corporation +* Modifications Copyright 2018, Blender Foundation. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* * Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of Intel Corporation nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef __UTIL_TYPES_FLOAT8_IMPL_H__ +#define __UTIL_TYPES_FLOAT8_IMPL_H__ + +#ifndef __UTIL_TYPES_H__ +# error "Do not include this file directly, include util_types.h instead." +#endif + +#ifndef __KERNEL_GPU__ +# include +#endif + +CCL_NAMESPACE_BEGIN + +#ifndef __KERNEL_GPU__ +#ifdef __KERNEL_AVX2__ +__forceinline float8::float8() +{ +} + +__forceinline float8::float8(const float8& f) + : m256(f.m256) +{ +} + +__forceinline float8::float8(const __m256& f) + : m256(f) +{ +} + +__forceinline float8::operator const __m256&(void) const +{ + return m256; +} + +__forceinline float8::operator __m256&(void) +{ + return m256; +} + +__forceinline float8& float8::operator =(const float8& f) +{ + m256 = f.m256; + return *this; +} +#endif /* __KERNEL_AVX2__ */ + +__forceinline float float8::operator[](int i) const +{ + util_assert(i >= 0); + util_assert(i < 8); + return *(&a + i); +} + +__forceinline float& float8::operator[](int i) +{ + util_assert(i >= 0); + util_assert(i < 8); + return *(&a + i); +} + +ccl_device_inline float8 make_float8(float f) +{ +#ifdef __KERNEL_AVX2__ + float8 r(_mm256_set1_ps(f)); +#else + float8 r = {f, f, f, f, f, f, f, f}; +#endif + return r; +} + +ccl_device_inline float8 make_float8(float a, float b, float c, float d, + float e, float f, float g, float h) +{ +#ifdef __KERNEL_AVX2__ + float8 r(_mm256_set_ps(a, b, c, d, e, f, g, h)); +#else + float8 r = {a, b, c, d, e, f, g, h}; +#endif + return r; +} + +#endif /* __KERNEL_GPU__ */ + +CCL_NAMESPACE_END + +#endif /* __UTIL_TYPES_FLOAT8_IMPL_H__ */ diff --git a/intern/cycles/util/util_types_ushort4.h b/intern/cycles/util/util_types_ushort4.h new file mode 100644 index 000000000000..fc234b8abe8e --- /dev/null +++ b/intern/cycles/util/util_types_ushort4.h @@ -0,0 +1,36 @@ +/* + * Copyright 2011-2017 Blender Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UTIL_TYPES_USHORT4_H__ +#define __UTIL_TYPES_USHORT4_H__ + +#ifndef __UTIL_TYPES_H__ +# error "Do not include this file directly, include util_types.h instead." +#endif + +CCL_NAMESPACE_BEGIN + +#ifndef __KERNEL_GPU__ + +struct ushort4 { + uint16_t x, y, z, w; +}; + +#endif + +CCL_NAMESPACE_END + +#endif /* __UTIL_TYPES_USHORT4_H__ */ diff --git a/intern/cycles/util/util_vector.h b/intern/cycles/util/util_vector.h index 8d91d3936a48..0b33221ad4de 100644 --- a/intern/cycles/util/util_vector.h +++ b/intern/cycles/util/util_vector.h @@ -59,11 +59,7 @@ class vector : public std::vector void shrink_to_fit(void) { -#if __cplusplus < 201103L - vector().swap(*this); -#else std::vector::shrink_to_fit(); -#endif } void free_memory(void) @@ -341,4 +337,3 @@ class array CCL_NAMESPACE_END #endif /* __UTIL_VECTOR_H__ */ - diff --git a/intern/cycles/util/util_view.cpp b/intern/cycles/util/util_view.cpp index 10d86167921a..3836cc86ee0e 100644 --- a/intern/cycles/util/util_view.cpp +++ b/intern/cycles/util/util_view.cpp @@ -272,4 +272,3 @@ void view_redraw() } CCL_NAMESPACE_END - diff --git a/intern/cycles/util/util_view.h b/intern/cycles/util/util_view.h index 5def0564175e..e603e605776c 100644 --- a/intern/cycles/util/util_view.h +++ b/intern/cycles/util/util_view.h @@ -41,4 +41,3 @@ void view_redraw(); CCL_NAMESPACE_END #endif /*__UTIL_VIEW_H__*/ - diff --git a/intern/cycles/util/util_windows.h b/intern/cycles/util/util_windows.h index 7ea3e65c2c5b..3b23ce8a3cb2 100644 --- a/intern/cycles/util/util_windows.h +++ b/intern/cycles/util/util_windows.h @@ -57,4 +57,3 @@ CCL_NAMESPACE_END #endif /* WIN32 */ #endif /* __UTIL_WINDOWS_H__ */ - diff --git a/intern/dualcon/CMakeLists.txt b/intern/dualcon/CMakeLists.txt index 40c8ef8ff9c5..bd8c2eff5040 100644 --- a/intern/dualcon/CMakeLists.txt +++ b/intern/dualcon/CMakeLists.txt @@ -30,7 +30,7 @@ set(SRC intern/marching_cubes_table.cpp intern/octree.cpp intern/Projections.cpp - + intern/cubes.h intern/GeoCommon.h intern/manifold_table.h @@ -46,4 +46,3 @@ set(SRC ) blender_add_lib(bf_intern_dualcon "${SRC}" "${INC}" "${INC_SYS}") - diff --git a/intern/ghost/GHOST_IEvent.h b/intern/ghost/GHOST_IEvent.h index 83273716950a..2842e0094933 100644 --- a/intern/ghost/GHOST_IEvent.h +++ b/intern/ghost/GHOST_IEvent.h @@ -91,4 +91,3 @@ class GHOST_IEvent }; #endif // __GHOST_IEVENT_H__ - diff --git a/intern/ghost/GHOST_ISystem.h b/intern/ghost/GHOST_ISystem.h index a6f92d4a099a..be2a94bd5087 100644 --- a/intern/ghost/GHOST_ISystem.h +++ b/intern/ghost/GHOST_ISystem.h @@ -447,4 +447,3 @@ class GHOST_ISystem }; #endif // __GHOST_ISYSTEM_H__ - diff --git a/intern/ghost/GHOST_ITimerTask.h b/intern/ghost/GHOST_ITimerTask.h index dd3db5623ccc..6ae62952e981 100644 --- a/intern/ghost/GHOST_ITimerTask.h +++ b/intern/ghost/GHOST_ITimerTask.h @@ -91,4 +91,3 @@ class GHOST_ITimerTask }; #endif // __GHOST_ITIMERTASK_H__ - diff --git a/intern/ghost/GHOST_IWindow.h b/intern/ghost/GHOST_IWindow.h index 5a3403bcbd3d..b2f9fe24944f 100644 --- a/intern/ghost/GHOST_IWindow.h +++ b/intern/ghost/GHOST_IWindow.h @@ -368,4 +368,3 @@ class GHOST_IWindow }; #endif // __GHOST_IWINDOW_H__ - diff --git a/intern/ghost/GHOST_Rect.h b/intern/ghost/GHOST_Rect.h index c2ea8db0a66f..7906d169cdaa 100644 --- a/intern/ghost/GHOST_Rect.h +++ b/intern/ghost/GHOST_Rect.h @@ -257,4 +257,3 @@ inline bool GHOST_Rect::isInside(GHOST_TInt32 x, GHOST_TInt32 y) const } #endif // __GHOST_RECT_H__ - diff --git a/intern/ghost/GHOST_Types.h b/intern/ghost/GHOST_Types.h index b206bb677a7e..1fc1d1a3e567 100644 --- a/intern/ghost/GHOST_Types.h +++ b/intern/ghost/GHOST_Types.h @@ -557,4 +557,3 @@ typedef void (*GHOST_TimerProcPtr)(struct GHOST_TimerTaskHandle__ *task, GHOST_T #endif #endif // __GHOST_TYPES_H__ - diff --git a/intern/ghost/intern/GHOST_Buttons.h b/intern/ghost/intern/GHOST_Buttons.h index aed9a3cc81fb..d9d4e4a32b9a 100644 --- a/intern/ghost/intern/GHOST_Buttons.h +++ b/intern/ghost/intern/GHOST_Buttons.h @@ -75,4 +75,3 @@ struct GHOST_Buttons { }; #endif // __GHOST_BUTTONS_H__ - diff --git a/intern/ghost/intern/GHOST_CallbackEventConsumer.h b/intern/ghost/intern/GHOST_CallbackEventConsumer.h index 3505d651fa36..789ce1e1a72f 100644 --- a/intern/ghost/intern/GHOST_CallbackEventConsumer.h +++ b/intern/ghost/intern/GHOST_CallbackEventConsumer.h @@ -80,4 +80,3 @@ class GHOST_CallbackEventConsumer : public GHOST_IEventConsumer }; #endif // __GHOST_CALLBACKEVENTCONSUMER_H__ - diff --git a/intern/ghost/intern/GHOST_Debug.h b/intern/ghost/intern/GHOST_Debug.h index 658c9bf5d2cf..b899027f051e 100644 --- a/intern/ghost/intern/GHOST_Debug.h +++ b/intern/ghost/intern/GHOST_Debug.h @@ -84,4 +84,3 @@ #endif // GHOST_DEBUG #endif // __GHOST_DEBUG_H__ - diff --git a/intern/ghost/intern/GHOST_DisplayManager.h b/intern/ghost/intern/GHOST_DisplayManager.h index 02a742a54db3..20d724f61065 100644 --- a/intern/ghost/intern/GHOST_DisplayManager.h +++ b/intern/ghost/intern/GHOST_DisplayManager.h @@ -142,4 +142,3 @@ class GHOST_DisplayManager #endif // __GHOST_DISPLAYMANAGER_H__ - diff --git a/intern/ghost/intern/GHOST_DisplayManagerCocoa.h b/intern/ghost/intern/GHOST_DisplayManagerCocoa.h index 3ce0b4e22394..17343cb901df 100644 --- a/intern/ghost/intern/GHOST_DisplayManagerCocoa.h +++ b/intern/ghost/intern/GHOST_DisplayManagerCocoa.h @@ -103,4 +103,3 @@ class GHOST_DisplayManagerCocoa : public GHOST_DisplayManager #endif // __GHOST_DISPLAYMANAGERCOCOA_H__ - diff --git a/intern/ghost/intern/GHOST_DisplayManagerWin32.h b/intern/ghost/intern/GHOST_DisplayManagerWin32.h index f0d6d62083cf..997accf7e964 100644 --- a/intern/ghost/intern/GHOST_DisplayManagerWin32.h +++ b/intern/ghost/intern/GHOST_DisplayManagerWin32.h @@ -98,4 +98,3 @@ class GHOST_DisplayManagerWin32 : public GHOST_DisplayManager #endif // __GHOST_DISPLAYMANAGERWIN32_H__ - diff --git a/intern/ghost/intern/GHOST_DisplayManagerX11.h b/intern/ghost/intern/GHOST_DisplayManagerX11.h index 857a8a5fce89..e330e7756e39 100644 --- a/intern/ghost/intern/GHOST_DisplayManagerX11.h +++ b/intern/ghost/intern/GHOST_DisplayManagerX11.h @@ -120,4 +120,3 @@ class GHOST_DisplayManagerX11 : public GHOST_DisplayManager #endif // - diff --git a/intern/ghost/intern/GHOST_DropTargetWin32.cpp b/intern/ghost/intern/GHOST_DropTargetWin32.cpp index 79d7a2d48b4a..de12dfad8159 100644 --- a/intern/ghost/intern/GHOST_DropTargetWin32.cpp +++ b/intern/ghost/intern/GHOST_DropTargetWin32.cpp @@ -392,4 +392,3 @@ void printLastError(void) } } #endif // GHOST_DEBUG - diff --git a/intern/ghost/intern/GHOST_Event.h b/intern/ghost/intern/GHOST_Event.h index 278870738c2d..a0aef6550eb7 100644 --- a/intern/ghost/intern/GHOST_Event.h +++ b/intern/ghost/intern/GHOST_Event.h @@ -104,4 +104,3 @@ class GHOST_Event : public GHOST_IEvent }; #endif // __GHOST_EVENT_H__ - diff --git a/intern/ghost/intern/GHOST_EventButton.h b/intern/ghost/intern/GHOST_EventButton.h index ef5c5efa2027..2f004c3ca002 100644 --- a/intern/ghost/intern/GHOST_EventButton.h +++ b/intern/ghost/intern/GHOST_EventButton.h @@ -63,4 +63,3 @@ class GHOST_EventButton : public GHOST_Event }; #endif // __GHOST_EVENTBUTTON_H__ - diff --git a/intern/ghost/intern/GHOST_EventCursor.h b/intern/ghost/intern/GHOST_EventCursor.h index 1c6f762cd9e0..05b1caee081b 100644 --- a/intern/ghost/intern/GHOST_EventCursor.h +++ b/intern/ghost/intern/GHOST_EventCursor.h @@ -65,4 +65,3 @@ class GHOST_EventCursor : public GHOST_Event #endif // __GHOST_EVENTCURSOR_H__ - diff --git a/intern/ghost/intern/GHOST_EventDragnDrop.h b/intern/ghost/intern/GHOST_EventDragnDrop.h index c9f4f08b53ca..2f10c2e8f994 100644 --- a/intern/ghost/intern/GHOST_EventDragnDrop.h +++ b/intern/ghost/intern/GHOST_EventDragnDrop.h @@ -133,4 +133,3 @@ class GHOST_EventDragnDrop : public GHOST_Event }; #endif // __GHOST_EVENTDRAGNDROP_H__ - diff --git a/intern/ghost/intern/GHOST_EventKey.h b/intern/ghost/intern/GHOST_EventKey.h index 7e8675965033..8052625496ad 100644 --- a/intern/ghost/intern/GHOST_EventKey.h +++ b/intern/ghost/intern/GHOST_EventKey.h @@ -89,4 +89,3 @@ class GHOST_EventKey : public GHOST_Event }; #endif // __GHOST_EVENTKEY_H__ - diff --git a/intern/ghost/intern/GHOST_EventManager.h b/intern/ghost/intern/GHOST_EventManager.h index efad19616adc..651dd29536ef 100644 --- a/intern/ghost/intern/GHOST_EventManager.h +++ b/intern/ghost/intern/GHOST_EventManager.h @@ -161,4 +161,3 @@ class GHOST_EventManager }; #endif // __GHOST_EVENTMANAGER_H__ - diff --git a/intern/ghost/intern/GHOST_EventPrinter.cpp b/intern/ghost/intern/GHOST_EventPrinter.cpp index 221b85b80bac..359db162c041 100644 --- a/intern/ghost/intern/GHOST_EventPrinter.cpp +++ b/intern/ghost/intern/GHOST_EventPrinter.cpp @@ -338,4 +338,3 @@ void GHOST_EventPrinter::getKeyString(GHOST_TKey key, char str[32]) const sprintf(str, "%s", tstr); } } - diff --git a/intern/ghost/intern/GHOST_EventPrinter.h b/intern/ghost/intern/GHOST_EventPrinter.h index 0cbb7ca467d2..d4c49ae82945 100644 --- a/intern/ghost/intern/GHOST_EventPrinter.h +++ b/intern/ghost/intern/GHOST_EventPrinter.h @@ -61,4 +61,3 @@ class GHOST_EventPrinter : public GHOST_IEventConsumer }; #endif // __GHOST_EVENTPRINTER_H__ - diff --git a/intern/ghost/intern/GHOST_EventString.h b/intern/ghost/intern/GHOST_EventString.h index 391af0f8e2d7..a0cb35bead64 100644 --- a/intern/ghost/intern/GHOST_EventString.h +++ b/intern/ghost/intern/GHOST_EventString.h @@ -64,4 +64,3 @@ class GHOST_EventString : public GHOST_Event }; #endif // __GHOST_EVENTSTRING_H__ - diff --git a/intern/ghost/intern/GHOST_EventTrackpad.h b/intern/ghost/intern/GHOST_EventTrackpad.h index b4e80b5fd06e..faf0f1697d08 100644 --- a/intern/ghost/intern/GHOST_EventTrackpad.h +++ b/intern/ghost/intern/GHOST_EventTrackpad.h @@ -72,4 +72,3 @@ class GHOST_EventTrackpad : public GHOST_Event #endif // _GHOST_EVENT_PAN_H_ - diff --git a/intern/ghost/intern/GHOST_EventWheel.h b/intern/ghost/intern/GHOST_EventWheel.h index a632492acb95..c4e1c1af38c0 100644 --- a/intern/ghost/intern/GHOST_EventWheel.h +++ b/intern/ghost/intern/GHOST_EventWheel.h @@ -65,4 +65,3 @@ class GHOST_EventWheel : public GHOST_Event #endif // __GHOST_EVENTWHEEL_H__ - diff --git a/intern/ghost/intern/GHOST_ISystem.cpp b/intern/ghost/intern/GHOST_ISystem.cpp index 37d5926ffc20..21cec19328e0 100644 --- a/intern/ghost/intern/GHOST_ISystem.cpp +++ b/intern/ghost/intern/GHOST_ISystem.cpp @@ -105,4 +105,3 @@ GHOST_ISystem *GHOST_ISystem::getSystem() { return m_system; } - diff --git a/intern/ghost/intern/GHOST_ISystemPaths.cpp b/intern/ghost/intern/GHOST_ISystemPaths.cpp index 8bd7fbe4f9b2..57062a76fd57 100644 --- a/intern/ghost/intern/GHOST_ISystemPaths.cpp +++ b/intern/ghost/intern/GHOST_ISystemPaths.cpp @@ -96,6 +96,3 @@ GHOST_ISystemPaths *GHOST_ISystemPaths::get() } return m_systemPaths; } - - - diff --git a/intern/ghost/intern/GHOST_ModifierKeys.h b/intern/ghost/intern/GHOST_ModifierKeys.h index a30b66c4634d..72bcbcb5e01e 100644 --- a/intern/ghost/intern/GHOST_ModifierKeys.h +++ b/intern/ghost/intern/GHOST_ModifierKeys.h @@ -100,4 +100,3 @@ struct GHOST_ModifierKeys { }; #endif // __GHOST_MODIFIERKEYS_H__ - diff --git a/intern/ghost/intern/GHOST_Rect.cpp b/intern/ghost/intern/GHOST_Rect.cpp index 646dae9f2422..780ac9aaf53f 100644 --- a/intern/ghost/intern/GHOST_Rect.cpp +++ b/intern/ghost/intern/GHOST_Rect.cpp @@ -138,4 +138,3 @@ bool GHOST_Rect::clip(GHOST_Rect& r) const } return clipped; } - diff --git a/intern/ghost/intern/GHOST_System.cpp b/intern/ghost/intern/GHOST_System.cpp index f849993ae6d6..0629eacc3ffc 100644 --- a/intern/ghost/intern/GHOST_System.cpp +++ b/intern/ghost/intern/GHOST_System.cpp @@ -390,4 +390,3 @@ bool GHOST_System::useNativePixel(void) m_nativePixel = true; return 1; } - diff --git a/intern/ghost/intern/GHOST_System.h b/intern/ghost/intern/GHOST_System.h index 6831b3d07d9c..2fd8603516dd 100644 --- a/intern/ghost/intern/GHOST_System.h +++ b/intern/ghost/intern/GHOST_System.h @@ -396,4 +396,3 @@ inline GHOST_NDOFManager *GHOST_System::getNDOFManager() const #endif #endif // __GHOST_SYSTEM_H__ - diff --git a/intern/ghost/intern/GHOST_SystemCocoa.h b/intern/ghost/intern/GHOST_SystemCocoa.h index 2457a9457f11..d31df79bc2b8 100644 --- a/intern/ghost/intern/GHOST_SystemCocoa.h +++ b/intern/ghost/intern/GHOST_SystemCocoa.h @@ -304,4 +304,3 @@ class GHOST_SystemCocoa : public GHOST_System { }; #endif // __GHOST_SYSTEMCOCOA_H__ - diff --git a/intern/ghost/intern/GHOST_SystemPaths.h b/intern/ghost/intern/GHOST_SystemPaths.h index fbaa8ad8ba5d..25e696fc0814 100644 --- a/intern/ghost/intern/GHOST_SystemPaths.h +++ b/intern/ghost/intern/GHOST_SystemPaths.h @@ -77,5 +77,3 @@ class GHOST_SystemPaths : public GHOST_ISystemPaths }; #endif - - diff --git a/intern/ghost/intern/GHOST_SystemPathsWin32.h b/intern/ghost/intern/GHOST_SystemPathsWin32.h index 5685a57eba83..caa90a956aac 100644 --- a/intern/ghost/intern/GHOST_SystemPathsWin32.h +++ b/intern/ghost/intern/GHOST_SystemPathsWin32.h @@ -90,4 +90,3 @@ class GHOST_SystemPathsWin32 : public GHOST_SystemPaths { }; #endif // __GHOST_SYSTEMPATHSWIN32_H__ - diff --git a/intern/ghost/intern/GHOST_SystemWin32.cpp b/intern/ghost/intern/GHOST_SystemWin32.cpp index 7f5d561014e5..960baf3aa468 100644 --- a/intern/ghost/intern/GHOST_SystemWin32.cpp +++ b/intern/ghost/intern/GHOST_SystemWin32.cpp @@ -1249,7 +1249,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, * will not be dispatched to OUR active window if we minimize one of OUR windows. */ if (LOWORD(wParam) == WA_INACTIVE) window->lostMouseCapture(); - + window->processWin32TabletActivateEvent(GET_WM_ACTIVATE_STATE(wParam, lParam)); lResult = ::DefWindowProc(hwnd, msg, wParam, lParam); break; } diff --git a/intern/ghost/intern/GHOST_SystemX11.cpp b/intern/ghost/intern/GHOST_SystemX11.cpp index c8a6fe2d4132..577151820c07 100644 --- a/intern/ghost/intern/GHOST_SystemX11.cpp +++ b/intern/ghost/intern/GHOST_SystemX11.cpp @@ -258,7 +258,7 @@ GHOST_SystemX11:: #endif /* WITH_X11_XINPUT */ if (m_xkb_descr) { - XkbFreeNames(m_xkb_descr, XkbKeyNamesMask, false); + XkbFreeKeyboard (m_xkb_descr, XkbAllComponentsMask, true); } XCloseDisplay(m_display); @@ -1847,7 +1847,7 @@ ghost_key_from_keycode(const XkbDescPtr xkb_descr, const KeyCode keycode) #endif } } - else { + else if (keycode != 0) { GHOST_ASSERT(false, "KeyCode out of range!"); } return GHOST_kKeyUnknown; diff --git a/intern/ghost/intern/GHOST_SystemX11.h b/intern/ghost/intern/GHOST_SystemX11.h index de9a2cdcce9a..ed1542ec4908 100644 --- a/intern/ghost/intern/GHOST_SystemX11.h +++ b/intern/ghost/intern/GHOST_SystemX11.h @@ -418,4 +418,3 @@ class GHOST_SystemX11 : public GHOST_System { }; #endif - diff --git a/intern/ghost/intern/GHOST_TaskbarX11.cpp b/intern/ghost/intern/GHOST_TaskbarX11.cpp index 2ef82dc6636b..9826ccdfa37d 100644 --- a/intern/ghost/intern/GHOST_TaskbarX11.cpp +++ b/intern/ghost/intern/GHOST_TaskbarX11.cpp @@ -44,7 +44,7 @@ static unity_event_loop_t unity_event_loop; static bool libunity_initialized = false; static bool libunity_available = false; -void* libunity_handle = NULL; +static void *libunity_handle = NULL; void GHOST_TaskBarX11::free() { diff --git a/intern/ghost/intern/GHOST_TimerManager.h b/intern/ghost/intern/GHOST_TimerManager.h index 78026a743eb3..8a06b37c73a9 100644 --- a/intern/ghost/intern/GHOST_TimerManager.h +++ b/intern/ghost/intern/GHOST_TimerManager.h @@ -127,4 +127,3 @@ class GHOST_TimerManager }; #endif // __GHOST_TIMERMANAGER_H__ - diff --git a/intern/ghost/intern/GHOST_TimerTask.h b/intern/ghost/intern/GHOST_TimerTask.h index fa35fd134f5c..bf28700ad581 100644 --- a/intern/ghost/intern/GHOST_TimerTask.h +++ b/intern/ghost/intern/GHOST_TimerTask.h @@ -193,4 +193,3 @@ class GHOST_TimerTask : public GHOST_ITimerTask }; #endif // __GHOST_TIMERTASK_H__ - diff --git a/intern/ghost/intern/GHOST_Window.cpp b/intern/ghost/intern/GHOST_Window.cpp index 6596028d5a17..6931ede067ed 100644 --- a/intern/ghost/intern/GHOST_Window.cpp +++ b/intern/ghost/intern/GHOST_Window.cpp @@ -242,4 +242,3 @@ bool GHOST_Window::getModifiedState() { return m_isUnsavedChanges; } - diff --git a/intern/ghost/intern/GHOST_Window.h b/intern/ghost/intern/GHOST_Window.h index 413a3315225b..e6a4682ee7cb 100644 --- a/intern/ghost/intern/GHOST_Window.h +++ b/intern/ghost/intern/GHOST_Window.h @@ -461,4 +461,3 @@ inline GHOST_TStandardCursor GHOST_Window::getCursorShape() const } #endif // _GHOST_WINDOW_H - diff --git a/intern/ghost/intern/GHOST_WindowManager.h b/intern/ghost/intern/GHOST_WindowManager.h index a7dde2af39c4..46a1e6c09cd9 100644 --- a/intern/ghost/intern/GHOST_WindowManager.h +++ b/intern/ghost/intern/GHOST_WindowManager.h @@ -168,4 +168,3 @@ class GHOST_WindowManager }; #endif // __GHOST_WINDOWMANAGER_H__ - diff --git a/intern/ghost/intern/GHOST_WindowWin32.cpp b/intern/ghost/intern/GHOST_WindowWin32.cpp index 6e89299e1ca1..92de41a859b5 100644 --- a/intern/ghost/intern/GHOST_WindowWin32.cpp +++ b/intern/ghost/intern/GHOST_WindowWin32.cpp @@ -265,23 +265,22 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system, GHOST_WIN32_WTInfo fpWTInfo = (GHOST_WIN32_WTInfo) ::GetProcAddress(m_wintab, "WTInfoA"); GHOST_WIN32_WTOpen fpWTOpen = (GHOST_WIN32_WTOpen) ::GetProcAddress(m_wintab, "WTOpenA"); - // let's see if we can initialize tablet here - /* check if WinTab available. */ - if (fpWTInfo && fpWTInfo(0, 0, NULL)) { + // Let's see if we can initialize tablet here. + // Check if WinTab available by getting system context info. + LOGCONTEXT lc = { 0 }; + lc.lcOptions |= CXO_SYSTEM; + if (fpWTInfo && fpWTInfo(WTI_DEFSYSCTX, 0, &lc)) { // Now init the tablet - LOGCONTEXT lc; /* The maximum tablet size, pressure and orientation (tilt) */ AXIS TabletX, TabletY, Pressure, Orientation[3]; // Open a Wintab context - // Get default context information - fpWTInfo(WTI_DEFCONTEXT, 0, &lc); - // Open the context lc.lcPktData = PACKETDATA; lc.lcPktMode = PACKETMODE; - lc.lcOptions |= CXO_MESSAGES | CXO_SYSTEM; + lc.lcOptions |= CXO_MESSAGES; + lc.lcMoveMask = PACKETDATA; /* Set the entire tablet as active */ fpWTInfo(WTI_DEVICES, DVC_X, &TabletX); @@ -309,11 +308,17 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system, } if (fpWTOpen) { - m_tablet = fpWTOpen(m_hWnd, &lc, TRUE); + // The Wintab spec says we must open the context disabled if we are using cursor masks. + m_tablet = fpWTOpen(m_hWnd, &lc, FALSE); if (m_tablet) { m_tabletData = new GHOST_TabletData(); m_tabletData->Active = GHOST_kTabletModeNone; } + + GHOST_WIN32_WTEnable fpWTEnable = (GHOST_WIN32_WTEnable) ::GetProcAddress(m_wintab, "WTEnable"); + if (fpWTEnable) { + fpWTEnable(m_tablet, TRUE); + } } } } @@ -857,6 +862,23 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cur return GHOST_kSuccess; } +void GHOST_WindowWin32::processWin32TabletActivateEvent(WORD state) +{ + if (!m_tablet) { + return; + } + + GHOST_WIN32_WTEnable fpWTEnable = (GHOST_WIN32_WTEnable) ::GetProcAddress(m_wintab, "WTEnable"); + GHOST_WIN32_WTOverlap fpWTOverlap = (GHOST_WIN32_WTOverlap) ::GetProcAddress(m_wintab, "WTOverlap"); + + if (fpWTEnable) { + fpWTEnable(m_tablet, state); + if (fpWTOverlap && state) { + fpWTOverlap(m_tablet, TRUE); + } + } +} + void GHOST_WindowWin32::processWin32TabletInitEvent() { if (m_wintab && m_tabletData) { diff --git a/intern/ghost/intern/GHOST_WindowWin32.h b/intern/ghost/intern/GHOST_WindowWin32.h index d998e86c9b15..c72669ed8983 100644 --- a/intern/ghost/intern/GHOST_WindowWin32.h +++ b/intern/ghost/intern/GHOST_WindowWin32.h @@ -56,6 +56,7 @@ typedef UINT (API * GHOST_WIN32_WTInfo)(UINT, UINT, LPVOID); typedef HCTX (API * GHOST_WIN32_WTOpen)(HWND, LPLOGCONTEXTA, BOOL); typedef BOOL (API * GHOST_WIN32_WTClose)(HCTX); typedef BOOL (API * GHOST_WIN32_WTPacket)(HCTX, UINT, LPVOID); +typedef BOOL (API * GHOST_WIN32_WTEnable)(HCTX, BOOL); typedef BOOL (API * GHOST_WIN32_WTOverlap)(HCTX, BOOL); // typedefs for user32 functions to allow dynamic loading of Windows 10 DPI scaling functions @@ -249,6 +250,7 @@ class GHOST_WindowWin32 : public GHOST_Window { return m_tabletData; } + void processWin32TabletActivateEvent(WORD state); void processWin32TabletInitEvent(); void processWin32TabletEvent(WPARAM wParam, LPARAM lParam); void bringTabletContextToFront(); diff --git a/intern/ghost/intern/GHOST_WindowX11.cpp b/intern/ghost/intern/GHOST_WindowX11.cpp index 933bcd7f0122..623d57705b24 100644 --- a/intern/ghost/intern/GHOST_WindowX11.cpp +++ b/intern/ghost/intern/GHOST_WindowX11.cpp @@ -598,13 +598,15 @@ GHOST_WindowX11(GHOST_SystemX11 *system, } #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) -static void destroyICCallback(XIC /*xic*/, XPointer ptr, XPointer /*data*/) +static Bool destroyICCallback(XIC /*xic*/, XPointer ptr, XPointer /*data*/) { GHOST_PRINT("XIM input context destroyed\n"); if (ptr) { *(XIC *)ptr = NULL; } + /* Ignored by X11. */ + return True; } bool GHOST_WindowX11::createX11_XIC() @@ -1697,6 +1699,7 @@ getDPIHint() } } } + XrmDestroyDatabase(xrdb); } /* Fallback to calculating DPI using X reported DPI, set using xrandr --dpi */ diff --git a/intern/ghost/test/multitest/Basic.h b/intern/ghost/test/multitest/Basic.h index 86d68ef06cb3..3b550af609ac 100644 --- a/intern/ghost/test/multitest/Basic.h +++ b/intern/ghost/test/multitest/Basic.h @@ -38,4 +38,3 @@ void rect_copy (int dst[2][2], int src[2][2]); int rect_contains_pt (int rect[2][2], int pt[2]); int rect_width (int rect[2][2]); int rect_height (int rect[2][2]); - diff --git a/intern/ghost/test/multitest/EventToBuf.h b/intern/ghost/test/multitest/EventToBuf.h index 23b61a4cf2a5..9eb24970584e 100644 --- a/intern/ghost/test/multitest/EventToBuf.h +++ b/intern/ghost/test/multitest/EventToBuf.h @@ -27,4 +27,3 @@ char *eventtype_to_string(GHOST_TEventType type); void event_to_buf(GHOST_EventHandle evt, char buf[128]); - diff --git a/intern/ghost/test/multitest/GL.h b/intern/ghost/test/multitest/GL.h index 4a82623f9f9d..292fc5b37caf 100644 --- a/intern/ghost/test/multitest/GL.h +++ b/intern/ghost/test/multitest/GL.h @@ -37,4 +37,3 @@ #else // defined(WIN32) || defined(__APPLE__) #include #endif // defined(WIN32) || defined(__APPLE__) - diff --git a/intern/ghost/test/multitest/ScrollBar.h b/intern/ghost/test/multitest/ScrollBar.h index dd737539bf26..752ed9056b88 100644 --- a/intern/ghost/test/multitest/ScrollBar.h +++ b/intern/ghost/test/multitest/ScrollBar.h @@ -50,4 +50,3 @@ void scrollbar_get_rect (ScrollBar *sb, int rect_r[2][2]); void scrollbar_get_thumb (ScrollBar *sb, int thumb_r[2][2]); void scrollbar_free (ScrollBar *sb); - diff --git a/intern/ghost/test/multitest/Util.h b/intern/ghost/test/multitest/Util.h index 4652a0bbf4db..87ec72f5e89a 100644 --- a/intern/ghost/test/multitest/Util.h +++ b/intern/ghost/test/multitest/Util.h @@ -29,4 +29,3 @@ void* memdbl (void *mem, int *size_pr, int item_size); char* string_dup (char *str); void fatal (char *fmt, ...); - diff --git a/intern/ghost/test/multitest/WindowData.h b/intern/ghost/test/multitest/WindowData.h index 0e6c7518843f..ca8199bddd87 100644 --- a/intern/ghost/test/multitest/WindowData.h +++ b/intern/ghost/test/multitest/WindowData.h @@ -33,4 +33,3 @@ typedef struct _WindowData WindowData; WindowData* windowdata_new (void *data, WindowDataHandler handler); void windowdata_handle (WindowData *wb, GHOST_EventHandle evt); void windowdata_free (WindowData *wb); - diff --git a/intern/mikktspace/CMakeLists.txt b/intern/mikktspace/CMakeLists.txt index 8abd9559358c..a4d02093ee11 100644 --- a/intern/mikktspace/CMakeLists.txt +++ b/intern/mikktspace/CMakeLists.txt @@ -35,7 +35,7 @@ set(INC ) set(INC_SYS - + ) set(SRC @@ -45,4 +45,3 @@ set(SRC ) blender_add_lib(bf_intern_mikktspace "${SRC}" "${INC}" "${INC_SYS}") - diff --git a/intern/opencolorio/CMakeLists.txt b/intern/opencolorio/CMakeLists.txt index 75e228933aa9..ac2c95d4b639 100644 --- a/intern/opencolorio/CMakeLists.txt +++ b/intern/opencolorio/CMakeLists.txt @@ -63,6 +63,9 @@ if(WITH_OPENCOLORIO) list(APPEND INC_SYS ${BOOST_INCLUDE_DIR} ) + add_definitions( + -DOpenColorIO_STATIC + ) endif() data_to_c_simple(gpu_shader_display_transform.glsl SRC) diff --git a/intern/opensubdiv/opensubdiv_converter.cc b/intern/opensubdiv/opensubdiv_converter.cc index ea41a56768fd..fec15b118aed 100644 --- a/intern/opensubdiv/opensubdiv_converter.cc +++ b/intern/opensubdiv/opensubdiv_converter.cc @@ -542,7 +542,7 @@ namespace { OpenSubdiv::Sdc::SchemeType get_capi_scheme_type(OpenSubdiv_SchemeType type) { - switch(type) { + switch (type) { case OSD_SCHEME_BILINEAR: return OpenSubdiv::Sdc::SCHEME_BILINEAR; case OSD_SCHEME_CATMARK: @@ -550,10 +550,29 @@ OpenSubdiv::Sdc::SchemeType get_capi_scheme_type(OpenSubdiv_SchemeType type) case OSD_SCHEME_LOOP: return OpenSubdiv::Sdc::SCHEME_LOOP; } - assert(!"Unknown sceme type passed via C-API"); + assert(!"Unknown scheme type passed via C-API"); return OpenSubdiv::Sdc::SCHEME_CATMARK; } +OpenSubdiv::Sdc::Options::FVarLinearInterpolation +get_capi_fvar_linear_interpolation( + OpenSubdiv_FVarLinearInterpolation linear_interpolation) +{ + typedef OpenSubdiv::Sdc::Options Options; + switch (linear_interpolation) { + case OSD_FVAR_LINEAR_INTERPOLATION_NONE: + return Options::FVAR_LINEAR_NONE; + case OSD_FVAR_LINEAR_INTERPOLATION_CORNERS_ONLY: + return Options::FVAR_LINEAR_CORNERS_ONLY; + case OSD_FVAR_LINEAR_INTERPOLATION_BOUNDARIES: + return Options::FVAR_LINEAR_BOUNDARIES; + case OSD_FVAR_LINEAR_INTERPOLATION_ALL: + return Options::FVAR_LINEAR_ALL; + } + assert(!"Unknown fvar linear interpolation passed via C-API"); + return Options::FVAR_LINEAR_NONE; +} + } /* namespace */ struct OpenSubdiv_TopologyRefinerDescr *openSubdiv_createTopologyRefinerDescr( @@ -562,17 +581,15 @@ struct OpenSubdiv_TopologyRefinerDescr *openSubdiv_createTopologyRefinerDescr( typedef OpenSubdiv::Sdc::Options Options; using OpenSubdiv::Far::TopologyRefinerFactory; - OpenSubdiv::Sdc::SchemeType scheme_type = - get_capi_scheme_type(converter->get_type(converter)); + const OpenSubdiv::Sdc::SchemeType scheme_type = + get_capi_scheme_type(converter->get_scheme_type(converter)); + const Options::FVarLinearInterpolation linear_interpolation = + get_capi_fvar_linear_interpolation( + converter->get_fvar_linear_interpolation(converter)); Options options; options.SetVtxBoundaryInterpolation(Options::VTX_BOUNDARY_EDGE_ONLY); options.SetCreasingMethod(Options::CREASE_UNIFORM); - if (converter->get_subdiv_uvs(converter)) { - options.SetFVarLinearInterpolation(Options::FVAR_LINEAR_CORNERS_ONLY); - } - else { - options.SetFVarLinearInterpolation(Options::FVAR_LINEAR_ALL); - } + options.SetFVarLinearInterpolation(linear_interpolation); TopologyRefinerFactory::Options topology_options(scheme_type, options); @@ -663,14 +680,17 @@ int openSubdiv_topologyRefnerCompareConverter( const int num_faces = base_level.GetNumFaces(); /* Quick preliminary check. */ OpenSubdiv::Sdc::SchemeType scheme_type = - get_capi_scheme_type(converter->get_type(converter)); + get_capi_scheme_type(converter->get_scheme_type(converter)); if (scheme_type != refiner->GetSchemeType()) { return false; } const Options options = refiner->GetSchemeOptions(); - Options::FVarLinearInterpolation interp = options.GetFVarLinearInterpolation(); - const bool subdiv_uvs = (interp != Options::FVAR_LINEAR_ALL); - if (converter->get_subdiv_uvs(converter) != subdiv_uvs) { + const Options::FVarLinearInterpolation interp = + options.GetFVarLinearInterpolation(); + const Options::FVarLinearInterpolation new_interp = + get_capi_fvar_linear_interpolation( + converter->get_fvar_linear_interpolation(converter)); + if (new_interp != interp) { return false; } if (converter->get_num_verts(converter) != num_verts || diff --git a/intern/opensubdiv/opensubdiv_converter_capi.h b/intern/opensubdiv/opensubdiv_converter_capi.h index 6eda6ae5d8ab..ea4f20c59616 100644 --- a/intern/opensubdiv/opensubdiv_converter_capi.h +++ b/intern/opensubdiv/opensubdiv_converter_capi.h @@ -41,13 +41,22 @@ typedef enum OpenSubdiv_SchemeType { OSD_SCHEME_LOOP, } OpenSubdiv_SchemeType; +typedef enum OpenSubdiv_FVarLinearInterpolation { + OSD_FVAR_LINEAR_INTERPOLATION_NONE, + OSD_FVAR_LINEAR_INTERPOLATION_CORNERS_ONLY, + OSD_FVAR_LINEAR_INTERPOLATION_BOUNDARIES, + OSD_FVAR_LINEAR_INTERPOLATION_ALL, +} OpenSubdiv_FVarLinearInterpolation; + typedef struct OpenSubdiv_Converter { /* TODO(sergey): Needs to be implemented. */ /* OpenSubdiv::Sdc::Options get_options() const; */ - OpenSubdiv_SchemeType (*get_type)(const OpenSubdiv_Converter *converter); + OpenSubdiv_SchemeType (*get_scheme_type)( + const OpenSubdiv_Converter *converter); - bool (*get_subdiv_uvs)(const OpenSubdiv_Converter *converter); + OpenSubdiv_FVarLinearInterpolation (*get_fvar_linear_interpolation)( + const OpenSubdiv_Converter *converter); int (*get_num_faces)(const OpenSubdiv_Converter *converter); int (*get_num_edges)(const OpenSubdiv_Converter *converter); @@ -86,7 +95,6 @@ typedef struct OpenSubdiv_Converter { int *vert_faces); /* Face-varying data. */ - int (*get_num_uv_layers)(const OpenSubdiv_Converter *converter); void (*precalc_uv_layer)(const OpenSubdiv_Converter *converter, int layer); @@ -99,6 +107,7 @@ typedef struct OpenSubdiv_Converter { int face, int corner); + /* User data associated with this converter. */ void (*free_user_data)(const OpenSubdiv_Converter *converter); void *user_data; } OpenSubdiv_Converter; diff --git a/intern/opensubdiv/opensubdiv_evaluator_capi.cc b/intern/opensubdiv/opensubdiv_evaluator_capi.cc index c4a128213dd2..049c0aad3bf4 100644 --- a/intern/opensubdiv/opensubdiv_evaluator_capi.cc +++ b/intern/opensubdiv/opensubdiv_evaluator_capi.cc @@ -42,6 +42,7 @@ #include #include "opensubdiv_intern.h" +#include "opensubdiv_topology_refiner.h" #include "MEM_guardedalloc.h" @@ -341,7 +342,7 @@ OpenSubdiv_EvaluatorDescr *openSubdiv_createEvaluatorDescr( int subsurf_level) { /* TODO(sergey): Look into re-using refiner with GLMesh. */ - TopologyRefiner *refiner = (TopologyRefiner *)topology_refiner; + TopologyRefiner *refiner = topology_refiner->osd_refiner; if(refiner == NULL) { /* Happens on bad topology. */ return NULL; diff --git a/intern/openvdb/CMakeLists.txt b/intern/openvdb/CMakeLists.txt index f666dc78e75b..9ac0817903b0 100644 --- a/intern/openvdb/CMakeLists.txt +++ b/intern/openvdb/CMakeLists.txt @@ -38,6 +38,7 @@ set(SRC if(WITH_OPENVDB) add_definitions( -DWITH_OPENVDB + ${OPENVDB_DEFINITIONS} ) if(WITH_OPENVDB_3_ABI_COMPATIBLE) diff --git a/intern/rigidbody/CMakeLists.txt b/intern/rigidbody/CMakeLists.txt index 5d84c2cf0820..91fe1023b5e5 100644 --- a/intern/rigidbody/CMakeLists.txt +++ b/intern/rigidbody/CMakeLists.txt @@ -31,7 +31,7 @@ set(INC_SYS set(SRC rb_bullet_api.cpp - + RBI_api.h ) diff --git a/intern/rigidbody/RBI_api.h b/intern/rigidbody/RBI_api.h index 556ca959e64b..eec94bcea507 100644 --- a/intern/rigidbody/RBI_api.h +++ b/intern/rigidbody/RBI_api.h @@ -268,6 +268,7 @@ rbConstraint *RB_constraint_new_slider(float pivot[3], float orn[4], rbRigidBody rbConstraint *RB_constraint_new_piston(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2); rbConstraint *RB_constraint_new_6dof(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2); rbConstraint *RB_constraint_new_6dof_spring(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2); +rbConstraint *RB_constraint_new_6dof_spring2(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2); rbConstraint *RB_constraint_new_motor(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2); /* ............ */ @@ -299,12 +300,18 @@ void RB_constraint_set_limits_piston(rbConstraint *con, float lin_lower, float l void RB_constraint_set_limits_6dof(rbConstraint *con, int axis, float lower, float upper); /* 6dof spring specific */ -void RB_constraint_set_limits_6dof_spring(rbConstraint *con, int axis, float lower, float upper); void RB_constraint_set_stiffness_6dof_spring(rbConstraint *con, int axis, float stiffness); void RB_constraint_set_damping_6dof_spring(rbConstraint *con, int axis, float damping); void RB_constraint_set_spring_6dof_spring(rbConstraint *con, int axis, int enable); void RB_constraint_set_equilibrium_6dof_spring(rbConstraint *con); +/* 6dof spring 2 specific */ +void RB_constraint_set_limits_6dof_spring2(rbConstraint *con, int axis, float lower, float upper); +void RB_constraint_set_stiffness_6dof_spring2(rbConstraint *con, int axis, float stiffness); +void RB_constraint_set_damping_6dof_spring2(rbConstraint *con, int axis, float damping); +void RB_constraint_set_spring_6dof_spring2(rbConstraint *con, int axis, int enable); +void RB_constraint_set_equilibrium_6dof_spring2(rbConstraint *con); + /* motors */ void RB_constraint_set_enable_motor(rbConstraint *con, int enable_lin, int enable_ang); void RB_constraint_set_max_impulse_motor(rbConstraint *con, float max_impulse_lin, float max_impulse_ang); diff --git a/intern/rigidbody/rb_bullet_api.cpp b/intern/rigidbody/rb_bullet_api.cpp index a9fbcb285290..6a50c5c93ee7 100644 --- a/intern/rigidbody/rb_bullet_api.cpp +++ b/intern/rigidbody/rb_bullet_api.cpp @@ -954,11 +954,25 @@ rbConstraint *RB_constraint_new_6dof_spring(float pivot[3], float orn[4], rbRigi make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn); - btTypedConstraint *con = new btGeneric6DofSpring2Constraint(*body1, *body2, transform1, transform2); + btTypedConstraint *con = new btGeneric6DofSpringConstraint(*body1, *body2, transform1, transform2, true); return (rbConstraint *)con; } +rbConstraint *RB_constraint_new_6dof_spring2(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2) +{ + btRigidBody *body1 = rb1->body; + btRigidBody *body2 = rb2->body; + btTransform transform1; + btTransform transform2; + + make_constraint_transforms(transform1, transform2, body1, body2, pivot, orn); + + btTypedConstraint *con = new btGeneric6DofSpring2Constraint(*body1, *body2, transform1, transform2); + + return (rbConstraint *)con; +} + rbConstraint *RB_constraint_new_motor(float pivot[3], float orn[4], rbRigidBody *rb1, rbRigidBody *rb2) { btRigidBody *body1 = rb1->body; @@ -1034,7 +1048,7 @@ void RB_constraint_set_limits_6dof(rbConstraint *con, int axis, float lower, flo constraint->setLimit(axis, lower, upper); } -void RB_constraint_set_limits_6dof_spring(rbConstraint *con, int axis, float lower, float upper) +void RB_constraint_set_limits_6dof_spring2(rbConstraint *con, int axis, float lower, float upper) { btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); @@ -1043,26 +1057,57 @@ void RB_constraint_set_limits_6dof_spring(rbConstraint *con, int axis, float low void RB_constraint_set_stiffness_6dof_spring(rbConstraint *con, int axis, float stiffness) { - btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + btGeneric6DofSpringConstraint *constraint = reinterpret_cast(con); constraint->setStiffness(axis, stiffness); } void RB_constraint_set_damping_6dof_spring(rbConstraint *con, int axis, float damping) { - btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + btGeneric6DofSpringConstraint *constraint = reinterpret_cast(con); + + // invert damping range so that 0 = no damping + damping = (damping > 1.0f) ? 0.0f : 1.0f - damping; constraint->setDamping(axis, damping); } void RB_constraint_set_spring_6dof_spring(rbConstraint *con, int axis, int enable) { - btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + btGeneric6DofSpringConstraint *constraint = reinterpret_cast(con); constraint->enableSpring(axis, enable); } void RB_constraint_set_equilibrium_6dof_spring(rbConstraint *con) +{ + btGeneric6DofSpringConstraint *constraint = reinterpret_cast(con); + + constraint->setEquilibriumPoint(); +} + +void RB_constraint_set_stiffness_6dof_spring2(rbConstraint *con, int axis, float stiffness) +{ + btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + + constraint->setStiffness(axis, stiffness); +} + +void RB_constraint_set_damping_6dof_spring2(rbConstraint *con, int axis, float damping) +{ + btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + + constraint->setDamping(axis, damping); +} + +void RB_constraint_set_spring_6dof_spring2(rbConstraint *con, int axis, int enable) +{ + btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); + + constraint->enableSpring(axis, enable); +} + +void RB_constraint_set_equilibrium_6dof_spring2(rbConstraint *con) { btGeneric6DofSpring2Constraint *constraint = reinterpret_cast(con); diff --git a/intern/smoke/CMakeLists.txt b/intern/smoke/CMakeLists.txt index 57678ecf2f8d..a95d8281974a 100644 --- a/intern/smoke/CMakeLists.txt +++ b/intern/smoke/CMakeLists.txt @@ -99,4 +99,3 @@ if(WITH_FFTW3) endif() blender_add_lib(bf_intern_smoke "${SRC}" "${INC}" "${INC_SYS}") - diff --git a/make.bat b/make.bat index 18e861f8fdb7..5fb428fbed03 100644 --- a/make.bat +++ b/make.bat @@ -31,7 +31,7 @@ if "%BUILD_UPDATE%" == "1" ( goto EOF ) -call "%BLENDER_DIR%\build_files\windows\detect_architecture.cmd" +call "%BLENDER_DIR%\build_files\windows\detect_architecture.cmd" if "%BUILD_VS_YEAR%" == "" ( call "%BLENDER_DIR%\build_files\windows\autodetect_msvc.cmd" @@ -47,28 +47,28 @@ if "%BUILD_VS_YEAR%" == "" ( ) ) -call "%BLENDER_DIR%\build_files\windows\set_build_dir.cmd" +call "%BLENDER_DIR%\build_files\windows\set_build_dir.cmd" echo Building blender with VS%BUILD_VS_YEAR% for %BUILD_ARCH% in %BUILD_DIR% -call "%BLENDER_DIR%\build_files\windows\check_libraries.cmd" +call "%BLENDER_DIR%\build_files\windows\check_libraries.cmd" if errorlevel 1 goto EOF -call "%BLENDER_DIR%\build_files\windows\check_submodules.cmd" +call "%BLENDER_DIR%\build_files\windows\check_submodules.cmd" if errorlevel 1 goto EOF if "%BUILD_WITH_NINJA%" == "" ( - call "%BLENDER_DIR%\build_files\windows\configure_msbuild.cmd" + call "%BLENDER_DIR%\build_files\windows\configure_msbuild.cmd" if errorlevel 1 goto EOF - call "%BLENDER_DIR%\build_files\windows\build_msbuild.cmd" + call "%BLENDER_DIR%\build_files\windows\build_msbuild.cmd" if errorlevel 1 goto EOF ) else ( - call "%BLENDER_DIR%\build_files\windows\configure_ninja.cmd" + call "%BLENDER_DIR%\build_files\windows\configure_ninja.cmd" if errorlevel 1 goto EOF - call "%BLENDER_DIR%\build_files\windows\build_ninja.cmd" + call "%BLENDER_DIR%\build_files\windows\build_ninja.cmd" if errorlevel 1 goto EOF ) -:EOF \ No newline at end of file +:EOF diff --git a/release/datafiles/blender_icons_update.py b/release/datafiles/blender_icons_update.py index 68f4ef23082a..3aeb66978241 100755 --- a/release/datafiles/blender_icons_update.py +++ b/release/datafiles/blender_icons_update.py @@ -11,8 +11,8 @@ def run(cmd): BASEDIR = os.path.abspath(os.path.dirname(__file__)) -inkscape_bin = "inkscape" -blender_bin = "blender" +inkscape_bin = os.environ.get("INKSCAPE_BIN", "inkscape") +blender_bin = os.environ.get("BLENDER_BIN", "blender") if sys.platform == 'darwin': inkscape_app_path = '/Applications/Inkscape.app/Contents/Resources/script' diff --git a/release/scripts/modules/addon_utils.py b/release/scripts/modules/addon_utils.py index 97fc45189f25..5cb313ec41b6 100644 --- a/release/scripts/modules/addon_utils.py +++ b/release/scripts/modules/addon_utils.py @@ -78,7 +78,7 @@ def fake_module(mod_name, mod_path, speedy=True, force_support=None): try: file_mod = open(mod_path, "r", encoding='UTF-8') except OSError as ex: - print("Error opening file %r: %s" % (mod_path, ex)) + print("Error opening file:", mod_path, ex) return None with file_mod: @@ -116,7 +116,7 @@ def fake_module(mod_name, mod_path, speedy=True, force_support=None): try: ast_data = ast.parse(data, filename=mod_path) except: - print("Syntax error 'ast.parse' can't read %r" % mod_path) + print("Syntax error 'ast.parse' can't read:", repr(mod_path)) import traceback traceback.print_exc() ast_data = None @@ -138,7 +138,7 @@ def fake_module(mod_name, mod_path, speedy=True, force_support=None): mod.__file__ = mod_path mod.__time__ = os.path.getmtime(mod_path) except: - print("AST error parsing bl_info for %s" % mod_name) + print("AST error parsing bl_info for:", mod_name) import traceback traceback.print_exc() raise @@ -148,8 +148,11 @@ def fake_module(mod_name, mod_path, speedy=True, force_support=None): return mod else: - print("fake_module: addon missing 'bl_info' " - "gives bad performance!: %r" % mod_path) + print( + "fake_module: addon missing 'bl_info' " + "gives bad performance!:", + repr(mod_path), + ) return None modules_stale = set(module_cache.keys()) @@ -167,17 +170,21 @@ def fake_module(mod_name, mod_path, speedy=True, force_support=None): mod = module_cache.get(mod_name) if mod: if mod.__file__ != mod_path: - print("multiple addons with the same name:\n %r\n %r" % - (mod.__file__, mod_path)) + print( + "multiple addons with the same name:\n" + " " f"{mod.__file__!r}" "\n" + " " f"{mod_path!r}" + ) error_duplicates.append((mod.bl_info["name"], mod.__file__, mod_path)) elif mod.__time__ != os.path.getmtime(mod_path): - print("reloading addon:", - mod_name, - mod.__time__, - os.path.getmtime(mod_path), - mod_path, - ) + print( + "reloading addon:", + mod_name, + mod.__time__, + os.path.getmtime(mod_path), + repr(mod_path), + ) del module_cache[mod_name] mod = None @@ -209,6 +216,8 @@ def modules(module_cache=addons_fake_modules, *, refresh=True): ) ) return mod_list + + modules._is_first = True @@ -231,10 +240,12 @@ def check(module_name): ) if loaded_state is Ellipsis: - print("Warning: addon-module %r found module " - "but without __addon_enabled__ field, " - "possible name collision from file: %r" % - (module_name, getattr(mod, "__file__", ""))) + print( + "Warning: addon-module " f"{module_name:s}" " found module " + "but without '__addon_enabled__' field, " + "possible name collision from file:", + repr(getattr(mod, "__file__", "")), + ) loaded_state = False @@ -301,8 +312,10 @@ def handle_error(ex): try: mod.unregister() except Exception as ex: - print("Exception in module unregister(): %r" % - getattr(mod, "__file__", module_name)) + print( + "Exception in module unregister():", + repr(getattr(mod, "__file__", module_name)), + ) handle_error(ex) return None @@ -311,7 +324,7 @@ def handle_error(ex): mtime_new = os.path.getmtime(mod.__file__) if mtime_orig != mtime_new: import importlib - print("module changed on disk:", mod.__file__, "reloading...") + print("module changed on disk:", repr(mod.__file__), "reloading...") try: importlib.reload(mod) @@ -341,7 +354,7 @@ def handle_error(ex): except Exception as ex: # if the addon doesn't exist, dont print full traceback if type(ex) is ImportError and ex.name == module_name: - print("addon not found: %r" % module_name) + print("addon not found:", repr(module_name)) else: handle_error(ex) @@ -356,8 +369,10 @@ def handle_error(ex): try: mod.register() except Exception as ex: - print("Exception in module register(): %r" % - getattr(mod, "__file__", module_name)) + print( + "Exception in module register():", + getattr(mod, "__file__", module_name), + ) handle_error(ex) del sys.modules[module_name] if default_set: @@ -404,12 +419,15 @@ def handle_error(ex): try: mod.unregister() except Exception as ex: - print("Exception in module unregister(): %r" % - getattr(mod, "__file__", module_name)) + mod_path = getattr(mod, "__file__", module_name) + print("Exception in module unregister():", repr(mod_path)) + del mod_path handle_error(ex) else: - print("addon_utils.disable: %s not %s." % - (module_name, "disabled" if mod is None else "loaded")) + print( + "addon_utils.disable: " f"{module_name:s}" " not", + ("disabled" if mod is None else "loaded") + ) # could be in more than once, unlikely but better do this just in case. if default_set: diff --git a/release/scripts/modules/bl_app_override/__init__.py b/release/scripts/modules/bl_app_override/__init__.py index f17878b4822f..2104b10bf851 100644 --- a/release/scripts/modules/bl_app_override/__init__.py +++ b/release/scripts/modules/bl_app_override/__init__.py @@ -172,6 +172,7 @@ def draw_override(func_orig, self_real, context): class Wrapper(cls_real): __slots__ = () + def __getattribute__(self, attr): if attr == "layout": return UILayout_Fake(self_real.layout) diff --git a/release/scripts/modules/bl_i18n_utils/bl_extract_messages.py b/release/scripts/modules/bl_i18n_utils/bl_extract_messages.py index bbeb1780355f..10a386039c43 100644 --- a/release/scripts/modules/bl_i18n_utils/bl_extract_messages.py +++ b/release/scripts/modules/bl_i18n_utils/bl_extract_messages.py @@ -120,8 +120,11 @@ def check(check_ctxt, msgs, key, msgsrc, settings): key[1][0].isalpha() and not key[1][0].isupper()): not_capitalized.add(key) if end_point is not None: - if (key[1].strip().endswith('.') and not key[1].strip().endswith('...') and - key[1] not in settings.WARN_MSGID_END_POINT_ALLOWED): + if ( + key[1].strip().endswith('.') and + (not key[1].strip().endswith('...')) and + key[1] not in settings.WARN_MSGID_END_POINT_ALLOWED + ): end_point.add(key) if undoc_ops is not None: if key[1] == settings.UNDOC_OPS_STR: @@ -183,8 +186,10 @@ def _print(*args, **kwargs): # if py_in_rna and key in py_in_rna: # _print("\t\t-> RNA message also used in py UI code!") if spell_errors and spell_errors.get(key): - lines = ["\t\t-> {}: misspelled, suggestions are ({})".format(w, "'" + "', '".join(errs) + "'") - for w, errs in spell_errors[key]] + lines = [ + "\t\t-> {}: misspelled, suggestions are ({})".format(w, "'" + "', '".join(errs) + "'") + for w, errs in spell_errors[key] + ] _print("\n".join(lines)) _print("\t\t{}".format("\n\t\t".join(pot.msgs[key].sources))) @@ -215,13 +220,13 @@ def dump_rna_messages(msgs, reports, settings, verbose=False): """ def class_blacklist(): blacklist_rna_class = {getattr(bpy.types, cls_id) for cls_id in ( - # core classes - "Context", "Event", "Function", "UILayout", "UnknownType", "Property", "Struct", - # registerable classes - "Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro", "KeyingSetInfo", - # window classes - "Window", - ) + # core classes + "Context", "Event", "Function", "UILayout", "UnknownType", "Property", "Struct", + # registerable classes + "Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro", "KeyingSetInfo", + # window classes + "Window", + ) } # More builtin classes we don't need to parse. @@ -380,6 +385,7 @@ def walk_keymap_hierarchy(hier, msgsrc_prev): # Dump Messages operator_categories = {} + def process_cls_list(cls_list): if not cls_list: return @@ -447,6 +453,7 @@ def dump_py_messages_from_files(msgs, reports, files, settings): i18n_contexts = bpy.app.translations.contexts root_paths = tuple(bpy.utils.resource_path(t) for t in ('USER', 'LOCAL', 'SYSTEM')) + def make_rel(path): for rp in root_paths: if path.startswith(rp): @@ -510,6 +517,7 @@ def extract_strings_split(node): return [_extract_string_merge(estr_ls, nds_ls) for estr_ls, nds_ls in bag] i18n_ctxt_ids = {v for v in bpy.app.translations.contexts_C_to_py.values()} + def _ctxt_to_ctxt(node): # We must try, to some extend, to get contexts from vars instead of only literal strings... ctxt = extract_strings(node)[0] @@ -561,9 +569,9 @@ def _op_to_ctxt(node): translate_kw = { "text": ((("text_ctxt",), _ctxt_to_ctxt), (("operator",), _op_to_ctxt), - ), - "msgid": ((("msgctxt",), _ctxt_to_ctxt), ), + "msgid": ((("msgctxt",), _ctxt_to_ctxt), + ), "message": (), } @@ -611,7 +619,7 @@ def _op_to_ctxt(node): func_translate_args[func_id] = pgettext_variants_args for func_id in func_ids: func_translate_args[func_id] = pgettext_variants_args - #print(func_translate_args) + # print(func_translate_args) # Break recursive nodes look up on some kind of nodes. # E.g. we don't want to get strings inside subscripts (blah["foo"])! @@ -666,7 +674,7 @@ def _op_to_ctxt(node): if kw.arg == arg_kw: context_elements[arg_kw] = kw.value break - #print(context_elements) + # print(context_elements) for kws, proc in translate_kw[msgid]: if set(kws) <= context_elements.keys(): args = tuple(context_elements[k] for k in kws) @@ -676,7 +684,7 @@ def _op_to_ctxt(node): msgctxts[msgid] = ctxt break - #print(translate_args) + # print(translate_args) # do nothing if not found for arg_kw, (arg_pos, _) in func_args.items(): msgctxt = msgctxts[arg_kw] @@ -706,7 +714,7 @@ def _get_files(path): return [] if os.path.isdir(path): return [os.path.join(dpath, fn) for dpath, _, fnames in os.walk(path) for fn in fnames - if not fn.startswith("_") and fn.endswith(".py")] + if not fn.startswith("_") and fn.endswith(".py")] return [path] files = [] @@ -738,7 +746,9 @@ def get_contexts(): pygettexts = tuple(re.compile(r).search for r in settings.PYGETTEXT_KEYWORDS) _clean_str = re.compile(settings.str_clean_re).finditer - clean_str = lambda s: "".join(m.group("clean") for m in _clean_str(s)) + + def clean_str(s): + return "".join(m.group("clean") for m in _clean_str(s)) def dump_src_file(path, rel_path, msgs, reports, settings): def process_entry(_msgctxt, _msgid): @@ -873,10 +883,10 @@ def dump_messages(do_messages, do_checks, settings): process_msg(msgs, settings.DEFAULT_CONTEXT, cat[1], "Language categories’ labels from bl_i18n_utils/settings.py", reports, None, settings) - #pot.check() + # pot.check() pot.unescape() # Strings gathered in py/C source code may contain escaped chars... print_info(reports, pot) - #pot.check() + # pot.check() if do_messages: print("Writing messages…") diff --git a/release/scripts/modules/bl_i18n_utils/merge_po.py b/release/scripts/modules/bl_i18n_utils/merge_po.py index ecb261239999..7e3c8a42b175 100755 --- a/release/scripts/modules/bl_i18n_utils/merge_po.py +++ b/release/scripts/modules/bl_i18n_utils/merge_po.py @@ -43,14 +43,17 @@ # XXX This is a quick hack to make it work with new I18n... objects! To be reworked! def main(): import argparse - parser = argparse.ArgumentParser(description= - "Merge one or more .po files into the first dest one.\n" - "If a msgkey (msgctxt, msgid) is present in more than one merged po, the one in the first file " - "wins, unless it’s marked as fuzzy and one later is not.\n" - "The fuzzy flag is removed if necessary.\n" - "All other comments are never modified.\n" - "Commented messages in dst will always remain commented, and commented messages are never merged " - "from sources.") + parser = argparse.ArgumentParser( + description=( + "Merge one or more .po files into the first dest one.\n" + "If a msgkey (msgctxt, msgid) is present in more than one merged po, the one in the first file " + "wins, unless it’s marked as fuzzy and one later is not.\n" + "The fuzzy flag is removed if necessary.\n" + "All other comments are never modified.\n" + "Commented messages in dst will always remain commented, and commented messages are never merged " + "from sources." + ), + ) parser.add_argument('-s', '--stats', action="store_true", help="Show statistics info.") parser.add_argument('-r', '--replace', action="store_true", help="Replace existing messages of same \"level\" already in dest po.") diff --git a/release/scripts/modules/bl_i18n_utils/utils.py b/release/scripts/modules/bl_i18n_utils/utils.py index 5fdb6b88cbf9..880721176e09 100644 --- a/release/scripts/modules/bl_i18n_utils/utils.py +++ b/release/scripts/modules/bl_i18n_utils/utils.py @@ -32,9 +32,9 @@ #import time from bl_i18n_utils import ( - settings, - utils_rtl, - ) + settings, + utils_rtl, +) import bpy @@ -44,6 +44,8 @@ _valid_po_path_re = re.compile(r"^\S+:[0-9]+$") + + def is_valid_po_path(path): return bool(_valid_po_path_re.match(path)) @@ -57,9 +59,10 @@ def get_best_similar(data): # We also consider to never make a match when len differs more than -len_key / 2, +len_key * 2 (which is valid # as long as use_similar is not below ~0.7). # Gives an overall ~20% of improvement! - #tmp = difflib.get_close_matches(key[1], similar_pool, n=1, cutoff=use_similar) - #if tmp: - #tmp = tmp[0] + + # tmp = difflib.get_close_matches(key[1], similar_pool, n=1, cutoff=use_similar) + # if tmp: + # tmp = tmp[0] tmp = None s = difflib.SequenceMatcher() s.set_seq2(key[1]) @@ -178,9 +181,11 @@ def enable_addons(addons=None, support=None, disable=False, check_only=False): userpref = bpy.context.user_preferences used_ext = {ext.module for ext in userpref.addons} - ret = [mod for mod in addon_utils.modules() - if ((addons and mod.__name__ in addons) or - (not addons and addon_utils.module_bl_info(mod)["support"] in support))] + ret = [ + mod for mod in addon_utils.modules() + if ((addons and mod.__name__ in addons) or + (not addons and addon_utils.module_bl_info(mod)["support"] in support)) + ] if not check_only: for mod in ret: @@ -229,18 +234,21 @@ def __init__(self, msgctxt_lines=None, msgid_lines=None, msgstr_lines=None, comm def _get_msgctxt(self): return "".join(self.msgctxt_lines) + def _set_msgctxt(self, ctxt): self.msgctxt_lines = [ctxt] msgctxt = property(_get_msgctxt, _set_msgctxt) def _get_msgid(self): return "".join(self.msgid_lines) + def _set_msgid(self, msgid): self.msgid_lines = [msgid] msgid = property(_get_msgid, _set_msgid) def _get_msgstr(self): return "".join(self.msgstr_lines) + def _set_msgstr(self, msgstr): self.msgstr_lines = [msgstr] msgstr = property(_get_msgstr, _set_msgstr) @@ -250,12 +258,15 @@ def _get_sources(self): lstrip2 = len(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM) return ([l[lstrip1:] for l in self.comment_lines if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE)] + [l[lstrip2:] for l in self.comment_lines - if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)]) + if l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)]) + def _set_sources(self, sources): cmmlines = self.comment_lines.copy() for l in cmmlines: - if (l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE) or - l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM)): + if ( + l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE) or + l.startswith(self.settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM) + ): self.comment_lines.remove(l) lines_src = [] lines_src_custom = [] @@ -791,7 +802,7 @@ def find_best_messages_matches(self, msgs, msgmap, rna_ctxt, rna_struct_name, rn if len(k) > 1 and src_rna in src_to_msg: k &= src_to_msg[src_rna] msgmap["rna_tip"]["key"] = k - #print(k) + # print(k) btip = getattr(msgs, msgmap["but_tip"]["msgstr"]) #print("button tip: " + btip) if btip and btip not in {rtip, etip}: @@ -1051,12 +1062,13 @@ def write_messages_to_mo(self, fname): import subprocess with tempfile.NamedTemporaryFile(mode='w+', encoding="utf-8") as tmp_po_f: self.write_messages_to_po(tmp_po_f) - cmd = (self.settings.GETTEXT_MSGFMT_EXECUTABLE, - "--statistics", # show stats - tmp_po_f.name, - "-o", - fname, - ) + cmd = ( + self.settings.GETTEXT_MSGFMT_EXECUTABLE, + "--statistics", # show stats + tmp_po_f.name, + "-o", + fname, + ) print("Running ", " ".join(cmd)) ret = subprocess.call(cmd) print("Finished.") @@ -1081,6 +1093,7 @@ def write_messages_to_mo(self, fname): EOT = b"0x04" # Used to concatenate context and msgid _msgid_offset = 0 _msgstr_offset = 0 + def _gen(v): nonlocal _msgid_offset, _msgstr_offset msgid = v.msgid.encode("utf-8") @@ -1188,6 +1201,7 @@ def __init__(self, kind=None, src=None, langs=set(), settings=settings): def _py_file_get(self): return self.src.get(self.settings.PARSER_PY_ID) + def _py_file_set(self, value): self.src[self.settings.PARSER_PY_ID] = value py_file = property(_py_file_get, _py_file_set) @@ -1252,7 +1266,8 @@ def print_stats(self, prefix="", print_msgs=True): _ctx_txt = "s are" else: _ctx_txt = " is" - lines = (("", + lines = (( + "", "Average stats for all {} translations:\n".format(self.nbr_trans), " {:>6.1%} done!\n".format(self.lvl / self.nbr_trans), " {:>6.1%} of messages are tooltips.\n".format(self.lvl_ttips / self.nbr_trans), @@ -1350,10 +1365,10 @@ def parse_from_py(self, src, langs=set()): comment_lines = [self.settings.PO_COMMENT_PREFIX + c for c in user_comments] + common_comment_lines self.trans[uid].msgs[key] = I18nMessage(ctxt, [key[1]], [msgstr], comment_lines, False, is_fuzzy, settings=self.settings) - #key = self.settings.PO_HEADER_KEY - #for uid, trans in self.trans.items(): - #if key not in trans.msgs: - #trans.msgs[key] + # key = self.settings.PO_HEADER_KEY + # for uid, trans in self.trans.items(): + # if key not in trans.msgs: + # trans.msgs[key] self.unescape() def write(self, kind, langs=set()): diff --git a/release/scripts/modules/bl_i18n_utils/utils_spell_check.py b/release/scripts/modules/bl_i18n_utils/utils_spell_check.py index 2ce8385f7141..6adf7f1ef918 100644 --- a/release/scripts/modules/bl_i18n_utils/utils_spell_check.py +++ b/release/scripts/modules/bl_i18n_utils/utils_spell_check.py @@ -163,7 +163,7 @@ class SpellChecker: "rolloff", "runtime", "scanline", - "screencast", "screenshot", "screenshots", + "screenshot", "screenshots", "seekability", "selfcollision", "shadowbuffer", "shadowbuffers", diff --git a/release/scripts/modules/bl_previews_utils/bl_previews_render.py b/release/scripts/modules/bl_previews_utils/bl_previews_render.py index 32266e972bb4..4159121cd907 100644 --- a/release/scripts/modules/bl_previews_utils/bl_previews_render.py +++ b/release/scripts/modules/bl_previews_utils/bl_previews_render.py @@ -442,7 +442,7 @@ def preview_render_do(render_context, item_container, item_name, objects, offset if not has_camera: # We had to add a temp camera, now we need to place it to see interesting objects! objects = tuple((ob.name, ob.library.filepath if ob.library else None) for ob in scene.objects - if (not ob.hide_render) and (ob.type in OBJECT_TYPES_RENDER)) + if (not ob.hide_render) and (ob.type in OBJECT_TYPES_RENDER)) preview_render_do(render_context, 'scenes', scene.name, objects) diff --git a/release/scripts/modules/blend_render_info.py b/release/scripts/modules/blend_render_info.py index 30c3ed2388b7..3b4fb2550054 100755 --- a/release/scripts/modules/blend_render_info.py +++ b/release/scripts/modules/blend_render_info.py @@ -98,5 +98,6 @@ def main(): for value in read_blend_rend_chunk(arg): print("%d %d %s" % value) + if __name__ == '__main__': main() diff --git a/release/scripts/modules/bpy/ops.py b/release/scripts/modules/bpy/ops.py index d3d9255123b4..7c5c76ffdbe2 100644 --- a/release/scripts/modules/bpy/ops.py +++ b/release/scripts/modules/bpy/ops.py @@ -225,4 +225,5 @@ def __str__(self): # used for print(...) return ("" % (self._module, self._func, id(self))) + ops_fake_module = BPyOps() diff --git a/release/scripts/modules/bpy/path.py b/release/scripts/modules/bpy/path.py index a88e60d00220..6af78bbb4c07 100644 --- a/release/scripts/modules/bpy/path.py +++ b/release/scripts/modules/bpy/path.py @@ -183,6 +183,8 @@ def maketrans_init(): trans = maketrans_init() return name.translate(trans) + + clean_name._trans_cache = {} @@ -223,6 +225,7 @@ def display_name(name): name = _clean_utf8(name) return name + def display_name_to_filepath(name): """ Performs the reverse of display_name using literal versions of characters diff --git a/release/scripts/modules/bpy/utils/__init__.py b/release/scripts/modules/bpy/utils/__init__.py index c3175f93f4e1..5e5a35b95187 100644 --- a/release/scripts/modules/bpy/utils/__init__.py +++ b/release/scripts/modules/bpy/utils/__init__.py @@ -488,11 +488,11 @@ def smpte_from_frame(frame, fps=None, fps_base=None): return ( "%s%02d:%02d:%02d:%02d" % ( - sign, - int(frame / (3600 * fps)), # HH - int((frame / (60 * fps)) % 60), # MM - int((frame / fps) % 60), # SS - int(frame % fps), # FF + sign, + int(frame / (3600 * fps)), # HH + int((frame / (60 * fps)) % 60), # MM + int((frame / fps) % 60), # SS + int(frame % fps), # FF )) @@ -773,6 +773,7 @@ def _blender_default_map(): del _sys.modules["rna_manual_reference"] return ret + # hooks for doc lookups _manual_map = [_blender_default_map] diff --git a/release/scripts/modules/bpy/utils/previews.py b/release/scripts/modules/bpy/utils/previews.py index 568116b027cc..a3baf8f878c8 100644 --- a/release/scripts/modules/bpy/utils/previews.py +++ b/release/scripts/modules/bpy/utils/previews.py @@ -37,7 +37,7 @@ "new", "remove", "ImagePreviewCollection", - ) +) import _bpy _utils_previews = _bpy._utils_previews @@ -76,9 +76,9 @@ def __del__(self): return raise ResourceWarning( - "<%s id=%s[%d]>: left open, remove with " - "'bpy.utils.previews.remove()'" % - (self.__class__.__name__, self._uuid, len(self))) + f"{self!r}: left open, remove with " + "'bpy.utils.previews.remove()'" + ) self.close() def _gen_key(self, name): @@ -86,17 +86,17 @@ def _gen_key(self, name): def new(self, name): if name in self: - raise KeyError("key %r already exists" % name) + raise KeyError(f"key {name!r} already exists") p = self[name] = _utils_previews.new( - self._gen_key(name)) + self._gen_key(name)) return p new.__doc__ = _utils_previews.new.__doc__ def load(self, name, path, path_type, force_reload=False): if name in self: - raise KeyError("key %r already exists" % name) + raise KeyError("key {name!r} already exists") p = self[name] = _utils_previews.load( - self._gen_key(name), path, path_type, force_reload) + self._gen_key(name), path, path_type, force_reload) return p load.__doc__ = _utils_previews.load.__doc__ @@ -116,11 +116,7 @@ def __delitem__(self, key): super().__delitem__(key) def __repr__(self): - return "<%s id=%s[%d], %s>" % ( - self.__class__.__name__, - self._uuid, - len(self), - super().__repr__()) + return f"<{self.__class__.__name__:s} id={self._uuid:s}[{len(self):d}], {super()!r}>" def new(): @@ -149,5 +145,6 @@ def remove(pcoll): def exit_clear_warning(): del ImagePreviewCollection.__del__ + atexit.register(exit_clear_warning) del atexit, exit_clear_warning diff --git a/release/scripts/modules/bpy_extras/__init__.py b/release/scripts/modules/bpy_extras/__init__.py index c8d12070de8f..d2578e1812a6 100644 --- a/release/scripts/modules/bpy_extras/__init__.py +++ b/release/scripts/modules/bpy_extras/__init__.py @@ -30,4 +30,4 @@ "keyconfig_utils", "mesh_utils", "view3d_utils", - ) +) diff --git a/release/scripts/modules/bpy_extras/anim_utils.py b/release/scripts/modules/bpy_extras/anim_utils.py index 75d2065a3d1f..7216add2c2c2 100644 --- a/release/scripts/modules/bpy_extras/anim_utils.py +++ b/release/scripts/modules/bpy_extras/anim_utils.py @@ -174,7 +174,7 @@ def pose_frame_info(obj): # Bendy Bones if pbone.bone.bbone_segments > 1: - bbones[name] = {bb_prop : getattr(pbone, bb_prop) for bb_prop in BBONE_PROPS} + bbones[name] = {bb_prop: getattr(pbone, bb_prop) for bb_prop in BBONE_PROPS} return matrix, bbones if do_parents_clear: diff --git a/release/scripts/modules/bpy_extras/image_utils.py b/release/scripts/modules/bpy_extras/image_utils.py index f772aab2b141..49fce7d27c7a 100644 --- a/release/scripts/modules/bpy_extras/image_utils.py +++ b/release/scripts/modules/bpy_extras/image_utils.py @@ -20,7 +20,7 @@ __all__ = ( "load_image", - ) +) # limited replacement for BPyImage.comprehensiveImageLoad diff --git a/release/scripts/modules/bpy_extras/io_utils.py b/release/scripts/modules/bpy_extras/io_utils.py index 8a516f12b172..e2c2e4c9b936 100644 --- a/release/scripts/modules/bpy_extras/io_utils.py +++ b/release/scripts/modules/bpy_extras/io_utils.py @@ -32,7 +32,7 @@ "path_reference_copy", "path_reference_mode", "unique_name" - ) +) import bpy from bpy.props import ( @@ -53,23 +53,23 @@ def _check_axis_conversion(op): class ExportHelper: filepath = StringProperty( - name="File Path", - description="Filepath used for exporting the file", - maxlen=1024, - subtype='FILE_PATH', - ) + name="File Path", + description="Filepath used for exporting the file", + maxlen=1024, + subtype='FILE_PATH', + ) check_existing = BoolProperty( - name="Check Existing", - description="Check and warn on overwriting existing files", - default=True, - options={'HIDDEN'}, - ) + name="Check Existing", + description="Check and warn on overwriting existing files", + default=True, + options={'HIDDEN'}, + ) # needed for mix-ins order = [ "filepath", "check_existing", - ] + ] # subclasses can override with decorator # True == use ext, False == no ext, None == do nothing. @@ -113,16 +113,16 @@ def check(self, context): class ImportHelper: filepath = StringProperty( - name="File Path", - description="Filepath used for importing the file", - maxlen=1024, - subtype='FILE_PATH', - ) + name="File Path", + description="Filepath used for importing the file", + maxlen=1024, + subtype='FILE_PATH', + ) # needed for mix-ins order = [ "filepath", - ] + ] def invoke(self, context, event): context.window_manager.fileselect_add(self) @@ -138,43 +138,45 @@ def orientation_helper_factory(name, axis_forward='Y', axis_up='Z'): def _update_axis_forward(self, context): if self.axis_forward[-1] == self.axis_up[-1]: self.axis_up = (self.axis_up[0:-1] + - 'XYZ'[('XYZ'.index(self.axis_up[-1]) + 1) % 3]) + 'XYZ'[('XYZ'.index(self.axis_up[-1]) + 1) % 3]) members['axis_forward'] = EnumProperty( - name="Forward", - items=(('X', "X Forward", ""), - ('Y', "Y Forward", ""), - ('Z', "Z Forward", ""), - ('-X', "-X Forward", ""), - ('-Y', "-Y Forward", ""), - ('-Z', "-Z Forward", ""), - ), - default=axis_forward, - update=_update_axis_forward, - ) + name="Forward", + items=( + ('X', "X Forward", ""), + ('Y', "Y Forward", ""), + ('Z', "Z Forward", ""), + ('-X', "-X Forward", ""), + ('-Y', "-Y Forward", ""), + ('-Z', "-Z Forward", ""), + ), + default=axis_forward, + update=_update_axis_forward, + ) def _update_axis_up(self, context): if self.axis_up[-1] == self.axis_forward[-1]: self.axis_forward = (self.axis_forward[0:-1] + - 'XYZ'[('XYZ'.index(self.axis_forward[-1]) + 1) % 3]) + 'XYZ'[('XYZ'.index(self.axis_forward[-1]) + 1) % 3]) members['axis_up'] = EnumProperty( - name="Up", - items=(('X', "X Up", ""), - ('Y', "Y Up", ""), - ('Z', "Z Up", ""), - ('-X', "-X Up", ""), - ('-Y', "-Y Up", ""), - ('-Z', "-Z Up", ""), - ), - default=axis_up, - update=_update_axis_up, - ) + name="Up", + items=( + ('X', "X Up", ""), + ('Y', "Y Up", ""), + ('Z', "Z Up", ""), + ('-X', "-X Up", ""), + ('-Y', "-Y Up", ""), + ('-Z', "-Z Up", ""), + ), + default=axis_up, + update=_update_axis_up, + ) members["order"] = [ "axis_forward", "axis_up", - ] + ] return type(name, (object,), members) @@ -205,7 +207,7 @@ def _update_axis_up(self, context): ((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0)), ((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), - ) +) # store args as a single int # (X Y Z -X -Y -Z) --> (0, 1, 2, 3, 4, 5) @@ -282,7 +284,7 @@ def _update_axis_up(self, context): {0x408, 0x810, 0xA20, 0x228, 0x081, 0x891, 0x699, 0x2A9, 0x102, 0x50A, 0x71A, 0xB22, 0x4CB, 0x8D3, 0xAE3, 0x2EB, 0x144, 0x954, 0x75C, 0x36C, 0x045, 0x44D, 0x65D, 0xA65}, - ) +) _axis_convert_num = {'X': 0, 'Y': 1, 'Z': 2, '-X': 3, '-Y': 4, '-Z': 5} @@ -303,11 +305,11 @@ def axis_conversion(from_forward='Y', from_up='Z', to_forward='Y', to_up='Z'): "can't use up/forward on the same axis") value = reduce(int.__or__, (_axis_convert_num[a] << (i * 3) - for i, a in enumerate((from_forward, - from_up, - to_forward, - to_up, - )))) + for i, a in enumerate((from_forward, + from_up, + to_forward, + to_up, + )))) for i, axis_lut in enumerate(_axis_convert_lut): if value in axis_lut: @@ -392,20 +394,21 @@ def unpack_face_list(list_of_tuples): path_reference_mode = EnumProperty( - name="Path Mode", - description="Method used to reference paths", - items=(('AUTO', "Auto", "Use Relative paths with subdirectories only"), - ('ABSOLUTE', "Absolute", "Always write absolute paths"), - ('RELATIVE', "Relative", "Always write relative paths " - "(where possible)"), - ('MATCH', "Match", "Match Absolute/Relative " - "setting with input path"), - ('STRIP', "Strip Path", "Filename only"), - ('COPY', "Copy", "Copy the file to the destination path " - "(or subdirectory)"), - ), - default='AUTO', - ) + name="Path Mode", + description="Method used to reference paths", + items=( + ('AUTO', "Auto", "Use Relative paths with subdirectories only"), + ('ABSOLUTE', "Absolute", "Always write absolute paths"), + ('RELATIVE', "Relative", "Always write relative paths " + "(where possible)"), + ('MATCH', "Match", "Match Absolute/Relative " + "setting with input path"), + ('STRIP', "Strip Path", "Filename only"), + ('COPY', "Copy", "Copy the file to the destination path " + "(or subdirectory)"), + ), + default='AUTO', +) def path_reference(filepath, diff --git a/release/scripts/modules/bpy_extras/keyconfig_utils.py b/release/scripts/modules/bpy_extras/keyconfig_utils.py index 9d206afb2c5b..0ff6595eca9c 100644 --- a/release/scripts/modules/bpy_extras/keyconfig_utils.py +++ b/release/scripts/modules/bpy_extras/keyconfig_utils.py @@ -177,8 +177,8 @@ def addon_keymap_register(wm, keymaps_description): for km_info, km_items in keymaps_description: km_name, km_sptype, km_regtype, km_ismodal = km_info kmap = [k for k in kconf.keymaps - if k.name == km_name and k.region_type == km_regtype and - k.space_type == km_sptype and k.is_modal == km_ismodal] + if k.name == km_name and k.region_type == km_regtype and + k.space_type == km_sptype and k.is_modal == km_ismodal] if kmap: kmap = kmap[0] else: @@ -202,8 +202,8 @@ def addon_keymap_unregister(wm, keymaps_description): for km_info, km_items in keymaps_description: km_name, km_sptype, km_regtype, km_ismodal = km_info kmaps = (k for k in kconf.keymaps - if k.name == km_name and k.region_type == km_regtype and - k.space_type == km_sptype and k.is_modal == km_ismodal) + if k.name == km_name and k.region_type == km_regtype and + k.space_type == km_sptype and k.is_modal == km_ismodal) for kmap in kmaps: for kmi_kwargs, props in km_items: idname = kmi_kwargs["idname"] @@ -240,9 +240,9 @@ def _export_properties(prefix, properties, kmi_id, lines=None): lines = [] def string_value(value): - if isinstance(value, str) or isinstance(value, bool) or isinstance(value, float) or isinstance(value, int): + if isinstance(value, (str, bool, float, int)): return repr(value) - elif getattr(value, '__len__', False): + elif hasattr(value, "__len__"): return repr(list(value)) print("Export key configuration: can't write ", value) @@ -296,8 +296,10 @@ def _kmistr(kmi, is_modal): return "".join(s) -def keyconfig_export(wm, kc, filepath): - +def keyconfig_export( + wm, kc, filepath, *, + all_keymaps=False, +): f = open(filepath, "w") f.write("import bpy\n") @@ -327,7 +329,7 @@ class FakeKeyConfig: keymaps = [] edited_kc = FakeKeyConfig() for km in wm.keyconfigs.user.keymaps: - if km.is_user_modified: + if all_keymaps or km.is_user_modified: edited_kc.keymaps.append(km) # merge edited keymaps with non-default keyconfig, if it exists if kc != wm.keyconfigs.default: diff --git a/release/scripts/modules/bpy_extras/mesh_utils.py b/release/scripts/modules/bpy_extras/mesh_utils.py index 4293930e8234..43b02e5c8810 100644 --- a/release/scripts/modules/bpy_extras/mesh_utils.py +++ b/release/scripts/modules/bpy_extras/mesh_utils.py @@ -27,7 +27,7 @@ "edge_loops_from_edges", "ngon_tessellate", "face_random_points", - ) +) def mesh_linked_uv_islands(mesh): @@ -286,7 +286,7 @@ def edge_loops_from_edges(mesh, edges=None): ok = True while ok: ok = False - #for i, ed in enumerate(edges): + # for i, ed in enumerate(edges): i = len(edges) while i: i -= 1 @@ -303,7 +303,7 @@ def edge_loops_from_edges(mesh, edges=None): vert_end = line_poly[-1] ok = 1 del edges[i] - #break + # break elif v1 == vert_start: line_poly.insert(0, v2) vert_start = line_poly[0] @@ -315,7 +315,7 @@ def edge_loops_from_edges(mesh, edges=None): vert_start = line_poly[0] ok = 1 del edges[i] - #break + # break line_polys.append(line_poly) return line_polys @@ -481,7 +481,7 @@ def join_seg(s1, s2): ii += len(verts) fill = tessellate_polygon([[v[0] for v in loop] for loop in loop_list]) - #draw_loops(loop_list) + # draw_loops(loop_list) #raise Exception("done loop") # map to original indices fill = [[vert_map[i] for i in reversed(f)] for f in fill] diff --git a/release/scripts/modules/bpy_extras/object_utils.py b/release/scripts/modules/bpy_extras/object_utils.py index 9d9b5df1f9ab..0a48d99b5290 100644 --- a/release/scripts/modules/bpy_extras/object_utils.py +++ b/release/scripts/modules/bpy_extras/object_utils.py @@ -26,7 +26,7 @@ "object_add_grid_scale_apply_operator", "object_image_guess", "world_to_camera_view", - ) +) import bpy @@ -218,24 +218,24 @@ def view_align_update_callback(self, context): self.rotation.zero() view_align = BoolProperty( - name="Align to View", - default=False, - update=view_align_update_callback, - ) + name="Align to View", + default=False, + update=view_align_update_callback, + ) location = FloatVectorProperty( - name="Location", - subtype='TRANSLATION', - ) + name="Location", + subtype='TRANSLATION', + ) rotation = FloatVectorProperty( - name="Rotation", - subtype='EULER', - ) + name="Rotation", + subtype='EULER', + ) layers = BoolVectorProperty( - name="Layers", - size=20, - subtype='LAYER', - options={'HIDDEN', 'SKIP_SAVE'}, - ) + name="Layers", + size=20, + subtype='LAYER', + options={'HIDDEN', 'SKIP_SAVE'}, + ) @classmethod def poll(self, context): diff --git a/release/scripts/modules/bpyml.py b/release/scripts/modules/bpyml.py index f2a735016722..3cdbf848a242 100644 --- a/release/scripts/modules/bpyml.py +++ b/release/scripts/modules/bpyml.py @@ -153,6 +153,7 @@ def _topretty(py_item, indent_ctx, last): return "\n".join(lines) + if __name__ == "__main__": # testing code. diff --git a/release/scripts/modules/console/complete_import.py b/release/scripts/modules/console/complete_import.py index e7218594a86e..b9b7c6cb7798 100644 --- a/release/scripts/modules/console/complete_import.py +++ b/release/scripts/modules/console/complete_import.py @@ -19,12 +19,12 @@ # ##### END GPL LICENSE BLOCK ##### # Original copyright (see docstring): -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2001-2006 Fernando Perez # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. -#***************************************************************************** +# **************************************************************************** # diff --git a/release/scripts/modules/console_python.py b/release/scripts/modules/console_python.py index a740f31c8309..68ff1ed60a78 100644 --- a/release/scripts/modules/console_python.py +++ b/release/scripts/modules/console_python.py @@ -224,6 +224,7 @@ class redirect_stdin(redirect_stdout.__base__): return {'FINISHED'} + execute.hooks = [] diff --git a/release/scripts/modules/console_shell.py b/release/scripts/modules/console_shell.py index 83367e72e673..474e2c6ff819 100644 --- a/release/scripts/modules/console_shell.py +++ b/release/scripts/modules/console_shell.py @@ -40,6 +40,7 @@ def shell_run(text): add_scrollback(output, style) + PROMPT = "$ " @@ -64,7 +65,7 @@ def execute(context, is_interactive): def autocomplete(context): - #~ sc = context.space_data + # sc = context.space_data # TODO return {'CANCELLED'} diff --git a/release/scripts/modules/graphviz_export.py b/release/scripts/modules/graphviz_export.py index 88f8b15a728a..fbe23a05940a 100644 --- a/release/scripts/modules/graphviz_export.py +++ b/release/scripts/modules/graphviz_export.py @@ -140,7 +140,7 @@ def rna_path_as_pbone(rna_path): return None #rna_path_bone = rna_path[:rna_path.index("]") + 1] - #return obj.path_resolve(rna_path_bone) + # return obj.path_resolve(rna_path_bone) bone_name = rna_path.split("[")[1].split("]")[0] return obj.pose.bones[bone_name[1:-1]] @@ -179,6 +179,7 @@ def rna_path_as_pbone(rna_path): print("\nSaved:", filepath) return True + if __name__ == "__main__": import os tmppath = "/tmp/test.dot" diff --git a/release/scripts/modules/keyingsets_utils.py b/release/scripts/modules/keyingsets_utils.py index 7ce5f3e029b6..de8da450125f 100644 --- a/release/scripts/modules/keyingsets_utils.py +++ b/release/scripts/modules/keyingsets_utils.py @@ -36,7 +36,7 @@ "RKS_GEN_rotation", "RKS_GEN_scaling", "RKS_GEN_bendy_bones", - ) +) import bpy @@ -219,6 +219,7 @@ def RKS_GEN_scaling(ksi, context, ks, data): # ------ + # Property identifiers for Bendy Bones bbone_property_ids = ( "bbone_curveinx", @@ -256,4 +257,3 @@ def RKS_GEN_bendy_bones(ksi, context, ks, data): ks.paths.add(id_block, path, group_method='NAMED', group_name=grouping) else: ks.paths.add(id_block, path) - diff --git a/release/scripts/modules/nodeitems_utils.py b/release/scripts/modules/nodeitems_utils.py index 117e35dd0284..699b6ce05288 100644 --- a/release/scripts/modules/nodeitems_utils.py +++ b/release/scripts/modules/nodeitems_utils.py @@ -121,7 +121,7 @@ def draw_node_item(self, context): "category": cat, "poll": cat.poll, "draw": draw_node_item, - }) + }) panel_type = type("NODE_PT_category_" + cat.identifier, (bpy.types.Panel,), { "bl_space_type": 'NODE_EDITOR', "bl_region_type": 'TOOLS', @@ -130,7 +130,7 @@ def draw_node_item(self, context): "category": cat, "poll": cat.poll, "draw": draw_node_item, - }) + }) menu_types.append(menu_type) panel_types.append(panel_type) diff --git a/release/scripts/modules/rna_keymap_ui.py b/release/scripts/modules/rna_keymap_ui.py index aa1aa4925a3b..e151a81913b5 100644 --- a/release/scripts/modules/rna_keymap_ui.py +++ b/release/scripts/modules/rna_keymap_ui.py @@ -25,7 +25,7 @@ "draw_filtered", "draw_hierarchy", "draw_keymaps", - ) +) import bpy @@ -174,7 +174,7 @@ def draw_kmi(display_keymaps, kc, km, kmi, layout, level): sub.prop(kmi, "propvalue", text="") else: # One day... - #~ sub.prop_search(kmi, "idname", bpy.context.window_manager, "operators_all", text="") + # sub.prop_search(kmi, "idname", bpy.context.window_manager, "operators_all", text="") sub.prop(kmi, "idname", text="") if map_type not in {'TEXTINPUT', 'TIMER'}: @@ -207,6 +207,7 @@ def draw_kmi(display_keymaps, kc, km, kmi, layout, level): draw_km(display_keymaps, kc, kmm, None, layout, level + 1) layout.context_pointer_set("keymap", km) + _EVENT_TYPES = set() _EVENT_TYPE_MAP = {} _EVENT_TYPE_MAP_EXTRA = {} @@ -234,10 +235,10 @@ def filter_func(kmi): "RMB": 'RIGHTMOUSE', "LMB": 'LEFTMOUSE', "MMB": 'MIDDLEMOUSE', - }) + }) _EVENT_TYPE_MAP_EXTRA.update({ "%d" % i: "NUMPAD_%d" % i for i in range(10) - }) + }) # done with once off init filter_text_split = filter_text.strip() @@ -251,7 +252,7 @@ def filter_func(kmi): "cmd": "oskey", "oskey": "oskey", "any": "any", - } + } # KeyMapItem like dict, use for comparing against # attr: {states, ...} kmi_test_dict = {} @@ -260,8 +261,8 @@ def filter_func(kmi): kmi_test_type = [] # initialize? - so if a if a kmi has a MOD assigned it wont show up. - #~ for kv in key_mod.values(): - #~ kmi_test_dict[kv] = {False} + # for kv in key_mod.values(): + # kmi_test_dict[kv] = {False} # altname: attr for kk, kv in key_mod.items(): @@ -374,7 +375,7 @@ def draw_keymaps(context, layout): row = subcol.row(align=True) - #~ row.prop_search(wm.keyconfigs, "active", wm, "keyconfigs", text="Key Config") + # row.prop_search(wm.keyconfigs, "active", wm, "keyconfigs", text="Key Config") text = bpy.path.display_name(wm.keyconfigs.active.name) if not text: text = "Blender (default)" @@ -382,8 +383,8 @@ def draw_keymaps(context, layout): row.operator("wm.keyconfig_preset_add", text="", icon='ZOOMIN') row.operator("wm.keyconfig_preset_add", text="", icon='ZOOMOUT').remove_active = True - #~ layout.context_pointer_set("keyconfig", wm.keyconfigs.active) - #~ row.operator("wm.keyconfig_remove", text="", icon='X') + # layout.context_pointer_set("keyconfig", wm.keyconfigs.active) + # row.operator("wm.keyconfig_remove", text="", icon='X') row.separator() rowsub = row.split(align=True, percentage=0.33) # postpone drawing into rowsub, so we can set alert! diff --git a/release/scripts/presets/keyconfig/3dsmax.py b/release/scripts/presets/keyconfig/3dsmax.py index 6d05ff6982c1..e8576cfad9bd 100644 --- a/release/scripts/presets/keyconfig/3dsmax.py +++ b/release/scripts/presets/keyconfig/3dsmax.py @@ -91,7 +91,6 @@ kmi = km.keymap_items.new('screen.screen_full_area', 'DOWN_ARROW', 'PRESS', ctrl=True) kmi = km.keymap_items.new('screen.screen_full_area', 'SPACE', 'PRESS', shift=True) kmi = km.keymap_items.new('screen.screenshot', 'F3', 'PRESS', ctrl=True) -kmi = km.keymap_items.new('screen.screencast', 'F3', 'PRESS', alt=True) kmi = km.keymap_items.new('screen.region_quadview', 'W', 'PRESS', alt=True) kmi = km.keymap_items.new('screen.repeat_history', 'F3', 'PRESS', shift=True) kmi = km.keymap_items.new('screen.repeat_last', 'R', 'PRESS', shift=True) @@ -2449,4 +2448,3 @@ kmi = km.keymap_items.new_modal('SELECT', 'RIGHTMOUSE', 'RELEASE', any=True) kmi = km.keymap_items.new_modal('BEGIN', 'MIDDLEMOUSE', 'PRESS') kmi = km.keymap_items.new_modal('DESELECT', 'MIDDLEMOUSE', 'RELEASE') - diff --git a/release/scripts/presets/keyconfig/maya.py b/release/scripts/presets/keyconfig/maya.py index 53129593a596..855f8d928cd8 100644 --- a/release/scripts/presets/keyconfig/maya.py +++ b/release/scripts/presets/keyconfig/maya.py @@ -89,7 +89,6 @@ kmi.properties.delta = -1 kmi = km.keymap_items.new('screen.screen_full_area', 'SPACE', 'PRESS', shift=True) kmi = km.keymap_items.new('screen.screenshot', 'F3', 'PRESS', ctrl=True) -kmi = km.keymap_items.new('screen.screencast', 'F3', 'PRESS', alt=True) kmi = km.keymap_items.new('screen.region_quadview', 'SPACE', 'PRESS') kmi = km.keymap_items.new('screen.repeat_history', 'F3', 'PRESS') kmi = km.keymap_items.new('screen.repeat_last', 'G', 'PRESS') @@ -1931,4 +1930,3 @@ kmi = km.keymap_items.new('transform.translate', 'W', 'PRESS') kmi = km.keymap_items.new('transform.translate', 'EVT_TWEAK_S', 'ANY') kmi = km.keymap_items.new('transform.resize', 'R', 'PRESS') - diff --git a/release/scripts/startup/bl_operators/__init__.py b/release/scripts/startup/bl_operators/__init__.py index 1e0dbe6925e1..de538634595b 100644 --- a/release/scripts/startup/bl_operators/__init__.py +++ b/release/scripts/startup/bl_operators/__init__.py @@ -48,7 +48,7 @@ "vertexpaint_dirt", "view3d", "wm", - ] +] import bpy diff --git a/release/scripts/startup/bl_operators/add_mesh_torus.py b/release/scripts/startup/bl_operators/add_mesh_torus.py index cbe924dc360b..4af600473d14 100644 --- a/release/scripts/startup/bl_operators/add_mesh_torus.py +++ b/release/scripts/startup/bl_operators/add_mesh_torus.py @@ -135,63 +135,63 @@ def mode_update_callback(self, context): self.abso_minor_rad = self.major_radius - self.minor_radius major_segments = IntProperty( - name="Major Segments", - description="Number of segments for the main ring of the torus", - min=3, max=256, - default=48, - ) + name="Major Segments", + description="Number of segments for the main ring of the torus", + min=3, max=256, + default=48, + ) minor_segments = IntProperty( - name="Minor Segments", - description="Number of segments for the minor ring of the torus", - min=3, max=256, - default=12, - ) + name="Minor Segments", + description="Number of segments for the minor ring of the torus", + min=3, max=256, + default=12, + ) mode = bpy.props.EnumProperty( - name="Torus Dimensions", - items=(("MAJOR_MINOR", "Major/Minor", - "Use the major/minor radii for torus dimensions"), - ("EXT_INT", "Exterior/Interior", - "Use the exterior/interior radii for torus dimensions")), - update=mode_update_callback, - ) + name="Torus Dimensions", + items=(("MAJOR_MINOR", "Major/Minor", + "Use the major/minor radii for torus dimensions"), + ("EXT_INT", "Exterior/Interior", + "Use the exterior/interior radii for torus dimensions")), + update=mode_update_callback, + ) major_radius = FloatProperty( - name="Major Radius", - description=("Radius from the origin to the " - "center of the cross sections"), - min=0.01, max=100.0, - default=1.0, - subtype='DISTANCE', - unit='LENGTH', - ) + name="Major Radius", + description=("Radius from the origin to the " + "center of the cross sections"), + min=0.01, max=100.0, + default=1.0, + subtype='DISTANCE', + unit='LENGTH', + ) minor_radius = FloatProperty( - name="Minor Radius", - description="Radius of the torus' cross section", - min=0.01, max=100.0, - default=0.25, - subtype='DISTANCE', - unit='LENGTH', - ) + name="Minor Radius", + description="Radius of the torus' cross section", + min=0.01, max=100.0, + default=0.25, + subtype='DISTANCE', + unit='LENGTH', + ) abso_major_rad = FloatProperty( - name="Exterior Radius", - description="Total Exterior Radius of the torus", - min=0.01, max=100.0, - default=1.25, - subtype='DISTANCE', - unit='LENGTH', - ) + name="Exterior Radius", + description="Total Exterior Radius of the torus", + min=0.01, max=100.0, + default=1.25, + subtype='DISTANCE', + unit='LENGTH', + ) abso_minor_rad = FloatProperty( - name="Interior Radius", - description="Total Interior Radius of the torus", - min=0.01, max=100.0, - default=0.75, - subtype='DISTANCE', - unit='LENGTH', - ) + name="Interior Radius", + description="Total Interior Radius of the torus", + min=0.01, max=100.0, + default=0.75, + subtype='DISTANCE', + unit='LENGTH', + ) generate_uvs = BoolProperty( - name="Generate UVs", - description="Generate a default UV map", - default=False, - ) + name="Generate UVs", + description="Generate a default UV map", + default=False, + ) def draw(self, context): layout = self.layout diff --git a/release/scripts/startup/bl_operators/anim.py b/release/scripts/startup/bl_operators/anim.py index 0632f9bc3ca9..250c88b90099 100644 --- a/release/scripts/startup/bl_operators/anim.py +++ b/release/scripts/startup/bl_operators/anim.py @@ -41,23 +41,23 @@ class ANIM_OT_keying_set_export(Operator): bl_label = "Export Keying Set..." filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_text = BoolProperty( - name="Filter text", - default=True, - options={'HIDDEN'}, - ) + name="Filter text", + default=True, + options={'HIDDEN'}, + ) filter_python = BoolProperty( - name="Filter python", - default=True, - options={'HIDDEN'}, - ) + name="Filter python", + default=True, + options={'HIDDEN'}, + ) def execute(self, context): if not self.filepath: @@ -204,58 +204,59 @@ class BakeAction(Operator): bl_options = {'REGISTER', 'UNDO'} frame_start = IntProperty( - name="Start Frame", - description="Start frame for baking", - min=0, max=300000, - default=1, - ) + name="Start Frame", + description="Start frame for baking", + min=0, max=300000, + default=1, + ) frame_end = IntProperty( - name="End Frame", - description="End frame for baking", - min=1, max=300000, - default=250, - ) + name="End Frame", + description="End frame for baking", + min=1, max=300000, + default=250, + ) step = IntProperty( - name="Frame Step", - description="Frame Step", - min=1, max=120, - default=1, - ) + name="Frame Step", + description="Frame Step", + min=1, max=120, + default=1, + ) only_selected = BoolProperty( - name="Only Selected Bones", - description="Only key selected bones (Pose baking only)", - default=True, - ) + name="Only Selected Bones", + description="Only key selected bones (Pose baking only)", + default=True, + ) visual_keying = BoolProperty( - name="Visual Keying", - description="Keyframe from the final transformations (with constraints applied)", - default=False, - ) + name="Visual Keying", + description="Keyframe from the final transformations (with constraints applied)", + default=False, + ) clear_constraints = BoolProperty( - name="Clear Constraints", - description="Remove all constraints from keyed object/bones, and do 'visual' keying", - default=False, - ) + name="Clear Constraints", + description="Remove all constraints from keyed object/bones, and do 'visual' keying", + default=False, + ) clear_parents = BoolProperty( - name="Clear Parents", - description="Bake animation onto the object then clear parents (objects only)", - default=False, - ) + name="Clear Parents", + description="Bake animation onto the object then clear parents (objects only)", + default=False, + ) use_current_action = BoolProperty( - name="Overwrite Current Action", - description="Bake animation into current action, instead of creating a new one " - "(useful for baking only part of bones in an armature)", - default=False, - ) + name="Overwrite Current Action", + description="Bake animation into current action, instead of creating a new one " + "(useful for baking only part of bones in an armature)", + default=False, + ) bake_types = EnumProperty( - name="Bake Data", - description="Which data's transformations to bake", - options={'ENUM_FLAG'}, - items=(('POSE', "Pose", "Bake bones transformations"), - ('OBJECT', "Object", "Bake object transformations"), - ), - default={'POSE'}, - ) + name="Bake Data", + description="Which data's transformations to bake", + options={'ENUM_FLAG'}, + items=( + ('POSE', "Pose", "Bake bones transformations"), + ('OBJECT', "Object", "Bake object transformations"), + ), + default={'POSE'}, + ) def execute(self, context): from bpy_extras import anim_utils @@ -296,16 +297,16 @@ def invoke(self, context, event): class ClearUselessActions(Operator): """Mark actions with no F-Curves for deletion after save & reload of """ \ - """file preserving \"action libraries\"""" + """file preserving \"action libraries\"""" bl_idname = "anim.clear_useless_actions" bl_label = "Clear Useless Actions" bl_options = {'REGISTER', 'UNDO'} only_unused = BoolProperty( - name="Only Unused", - description="Only unused (Fake User only) actions get considered", - default=True, - ) + name="Only Unused", + description="Only unused (Fake User only) actions get considered", + default=True, + ) @classmethod def poll(cls, context): @@ -316,8 +317,10 @@ def execute(self, context): for action in bpy.data.actions: # if only user is "fake" user... - if ((self.only_unused is False) or - (action.use_fake_user and action.users == 1)): + if ( + (self.only_unused is False) or + (action.use_fake_user and action.users == 1) + ): # if it has F-Curves, then it's a "action library" # (i.e. walk, wave, jump, etc.) @@ -339,10 +342,10 @@ class UpdateAnimatedTransformConstraint(Operator): bl_options = {'REGISTER', 'UNDO'} use_convert_to_radians = BoolProperty( - name="Convert To Radians", - description="Convert fcurves/drivers affecting rotations to radians (Warning: use this only once!)", - default=True, - ) + name="Convert To Radians", + description="Convert fcurves/drivers affecting rotations to radians (Warning: use this only once!)", + default=True, + ) def execute(self, context): import animsys_refactor diff --git a/release/scripts/startup/bl_operators/bmesh/find_adjacent.py b/release/scripts/startup/bl_operators/bmesh/find_adjacent.py index ff2e09c6bb5b..5d8011249bc1 100644 --- a/release/scripts/startup/bl_operators/bmesh/find_adjacent.py +++ b/release/scripts/startup/bl_operators/bmesh/find_adjacent.py @@ -26,7 +26,7 @@ __all__ = ( "select_prev", "select_next", - ) +) def other_edges_over_face(e): @@ -303,8 +303,9 @@ def sum_set(seq): for fn in (pass_fn, set, sum_set, len): uuid_cmp_test = fn(uuid_cmp) ele_pair_next_uuid_test = [ - (ele, uuid) for (ele, uuid) in ele_pair_next_uuid - if uuid_cmp_test == fn(uuid)] + (ele, uuid) for (ele, uuid) in ele_pair_next_uuid + if uuid_cmp_test == fn(uuid) + ] if len(ele_pair_next_uuid_test) > 1: ele_pair_next_uuid = ele_pair_next_uuid_test elif len(ele_pair_next_uuid_test) == 1: @@ -350,4 +351,3 @@ def select_prev(bm, report): break return True - diff --git a/release/scripts/startup/bl_operators/clip.py b/release/scripts/startup/bl_operators/clip.py index 35b8a08bf217..dda6b2fa5ab7 100644 --- a/release/scripts/startup/bl_operators/clip.py +++ b/release/scripts/startup/bl_operators/clip.py @@ -134,10 +134,10 @@ class CLIP_OT_filter_tracks(bpy.types.Operator): bl_options = {'UNDO', 'REGISTER'} track_threshold = FloatProperty( - name="Track Threshold", - description="Filter Threshold to select problematic tracks", - default=5.0, - ) + name="Track Threshold", + description="Filter Threshold to select problematic tracks", + default=5.0, + ) @staticmethod def _filter_values(context, threshold): @@ -165,9 +165,10 @@ def marker_velocity(clip_size, track, frame): # Find tracks with markers in both this frame and the previous one. relevant_tracks = [ - track for track in clip.tracking.tracks - if (track.markers.find_frame(frame) and - track.markers.find_frame(frame - 1))] + track for track in clip.tracking.tracks + if (track.markers.find_frame(frame) and + track.markers.find_frame(frame - 1)) + ] if not relevant_tracks: continue @@ -399,7 +400,7 @@ def execute(self, context): class CLIP_OT_set_viewport_background(Operator): """Set current movie clip as a camera background in 3D view-port """ \ - """(works only when a 3D view-port is visible)""" + """(works only when a 3D view-port is visible)""" bl_idname = "clip.set_viewport_background" bl_label = "Set as Background" @@ -1047,13 +1048,13 @@ class CLIP_OT_track_settings_to_track(bpy.types.Operator): "use_green_channel", "use_blue_channel", "weight" - ) + ) _attrs_marker = ( "pattern_corners", "search_min", "search_max", - ) + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/console.py b/release/scripts/startup/bl_operators/console.py index 0025967c97c4..2d32f84805e1 100644 --- a/release/scripts/startup/bl_operators/console.py +++ b/release/scripts/startup/bl_operators/console.py @@ -38,8 +38,8 @@ class ConsoleExec(Operator): bl_label = "Console Execute" interactive = BoolProperty( - options={'SKIP_SAVE'}, - ) + options={'SKIP_SAVE'}, + ) @classmethod def poll(cls, context): @@ -61,7 +61,7 @@ def execute(self, context): class ConsoleAutocomplete(Operator): """Evaluate the namespace up until the cursor and give a list of """ \ - """options or complete the name if there is only one""" + """options or complete the name if there is only one""" bl_idname = "console.autocomplete" bl_label = "Console Autocomplete" @@ -138,9 +138,9 @@ class ConsoleLanguage(Operator): bl_label = "Console Language" language = StringProperty( - name="Language", - maxlen=32, - ) + name="Language", + maxlen=32, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/file.py b/release/scripts/startup/bl_operators/file.py index 4ab8d59f263b..5bb97ff298a3 100644 --- a/release/scripts/startup/bl_operators/file.py +++ b/release/scripts/startup/bl_operators/file.py @@ -38,59 +38,59 @@ class WM_OT_previews_batch_generate(Operator): # ----------- # File props. files = CollectionProperty( - type=bpy.types.OperatorFileListElement, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + type=bpy.types.OperatorFileListElement, + options={'HIDDEN', 'SKIP_SAVE'}, + ) directory = StringProperty( - maxlen=1024, - subtype='FILE_PATH', - options={'HIDDEN', 'SKIP_SAVE'}, - ) + maxlen=1024, + subtype='FILE_PATH', + options={'HIDDEN', 'SKIP_SAVE'}, + ) # Show only images/videos, and directories! filter_blender = BoolProperty( - default=True, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + default=True, + options={'HIDDEN', 'SKIP_SAVE'}, + ) filter_folder = BoolProperty( - default=True, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + default=True, + options={'HIDDEN', 'SKIP_SAVE'}, + ) # ----------- # Own props. use_scenes = BoolProperty( - default=True, - name="Scenes", - description="Generate scenes' previews", - ) + default=True, + name="Scenes", + description="Generate scenes' previews", + ) use_groups = BoolProperty( - default=True, - name="Groups", - description="Generate groups' previews", - ) + default=True, + name="Groups", + description="Generate groups' previews", + ) use_objects = BoolProperty( - default=True, - name="Objects", - description="Generate objects' previews", - ) + default=True, + name="Objects", + description="Generate objects' previews", + ) use_intern_data = BoolProperty( - default=True, - name="Mat/Tex/...", - description="Generate 'internal' previews (materials, textures, images, etc.)", - ) + default=True, + name="Mat/Tex/...", + description="Generate 'internal' previews (materials, textures, images, etc.)", + ) use_trusted = BoolProperty( - default=False, - name="Trusted Blend Files", - description="Enable python evaluation for selected files", - ) + default=False, + name="Trusted Blend Files", + description="Enable python evaluation for selected files", + ) use_backups = BoolProperty( - default=True, - name="Save Backups", - description="Keep a backup (.blend1) version of the files when saving with generated previews", - ) + default=True, + name="Save Backups", + description="Keep a backup (.blend1) version of the files when saving with generated previews", + ) def invoke(self, context, event): context.window_manager.fileselect_add(self) @@ -148,58 +148,58 @@ class WM_OT_previews_batch_clear(Operator): # ----------- # File props. files = CollectionProperty( - type=bpy.types.OperatorFileListElement, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + type=bpy.types.OperatorFileListElement, + options={'HIDDEN', 'SKIP_SAVE'}, + ) directory = StringProperty( - maxlen=1024, - subtype='FILE_PATH', - options={'HIDDEN', 'SKIP_SAVE'}, - ) + maxlen=1024, + subtype='FILE_PATH', + options={'HIDDEN', 'SKIP_SAVE'}, + ) # Show only images/videos, and directories! filter_blender = BoolProperty( - default=True, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + default=True, + options={'HIDDEN', 'SKIP_SAVE'}, + ) filter_folder = BoolProperty( - default=True, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + default=True, + options={'HIDDEN', 'SKIP_SAVE'}, + ) # ----------- # Own props. use_scenes = BoolProperty( - default=True, - name="Scenes", - description="Clear scenes' previews", - ) + default=True, + name="Scenes", + description="Clear scenes' previews", + ) use_groups = BoolProperty(default=True, - name="Groups", - description="Clear groups' previews", - ) + name="Groups", + description="Clear groups' previews", + ) use_objects = BoolProperty( - default=True, - name="Objects", - description="Clear objects' previews", - ) + default=True, + name="Objects", + description="Clear objects' previews", + ) use_intern_data = BoolProperty( - default=True, - name="Mat/Tex/...", - description="Clear 'internal' previews (materials, textures, images, etc.)", - ) + default=True, + name="Mat/Tex/...", + description="Clear 'internal' previews (materials, textures, images, etc.)", + ) use_trusted = BoolProperty( - default=False, - name="Trusted Blend Files", - description="Enable python evaluation for selected files", - ) + default=False, + name="Trusted Blend Files", + description="Enable python evaluation for selected files", + ) use_backups = BoolProperty( - default=True, - name="Save Backups", - description="Keep a backup (.blend1) version of the files when saving with cleared previews", - ) + default=True, + name="Save Backups", + description="Keep a backup (.blend1) version of the files when saving with cleared previews", + ) def invoke(self, context, event): context.window_manager.fileselect_add(self) diff --git a/release/scripts/startup/bl_operators/freestyle.py b/release/scripts/startup/bl_operators/freestyle.py index f5da7d45256b..6ee840ffc75a 100644 --- a/release/scripts/startup/bl_operators/freestyle.py +++ b/release/scripts/startup/bl_operators/freestyle.py @@ -35,15 +35,15 @@ class SCENE_OT_freestyle_fill_range_by_selection(bpy.types.Operator): bl_options = {'INTERNAL'} type = EnumProperty( - name="Type", description="Type of the modifier to work on", - items=(("COLOR", "Color", "Color modifier type"), - ("ALPHA", "Alpha", "Alpha modifier type"), - ("THICKNESS", "Thickness", "Thickness modifier type")), - ) + name="Type", description="Type of the modifier to work on", + items=(("COLOR", "Color", "Color modifier type"), + ("ALPHA", "Alpha", "Alpha modifier type"), + ("THICKNESS", "Thickness", "Thickness modifier type")), + ) name = StringProperty( - name="Name", - description="Name of the modifier to work on", - ) + name="Name", + description="Name of the modifier to work on", + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/image.py b/release/scripts/startup/bl_operators/image.py index c2ca271de667..5c5ca329cda9 100644 --- a/release/scripts/startup/bl_operators/image.py +++ b/release/scripts/startup/bl_operators/image.py @@ -30,8 +30,8 @@ class EditExternally(Operator): bl_options = {'REGISTER'} filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) @staticmethod def _editor_guess(context): diff --git a/release/scripts/startup/bl_operators/mesh.py b/release/scripts/startup/bl_operators/mesh.py index 467c3df31586..7fb1877d191c 100644 --- a/release/scripts/startup/bl_operators/mesh.py +++ b/release/scripts/startup/bl_operators/mesh.py @@ -34,18 +34,20 @@ class MeshMirrorUV(Operator): bl_options = {'REGISTER', 'UNDO'} direction = EnumProperty( - name="Axis Direction", - items=(('POSITIVE', "Positive", ""), - ('NEGATIVE', "Negative", "")), - ) + name="Axis Direction", + items=( + ('POSITIVE', "Positive", ""), + ('NEGATIVE', "Negative", ""), + ), + ) precision = IntProperty( - name="Precision", - description=("Tolerance for finding vertex duplicates"), - min=1, max=16, - soft_min=1, soft_max=16, - default=3, - ) + name="Precision", + description=("Tolerance for finding vertex duplicates"), + min=1, max=16, + soft_min=1, soft_max=16, + default=3, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/node.py b/release/scripts/startup/bl_operators/node.py index 40876e2b0697..bb8f991e526c 100644 --- a/release/scripts/startup/bl_operators/node.py +++ b/release/scripts/startup/bl_operators/node.py @@ -35,31 +35,31 @@ class NodeSetting(PropertyGroup): value = StringProperty( - name="Value", - description="Python expression to be evaluated " - "as the initial node setting", - default="", - ) + name="Value", + description="Python expression to be evaluated " + "as the initial node setting", + default="", + ) # Base class for node 'Add' operators class NodeAddOperator: type = StringProperty( - name="Node Type", - description="Node type", - ) + name="Node Type", + description="Node type", + ) use_transform = BoolProperty( - name="Use Transform", - description="Start transform operator after inserting the node", - default=False, - ) + name="Use Transform", + description="Start transform operator after inserting the node", + default=False, + ) settings = CollectionProperty( - name="Settings", - description="Settings to be applied on the newly created node", - type=NodeSetting, - options={'SKIP_SAVE'}, - ) + name="Settings", + description="Settings to be applied on the newly created node", + type=NodeSetting, + options={'SKIP_SAVE'}, + ) @staticmethod def store_mouse_cursor(context, event): @@ -70,7 +70,7 @@ def store_mouse_cursor(context, event): if context.region.type == 'WINDOW': # convert mouse position to the View2D for later node placement space.cursor_location_from_region( - event.mouse_region_x, event.mouse_region_y) + event.mouse_region_x, event.mouse_region_y) else: space.cursor_location = tree.view_center @@ -99,8 +99,8 @@ def create_node(self, context, node_type=None): setattr(node, setting.name, value) except AttributeError as e: self.report( - {'ERROR_INVALID_INPUT'}, - "Node has no attribute " + setting.name) + {'ERROR_INVALID_INPUT'}, + "Node has no attribute " + setting.name) print(str(e)) # Continue despite invalid attribute @@ -153,9 +153,9 @@ class NODE_OT_add_and_link_node(NodeAddOperator, Operator): bl_options = {'REGISTER', 'UNDO'} link_socket_index = IntProperty( - name="Link Socket Index", - description="Index of the socket to link", - ) + name="Link Socket Index", + description="Index of the socket to link", + ) def execute(self, context): space = context.space_data @@ -195,11 +195,11 @@ def node_enum_items(self, context): nodetype = getattr(bpy.types, item.nodetype, None) if nodetype: enum_items.append( - (str(index), - item.label, - nodetype.bl_rna.description, - index, - )) + (str(index), + item.label, + nodetype.bl_rna.description, + index, + )) return enum_items # Look up the item based on index @@ -211,10 +211,10 @@ def find_node_item(self, context): return None node_item = EnumProperty( - name="Node Type", - description="Node type", - items=node_enum_items, - ) + name="Node Type", + description="Node type", + items=node_enum_items, + ) def execute(self, context): item = self.find_node_item(context) @@ -233,7 +233,7 @@ def execute(self, context): if self.use_transform: bpy.ops.node.translate_attach_remove_on_cancel( - 'INVOKE_DEFAULT') + 'INVOKE_DEFAULT') return {'FINISHED'} else: diff --git a/release/scripts/startup/bl_operators/object.py b/release/scripts/startup/bl_operators/object.py index 307764205e6d..91e5859d2c0d 100644 --- a/release/scripts/startup/bl_operators/object.py +++ b/release/scripts/startup/bl_operators/object.py @@ -36,22 +36,22 @@ class SelectPattern(Operator): bl_options = {'REGISTER', 'UNDO'} pattern = StringProperty( - name="Pattern", - description="Name filter using '*', '?' and " - "'[abc]' unix style wildcards", - maxlen=64, - default="*", - ) + name="Pattern", + description="Name filter using '*', '?' and " + "'[abc]' unix style wildcards", + maxlen=64, + default="*", + ) case_sensitive = BoolProperty( - name="Case Sensitive", - description="Do a case sensitive compare", - default=False, - ) + name="Case Sensitive", + description="Do a case sensitive compare", + default=False, + ) extend = BoolProperty( - name="Extend", - description="Extend the existing selection", - default=True, - ) + name="Extend", + description="Extend the existing selection", + default=True, + ) def execute(self, context): @@ -114,10 +114,10 @@ class SelectCamera(Operator): bl_options = {'REGISTER', 'UNDO'} extend = BoolProperty( - name="Extend", - description="Extend the selection", - default=False - ) + name="Extend", + description="Extend the selection", + default=False + ) def execute(self, context): scene = context.scene @@ -144,24 +144,24 @@ def execute(self, context): class SelectHierarchy(Operator): """Select object relative to the active object's position """ \ - """in the hierarchy""" + """in the hierarchy""" bl_idname = "object.select_hierarchy" bl_label = "Select Hierarchy" bl_options = {'REGISTER', 'UNDO'} direction = EnumProperty( - items=(('PARENT', "Parent", ""), - ('CHILD', "Child", ""), - ), - name="Direction", - description="Direction to select in the hierarchy", - default='PARENT') + items=(('PARENT', "Parent", ""), + ('CHILD', "Child", ""), + ), + name="Direction", + description="Direction to select in the hierarchy", + default='PARENT') extend = BoolProperty( - name="Extend", - description="Extend the existing selection", - default=False, - ) + name="Extend", + description="Extend the existing selection", + default=False, + ) @classmethod def poll(cls, context): @@ -218,18 +218,18 @@ class SubdivisionSet(Operator): bl_options = {'REGISTER', 'UNDO'} level = IntProperty( - name="Level", - min=-100, max=100, - soft_min=-6, soft_max=6, - default=1, - ) + name="Level", + min=-100, max=100, + soft_min=-6, soft_max=6, + default=1, + ) relative = BoolProperty( - name="Relative", - description=("Apply the subsurf level as an offset " - "relative to the current level"), - default=False, - ) + name="Relative", + description=("Apply the subsurf level as an offset " + "relative to the current level"), + default=False, + ) @classmethod def poll(cls, context): @@ -302,36 +302,36 @@ def set_object_subd(obj): class ShapeTransfer(Operator): """Copy another selected objects active shape to this one by """ \ - """applying the relative offsets""" + """applying the relative offsets""" bl_idname = "object.shape_key_transfer" bl_label = "Transfer Shape Key" bl_options = {'REGISTER', 'UNDO'} mode = EnumProperty( - items=(('OFFSET', - "Offset", - "Apply the relative positional offset", - ), - ('RELATIVE_FACE', - "Relative Face", - "Calculate relative position (using faces)", - ), - ('RELATIVE_EDGE', - "Relative Edge", - "Calculate relative position (using edges)", - ), - ), - name="Transformation Mode", - description="Relative shape positions to the new shape method", - default='OFFSET', - ) + items=(('OFFSET', + "Offset", + "Apply the relative positional offset", + ), + ('RELATIVE_FACE', + "Relative Face", + "Calculate relative position (using faces)", + ), + ('RELATIVE_EDGE', + "Relative Edge", + "Calculate relative position (using edges)", + ), + ), + name="Transformation Mode", + description="Relative shape positions to the new shape method", + default='OFFSET', + ) use_clamp = BoolProperty( - name="Clamp Offset", - description=("Clamp the transformation to the distance each " - "vertex moves in the original shape"), - default=False, - ) + name="Clamp Offset", + description=("Clamp the transformation to the distance each " + "vertex moves in the original shape"), + default=False, + ) def _main(self, ob_act, objects, mode='OFFSET', use_clamp=False): @@ -364,7 +364,7 @@ def ob_add_shape(ob, name): orig_normals = me_nos(me.vertices) # actual mesh vertex location isn't as reliable as the base shape :S - #~ orig_coords = me_cos(me.vertices) + # orig_coords = me_cos(me.vertices) orig_coords = me_cos(me.shape_keys.key_blocks[0].data) for ob_other in objects: @@ -494,7 +494,7 @@ def execute(self, context): class JoinUVs(Operator): """Transfer UV Maps from active to selected objects """ \ - """(needs matching geometry)""" + """(needs matching geometry)""" bl_idname = "object.join_uvs" bl_label = "Transfer UV Maps" bl_options = {'REGISTER', 'UNDO'} @@ -654,7 +654,7 @@ def execute(self, context): class IsolateTypeRender(Operator): """Hide unselected render objects of same type as active """ \ - """by setting the hide render flag""" + """by setting the hide render flag""" bl_idname = "object.isolate_type_render" bl_label = "Restrict Render Unselected" bl_options = {'REGISTER', 'UNDO'} @@ -687,38 +687,27 @@ def execute(self, context): class TransformsToDeltas(Operator): """Convert normal object transforms to delta transforms, """ \ - """any existing delta transforms will be included as well""" + """any existing delta transforms will be included as well""" bl_idname = "object.transforms_to_deltas" bl_label = "Transforms to Deltas" bl_options = {'REGISTER', 'UNDO'} mode = EnumProperty( - items=(('ALL', - "All Transforms", - "Transfer location, rotation, and scale transforms", - ), - ('LOC', - "Location", - "Transfer location transforms only", - ), - ('ROT', - "Rotation", - "Transfer rotation transforms only", - ), - ('SCALE', - "Scale", - "Transfer scale transforms only", - ), - ), - name="Mode", - description="Which transforms to transfer", - default='ALL', - ) + items=( + ('ALL', "All Transforms", "Transfer location, rotation, and scale transforms"), + ('LOC', "Location", "Transfer location transforms only"), + ('ROT', "Rotation", "Transfer rotation transforms only"), + ('SCALE', "Scale", "Transfer scale transforms only"), + ), + name="Mode", + description="Which transforms to transfer", + default='ALL', + ) reset_values = BoolProperty( - name="Reset Values", - description=("Clear transform values after transferring to deltas"), - default=True, - ) + name="Reset Values", + description=("Clear transform values after transferring to deltas"), + default=True, + ) @classmethod def poll(cls, context): @@ -784,11 +773,11 @@ def poll(cls, context): def execute(self, context): # map from standard transform paths to "new" transform paths STANDARD_TO_DELTA_PATHS = { - "location" : "delta_location", - "rotation_euler" : "delta_rotation_euler", - "rotation_quaternion" : "delta_rotation_quaternion", - #"rotation_axis_angle" : "delta_rotation_axis_angle", - "scale" : "delta_scale" + "location": "delta_location", + "rotation_euler": "delta_rotation_euler", + "rotation_quaternion": "delta_rotation_quaternion", + # "rotation_axis_angle" : "delta_rotation_axis_angle", + "scale": "delta_scale" } DELTA_PATHS = STANDARD_TO_DELTA_PATHS.values() @@ -848,8 +837,8 @@ def execute(self, context): fcu.data_path = "delta_rotation_quaternion" obj.rotation_quaternion.identity() # XXX: currently not implemented - #~ elif fcu.data_path == "rotation_axis_angle": - #~ fcu.data_path = "delta_rotation_axis_angle" + # ~ elif fcu.data_path == "rotation_axis_angle": + # ~ fcu.data_path = "delta_rotation_axis_angle" elif fcu.data_path == "scale": fcu.data_path = "delta_scale" obj.scale = 1.0, 1.0, 1.0 @@ -956,18 +945,18 @@ class LodGenerate(Operator): bl_options = {'REGISTER', 'UNDO'} count = IntProperty( - name="Count", - default=3, - ) + name="Count", + default=3, + ) target = FloatProperty( - name="Target Size", - min=0.0, max=1.0, - default=0.1, - ) + name="Target Size", + min=0.0, max=1.0, + default=0.1, + ) package = BoolProperty( - name="Package into Group", - default=False, - ) + name="Package into Group", + default=False, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/object_align.py b/release/scripts/startup/bl_operators/object_align.py index 03b0d4f04a24..11c1514e4bfd 100644 --- a/release/scripts/startup/bl_operators/object_align.py +++ b/release/scripts/startup/bl_operators/object_align.py @@ -364,40 +364,45 @@ class AlignObjects(Operator): bl_options = {'REGISTER', 'UNDO'} bb_quality = BoolProperty( - name="High Quality", - description=("Enables high quality calculation of the " - "bounding box for perfect results on complex " - "shape meshes with rotation/scale (Slow)"), - default=True, - ) + name="High Quality", + description=( + "Enables high quality calculation of the " + "bounding box for perfect results on complex " + "shape meshes with rotation/scale (Slow)" + ), + default=True, + ) align_mode = EnumProperty( - name="Align Mode:", - description="Side of object to use for alignment", - items=(('OPT_1', "Negative Sides", ""), - ('OPT_2', "Centers", ""), - ('OPT_3', "Positive Sides", ""), - ), - default='OPT_2', - ) + name="Align Mode:", + description="Side of object to use for alignment", + items=( + ('OPT_1', "Negative Sides", ""), + ('OPT_2', "Centers", ""), + ('OPT_3', "Positive Sides", ""), + ), + default='OPT_2', + ) relative_to = EnumProperty( - name="Relative To:", - description="Reference location to align to", - items=(('OPT_1', "Scene Origin", "Use the Scene Origin as the position for the selected objects to align to"), - ('OPT_2', "3D Cursor", "Use the 3D cursor as the position for the selected objects to align to"), - ('OPT_3', "Selection", "Use the selected objects as the position for the selected objects to align to"), - ('OPT_4', "Active", "Use the active object as the position for the selected objects to align to"), - ), - default='OPT_4', - ) + name="Relative To:", + description="Reference location to align to", + items=( + ('OPT_1', "Scene Origin", "Use the Scene Origin as the position for the selected objects to align to"), + ('OPT_2', "3D Cursor", "Use the 3D cursor as the position for the selected objects to align to"), + ('OPT_3', "Selection", "Use the selected objects as the position for the selected objects to align to"), + ('OPT_4', "Active", "Use the active object as the position for the selected objects to align to"), + ), + default='OPT_4', + ) align_axis = EnumProperty( - name="Align", - description="Align to axis", - items=(('X', "X", ""), - ('Y', "Y", ""), - ('Z', "Z", ""), - ), - options={'ENUM_FLAG'}, - ) + name="Align", + description="Align to axis", + items=( + ('X', "X", ""), + ('Y', "Y", ""), + ('Z', "Z", ""), + ), + options={'ENUM_FLAG'}, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/object_quick_effects.py b/release/scripts/startup/bl_operators/object_quick_effects.py index 4c2a9e76dc78..c2592f13d667 100644 --- a/release/scripts/startup/bl_operators/object_quick_effects.py +++ b/release/scripts/startup/bl_operators/object_quick_effects.py @@ -53,24 +53,26 @@ class QuickFur(Operator): bl_options = {'REGISTER', 'UNDO'} density = EnumProperty( - name="Fur Density", - items=(('LIGHT', "Light", ""), - ('MEDIUM', "Medium", ""), - ('HEAVY', "Heavy", "")), - default='MEDIUM', - ) + name="Fur Density", + items=( + ('LIGHT', "Light", ""), + ('MEDIUM', "Medium", ""), + ('HEAVY', "Heavy", "") + ), + default='MEDIUM', + ) view_percentage = IntProperty( - name="View %", - min=1, max=100, - soft_min=1, soft_max=100, - default=10, - ) + name="View %", + min=1, max=100, + soft_min=1, soft_max=100, + default=10, + ) length = FloatProperty( - name="Length", - min=0.001, max=100, - soft_min=0.01, soft_max=10, - default=0.1, - ) + name="Length", + min=0.001, max=100, + soft_min=0.01, soft_max=10, + default=0.1, + ) def execute(self, context): fake_context = context.copy() @@ -117,49 +119,51 @@ class QuickExplode(Operator): bl_options = {'REGISTER', 'UNDO'} style = EnumProperty( - name="Explode Style", - items=(('EXPLODE', "Explode", ""), - ('BLEND', "Blend", "")), - default='EXPLODE', - ) + name="Explode Style", + items=( + ('EXPLODE', "Explode", ""), + ('BLEND', "Blend", ""), + ), + default='EXPLODE', + ) amount = IntProperty( - name="Amount of pieces", - min=2, max=10000, - soft_min=2, soft_max=10000, - default=100, - ) + name="Amount of pieces", + min=2, max=10000, + soft_min=2, soft_max=10000, + default=100, + ) frame_duration = IntProperty( - name="Duration", - min=1, max=300000, - soft_min=1, soft_max=10000, - default=50, - ) + name="Duration", + min=1, max=300000, + soft_min=1, soft_max=10000, + default=50, + ) frame_start = IntProperty( - name="Start Frame", - min=1, max=300000, - soft_min=1, soft_max=10000, - default=1, - ) + name="Start Frame", + min=1, max=300000, + soft_min=1, soft_max=10000, + default=1, + ) frame_end = IntProperty( - name="End Frame", - min=1, max=300000, - soft_min=1, soft_max=10000, - default=10, - ) + name="End Frame", + min=1, max=300000, + soft_min=1, soft_max=10000, + default=10, + ) velocity = FloatProperty( - name="Outwards Velocity", - min=0, max=300000, - soft_min=0, soft_max=10, - default=1, - ) + name="Outwards Velocity", + min=0, max=300000, + soft_min=0, soft_max=10, + default=1, + ) fade = BoolProperty( - name="Fade", - description="Fade the pieces over time", - default=True, - ) + name="Fade", + description="Fade the pieces over time", + default=True, + ) def execute(self, context): fake_context = context.copy() @@ -303,19 +307,20 @@ class QuickSmoke(Operator): bl_options = {'REGISTER', 'UNDO'} style = EnumProperty( - name="Smoke Style", - items=(('SMOKE', "Smoke", ""), - ('FIRE', "Fire", ""), - ('BOTH', "Smoke + Fire", ""), - ), - default='SMOKE', - ) + name="Smoke Style", + items=( + ('SMOKE', "Smoke", ""), + ('FIRE', "Fire", ""), + ('BOTH', "Smoke + Fire", ""), + ), + default='SMOKE', + ) show_flows = BoolProperty( - name="Render Smoke Objects", - description="Keep the smoke objects visible during rendering", - default=False, - ) + name="Render Smoke Objects", + description="Keep the smoke objects visible during rendering", + default=False, + ) def execute(self, context): if not bpy.app.build_options.mod_smoke: @@ -391,7 +396,7 @@ def execute(self, context): node_principled = nodes.new(type='ShaderNodeVolumePrincipled') node_principled.location = grid_location(4, 1) links.new(node_principled.outputs["Volume"], - node_out.inputs["Volume"]) + node_out.inputs["Volume"]) node_principled.inputs["Density"].default_value = 5.0 @@ -456,29 +461,31 @@ class QuickFluid(Operator): bl_options = {'REGISTER', 'UNDO'} style = EnumProperty( - name="Fluid Style", - items=(('INFLOW', "Inflow", ""), - ('BASIC', "Basic", "")), - default='BASIC', - ) + name="Fluid Style", + items=( + ('INFLOW', "Inflow", ""), + ('BASIC', "Basic", ""), + ), + default='BASIC', + ) initial_velocity = FloatVectorProperty( - name="Initial Velocity", - description="Initial velocity of the fluid", - min=-100.0, max=100.0, - default=(0.0, 0.0, 0.0), - subtype='VELOCITY', - ) + name="Initial Velocity", + description="Initial velocity of the fluid", + min=-100.0, max=100.0, + default=(0.0, 0.0, 0.0), + subtype='VELOCITY', + ) show_flows = BoolProperty( - name="Render Fluid Objects", - description="Keep the fluid objects visible during rendering", - default=False, - ) + name="Render Fluid Objects", + description="Keep the fluid objects visible during rendering", + default=False, + ) start_baking = BoolProperty( - name="Start Fluid Bake", - description=("Start baking the fluid immediately " - "after creating the domain object"), - default=False, - ) + name="Start Fluid Bake", + description=("Start baking the fluid immediately " + "after creating the domain object"), + default=False, + ) def execute(self, context): if not bpy.app.build_options.mod_fluid: diff --git a/release/scripts/startup/bl_operators/object_randomize_transform.py b/release/scripts/startup/bl_operators/object_randomize_transform.py index a91e1a5b0314..dbc9461ad5a5 100644 --- a/release/scripts/startup/bl_operators/object_randomize_transform.py +++ b/release/scripts/startup/bl_operators/object_randomize_transform.py @@ -104,55 +104,55 @@ class RandomizeLocRotSize(Operator): bl_options = {'REGISTER', 'UNDO'} random_seed = IntProperty( - name="Random Seed", - description="Seed value for the random generator", - min=0, - max=10000, - default=0, - ) + name="Random Seed", + description="Seed value for the random generator", + min=0, + max=10000, + default=0, + ) use_delta = BoolProperty( - name="Transform Delta", - description=("Randomize delta transform values " - "instead of regular transform"), - default=False, - ) + name="Transform Delta", + description=("Randomize delta transform values " + "instead of regular transform"), + default=False, + ) use_loc = BoolProperty( - name="Randomize Location", - description="Randomize the location values", - default=True, - ) + name="Randomize Location", + description="Randomize the location values", + default=True, + ) loc = FloatVectorProperty( - name="Location", - description=("Maximum distance the objects " - "can spread over each axis"), - min=-100.0, - max=100.0, - default=(0.0, 0.0, 0.0), - subtype='TRANSLATION', - ) + name="Location", + description=("Maximum distance the objects " + "can spread over each axis"), + min=-100.0, + max=100.0, + default=(0.0, 0.0, 0.0), + subtype='TRANSLATION', + ) use_rot = BoolProperty( - name="Randomize Rotation", - description="Randomize the rotation values", - default=True, - ) + name="Randomize Rotation", + description="Randomize the rotation values", + default=True, + ) rot = FloatVectorProperty( - name="Rotation", - description="Maximum rotation over each axis", - min=-3.141592, # math.pi - max=+3.141592, - default=(0.0, 0.0, 0.0), - subtype='EULER', - ) + name="Rotation", + description="Maximum rotation over each axis", + min=-3.141592, # math.pi + max=+3.141592, + default=(0.0, 0.0, 0.0), + subtype='EULER', + ) use_scale = BoolProperty( - name="Randomize Scale", - description="Randomize the scale values", - default=True, - ) + name="Randomize Scale", + description="Randomize the scale values", + default=True, + ) scale_even = BoolProperty( - name="Scale Even", - description="Use the same scale value for all axis", - default=False, - ) + name="Scale Even", + description="Use the same scale value for all axis", + default=False, + ) '''scale_min = FloatProperty( name="Minimun Scale Factor", @@ -162,13 +162,13 @@ class RandomizeLocRotSize(Operator): )''' scale = FloatVectorProperty( - name="Scale", - description="Maximum scale randomization over each axis", - min=-100.0, - max=100.0, - default=(1.0, 1.0, 1.0), - subtype='TRANSLATION', - ) + name="Scale", + description="Maximum scale randomization over each axis", + min=-100.0, + max=100.0, + default=(1.0, 1.0, 1.0), + subtype='TRANSLATION', + ) def execute(self, context): seed = self.random_seed diff --git a/release/scripts/startup/bl_operators/presets.py b/release/scripts/startup/bl_operators/presets.py index c696c38dac65..8852bca971d6 100644 --- a/release/scripts/startup/bl_operators/presets.py +++ b/release/scripts/startup/bl_operators/presets.py @@ -35,21 +35,21 @@ class AddPresetBase: bl_options = {'REGISTER', 'INTERNAL'} name = StringProperty( - name="Name", - description="Name of the preset, used to make the path name", - maxlen=64, - options={'SKIP_SAVE'}, - ) + name="Name", + description="Name of the preset, used to make the path name", + maxlen=64, + options={'SKIP_SAVE'}, + ) remove_active = BoolProperty( - default=False, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + default=False, + options={'HIDDEN', 'SKIP_SAVE'}, + ) # needed for mix-ins order = [ "name", "remove_active", - ] + ] @staticmethod def as_filename(name): # could reuse for other presets @@ -207,14 +207,14 @@ class ExecutePreset(Operator): bl_label = "Execute a Python Preset" filepath = StringProperty( - subtype='FILE_PATH', - options={'SKIP_SAVE'}, - ) + subtype='FILE_PATH', + options={'SKIP_SAVE'}, + ) menu_idname = StringProperty( - name="Menu ID Name", - description="ID name of the menu this was called from", - options={'SKIP_SAVE'}, - ) + name="Menu ID Name", + description="ID name of the menu this was called from", + options={'SKIP_SAVE'}, + ) def execute(self, context): from os.path import basename, splitext @@ -280,10 +280,10 @@ class AddPresetCamera(AddPresetBase, Operator): preset_subdir = "camera" use_focal_length = BoolProperty( - name="Include Focal Length", - description="Include focal length into the preset", - options={'SKIP_SAVE'}, - ) + name="Include Focal Length", + description="Include focal length into the preset", + options={'SKIP_SAVE'}, + ) @property def preset_values(self): @@ -376,12 +376,12 @@ class AddPresetFluid(AddPresetBase, Operator): preset_defines = [ "fluid = bpy.context.fluid" - ] + ] preset_values = [ "fluid.settings.viscosity_base", "fluid.settings.viscosity_exponent", - ] + ] preset_subdir = "fluid" @@ -413,7 +413,7 @@ class AddPresetHairDynamics(AddPresetBase, Operator): "settings.density_strength", "settings.voxel_cell_size", "settings.pin_stiffness", - ] + ] class AddPresetSunSky(AddPresetBase, Operator): @@ -484,11 +484,11 @@ class AddPresetTrackingCamera(AddPresetBase, Operator): preset_subdir = "tracking_camera" use_focal_length = BoolProperty( - name="Include Focal Length", - description="Include focal length into the preset", - options={'SKIP_SAVE'}, - default=True - ) + name="Include Focal Length", + description="Include focal length into the preset", + options={'SKIP_SAVE'}, + default=True + ) @property def preset_values(self): @@ -609,10 +609,10 @@ class AddPresetOperator(AddPresetBase, Operator): preset_menu = "WM_MT_operator_presets" operator = StringProperty( - name="Operator", - maxlen=64, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + name="Operator", + maxlen=64, + options={'HIDDEN', 'SKIP_SAVE'}, + ) preset_defines = [ "op = bpy.context.active_operator", diff --git a/release/scripts/startup/bl_operators/rigidbody.py b/release/scripts/startup/bl_operators/rigidbody.py index 6792d5256835..8fbc9b29b462 100644 --- a/release/scripts/startup/bl_operators/rigidbody.py +++ b/release/scripts/startup/bl_operators/rigidbody.py @@ -51,7 +51,7 @@ class CopyRigidbodySettings(Operator): "mesh_source", "use_deform", "enabled", - ) + ) @classmethod def poll(cls, context): @@ -93,23 +93,23 @@ class BakeToKeyframes(Operator): bl_options = {'REGISTER', 'UNDO'} frame_start = IntProperty( - name="Start Frame", - description="Start frame for baking", - min=0, max=300000, - default=1, - ) + name="Start Frame", + description="Start frame for baking", + min=0, max=300000, + default=1, + ) frame_end = IntProperty( - name="End Frame", - description="End frame for baking", - min=1, max=300000, - default=250, - ) + name="End Frame", + description="End frame for baking", + min=1, max=300000, + default=250, + ) step = IntProperty( - name="Frame Step", - description="Frame Step", - min=1, max=120, - default=1, - ) + name="Frame Step", + description="Frame Step", + min=1, max=120, + default=1, + ) @classmethod def poll(cls, context): @@ -217,28 +217,34 @@ class ConnectRigidBodies(Operator): bl_options = {'REGISTER', 'UNDO'} con_type = EnumProperty( - name="Type", - description="Type of generated constraint", - # XXX Would be nice to get icons too, but currently not possible ;) - items=tuple((e.identifier, e.name, e.description, e. value) - for e in bpy.types.RigidBodyConstraint.bl_rna.properties["type"].enum_items), - default='FIXED', - ) + name="Type", + description="Type of generated constraint", + # XXX Would be nice to get icons too, but currently not possible ;) + items=tuple( + (e.identifier, e.name, e.description, e. value) + for e in bpy.types.RigidBodyConstraint.bl_rna.properties["type"].enum_items + ), + default='FIXED', + ) pivot_type = EnumProperty( - name="Location", - description="Constraint pivot location", - items=(('CENTER', "Center", "Pivot location is between the constrained rigid bodies"), - ('ACTIVE', "Active", "Pivot location is at the active object position"), - ('SELECTED', "Selected", "Pivot location is at the selected object position")), - default='CENTER', - ) + name="Location", + description="Constraint pivot location", + items=( + ('CENTER', "Center", "Pivot location is between the constrained rigid bodies"), + ('ACTIVE', "Active", "Pivot location is at the active object position"), + ('SELECTED', "Selected", "Pivot location is at the selected object position"), + ), + default='CENTER', + ) connection_pattern = EnumProperty( - name="Connection Pattern", - description="Pattern used to connect objects", - items=(('SELECTED_TO_ACTIVE', "Selected to Active", "Connect selected objects to the active object"), - ('CHAIN_DISTANCE', "Chain by Distance", "Connect objects as a chain based on distance, starting at the active object")), - default='SELECTED_TO_ACTIVE', - ) + name="Connection Pattern", + description="Pattern used to connect objects", + items=( + ('SELECTED_TO_ACTIVE', "Selected to Active", "Connect selected objects to the active object"), + ('CHAIN_DISTANCE', "Chain by Distance", "Connect objects as a chain based on distance, starting at the active object"), + ), + default='SELECTED_TO_ACTIVE', + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/screen_play_rendered_anim.py b/release/scripts/startup/bl_operators/screen_play_rendered_anim.py index e32c1ac0f816..27c8487eaa91 100644 --- a/release/scripts/startup/bl_operators/screen_play_rendered_anim.py +++ b/release/scripts/startup/bl_operators/screen_play_rendered_anim.py @@ -75,10 +75,12 @@ class PlayRenderedAnim(Operator): def execute(self, context): import subprocess + from shlex import quote scene = context.scene rd = scene.render prefs = context.user_preferences + fps_final = rd.fps / rd.fps_base preset = prefs.filepaths.animation_player_preset player_path = prefs.filepaths.animation_player @@ -103,7 +105,7 @@ def execute(self, context): file_b = rd.frame_path(frame=int(frame_tmp / 10)) file = ("".join((c if file_b[i] == c else "#") - for i, c in enumerate(file_a))) + for i, c in enumerate(file_a))) del file_a, file_b, frame_tmp file = bpy.path.abspath(file) # expand '//' else: @@ -112,15 +114,15 @@ def execute(self, context): file = rd.frame_path(frame=scene.frame_start, preview=scene.use_preview_range) file = bpy.path.abspath(file) # expand '//' if not os.path.exists(file): - self.report({'WARNING'}, "File %r not found" % file) + self.report({'WARNING'}, f"File {file!r} not found") path_valid = False - #one last try for full range if we used preview range + # one last try for full range if we used preview range if scene.use_preview_range and not path_valid: file = rd.frame_path(frame=scene.frame_start, preview=False) file = bpy.path.abspath(file) # expand '//' if not os.path.exists(file): - self.report({'WARNING'}, "File %r not found" % file) + self.report({'WARNING'}, f"File {file!r} not found") cmd = [player_path] # extra options, fps controls etc. @@ -131,31 +133,34 @@ def execute(self, context): frame_start = scene.frame_start frame_end = scene.frame_end if preset == 'INTERNAL': - opts = ["-a", - "-f", str(rd.fps), str(rd.fps_base), - "-s", str(frame_start), - "-e", str(frame_end), - "-j", str(scene.frame_step), - file] + opts = [ + "-a", + "-f", str(rd.fps), str(rd.fps_base), + "-s", str(frame_start), + "-e", str(frame_end), + "-j", str(scene.frame_step), + file, + ] cmd.extend(opts) elif preset == 'DJV': - opts = [file, "-playback_speed", "%d" % int(rd.fps / rd.fps_base)] + opts = [file, "-playback_speed", str(int(fps_final))] cmd.extend(opts) elif preset == 'FRAMECYCLER': - opts = [file, "%d-%d" % (scene.frame_start, scene.frame_end)] + opts = [file, f"{scene.frame_start:d}-{scene.frame_end:d}"] cmd.extend(opts) elif preset == 'RV': - opts = ["-fps", str(rd.fps), "-play", "[ %s ]" % file] + opts = ["-fps", str(rd.fps), "-play", f"[ {file:s} ]"] cmd.extend(opts) elif preset == 'MPLAYER': opts = [] if is_movie: opts.append(file) else: - opts += [("mf://%s" % file.replace("#", "?")), - "-mf", - "fps=%.4f" % (rd.fps / rd.fps_base), - ] + opts += [ + ("mf://" + file.replace("#", "?")), + "-mf", + f"fps={fps_final:4f}" + ] opts += ["-loop", "0", "-really-quiet", "-fs"] cmd.extend(opts) @@ -163,7 +168,7 @@ def execute(self, context): cmd.append(file) # launch it - print("Executing command:\n %r" % " ".join(cmd)) + print("Executing command:\n ", " ".join(quote(c) for c in cmd)) # workaround for boost 1.46, can be eventually removed. bug: [#32350] env_copy = os.environ.copy() @@ -174,9 +179,11 @@ def execute(self, context): try: subprocess.Popen(cmd, env=env_copy) except Exception as e: - self.report({'ERROR'}, - "Couldn't run external animation player with command " - "%r\n%s" % (" ".join(cmd), str(e))) + self.report( + {'ERROR'}, + "Couldn't run external animation player with command " + f"{cmd!r}\n{e!s}", + ) return {'CANCELLED'} return {'FINISHED'} diff --git a/release/scripts/startup/bl_operators/sequencer.py b/release/scripts/startup/bl_operators/sequencer.py index 337492bc8a74..c9a7aa93805a 100644 --- a/release/scripts/startup/bl_operators/sequencer.py +++ b/release/scripts/startup/bl_operators/sequencer.py @@ -83,11 +83,11 @@ class SequencerCutMulticam(Operator): bl_options = {'REGISTER', 'UNDO'} camera = IntProperty( - name="Camera", - min=1, max=32, - soft_min=1, soft_max=32, - default=1, - ) + name="Camera", + min=1, max=32, + soft_min=1, soft_max=32, + default=1, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/uvcalc_follow_active.py b/release/scripts/startup/bl_operators/uvcalc_follow_active.py index bcc3a557b48a..72445be6950d 100644 --- a/release/scripts/startup/bl_operators/uvcalc_follow_active.py +++ b/release/scripts/startup/bl_operators/uvcalc_follow_active.py @@ -18,7 +18,7 @@ # -#for full docs see... +# for full docs see... # http://mediawiki.blender.org/index.php/Scripts/Manual/UV_Calculate/Follow_active_quads import bpy @@ -227,14 +227,14 @@ class FollowActiveQuads(Operator): bl_options = {'REGISTER', 'UNDO'} mode = bpy.props.EnumProperty( - name="Edge Length Mode", - description="Method to space UV edge loops", - items=(('EVEN', "Even", "Space all UVs evenly"), - ('LENGTH', "Length", "Average space UVs edge length of each loop"), - ('LENGTH_AVERAGE', "Length Average", "Average space UVs edge length of each loop"), - ), - default='LENGTH_AVERAGE', - ) + name="Edge Length Mode", + description="Method to space UV edge loops", + items=(('EVEN', "Even", "Space all UVs evenly"), + ('LENGTH', "Length", "Average space UVs edge length of each loop"), + ('LENGTH_AVERAGE', "Length Average", "Average space UVs edge length of each loop"), + ), + default='LENGTH_AVERAGE', + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/uvcalc_lightmap.py b/release/scripts/startup/bl_operators/uvcalc_lightmap.py index 3757a466382b..0b0dd58e80f2 100644 --- a/release/scripts/startup/bl_operators/uvcalc_lightmap.py +++ b/release/scripts/startup/bl_operators/uvcalc_lightmap.py @@ -33,7 +33,7 @@ class prettyface: "yoff", "has_parent", "rot", - ) + ) def __init__(self, data): self.has_parent = False @@ -63,9 +63,9 @@ def __init__(self, data): self.width = self.height = d * 2 - #else: - # print(len(data), data) - # raise "Error" + # else: + # print(len(data), data) + # raise "Error" for pf in data: pf.has_parent = True @@ -460,7 +460,7 @@ def trilensdiff(t1, t2): # Tall boxes in groups of 2 for d, boxes in list(odd_dict.items()): if d[1] < max_int_dimension: - #\boxes.sort(key = lambda a: len(a.children)) + # boxes.sort(key=lambda a: len(a.children)) while len(boxes) >= 2: # print("foo", len(boxes)) ok = True @@ -594,6 +594,7 @@ def unwrap(operator, context, **kwargs): return {'FINISHED'} + from bpy.props import BoolProperty, FloatProperty, IntProperty @@ -613,50 +614,55 @@ class LightMapPack(Operator): bl_options = {'UNDO'} PREF_CONTEXT = bpy.props.EnumProperty( - name="Selection", - items=(('SEL_FACES', "Selected Faces", "Space all UVs evenly"), - ('ALL_FACES', "All Faces", "Average space UVs edge length of each loop"), - ('ALL_OBJECTS', "Selected Mesh Object", "Average space UVs edge length of each loop") - ), - ) + name="Selection", + items=( + ('SEL_FACES', "Selected Faces", "Space all UVs evenly"), + ('ALL_FACES', "All Faces", "Average space UVs edge length of each loop"), + ('ALL_OBJECTS', "Selected Mesh Object", "Average space UVs edge length of each loop") + ), + ) # Image & UVs... PREF_PACK_IN_ONE = BoolProperty( - name="Share Tex Space", - description=("Objects Share texture space, map all objects " - "into 1 uvmap"), - default=True, - ) + name="Share Tex Space", + description=( + "Objects Share texture space, map all objects " + "into 1 uvmap" + ), + default=True, + ) PREF_NEW_UVLAYER = BoolProperty( - name="New UV Map", - description="Create a new UV map for every mesh packed", - default=False, - ) + name="New UV Map", + description="Create a new UV map for every mesh packed", + default=False, + ) PREF_APPLY_IMAGE = BoolProperty( - name="New Image", - description=("Assign new images for every mesh (only one if " - "shared tex space enabled)"), - default=False, - ) + name="New Image", + description=( + "Assign new images for every mesh (only one if " + "shared tex space enabled)" + ), + default=False, + ) PREF_IMG_PX_SIZE = IntProperty( - name="Image Size", - description="Width and Height for the new image", - min=64, max=5000, - default=512, - ) + name="Image Size", + description="Width and Height for the new image", + min=64, max=5000, + default=512, + ) # UV Packing... PREF_BOX_DIV = IntProperty( - name="Pack Quality", - description="Pre Packing before the complex boxpack", - min=1, max=48, - default=12, - ) + name="Pack Quality", + description="Pre Packing before the complex boxpack", + min=1, max=48, + default=12, + ) PREF_MARGIN_DIV = FloatProperty( - name="Margin", - description="Size of the margin as a division of the UV", - min=0.001, max=1.0, - default=0.1, - ) + name="Margin", + description="Size of the margin as a division of the UV", + min=0.001, max=1.0, + default=0.1, + ) def execute(self, context): kwargs = self.as_keywords() diff --git a/release/scripts/startup/bl_operators/uvcalc_smart_project.py b/release/scripts/startup/bl_operators/uvcalc_smart_project.py index 12c56a188970..f0b1f934e389 100644 --- a/release/scripts/startup/bl_operators/uvcalc_smart_project.py +++ b/release/scripts/startup/bl_operators/uvcalc_smart_project.py @@ -26,7 +26,7 @@ import bpy from bpy.types import Operator -DEG_TO_RAD = 0.017453292519943295 # pi/180.0 +DEG_TO_RAD = 0.017453292519943295 # pi/180.0 # see bugs: # - T31598 (when too small). # - T48086 (when too big). @@ -38,6 +38,7 @@ USER_FILL_HOLES = None USER_FILL_HOLES_QUALITY = None + def pointInTri2D(v, v1, v2, v3): key = v1.x, v1.y, v2.x, v2.y, v3.x, v3.y @@ -93,20 +94,25 @@ def pointInTri2D(v, v1, v2, v3): def boundsIsland(faces): - minx = maxx = faces[0].uv[0][0] # Set initial bounds. + minx = maxx = faces[0].uv[0][0] # Set initial bounds. miny = maxy = faces[0].uv[0][1] # print len(faces), minx, maxx, miny , maxy for f in faces: for uv in f.uv: - x= uv.x - y= uv.y - if xmaxx: maxx= x - if y>maxy: maxy= y + x = uv.x + y = uv.y + if x < minx: + minx = x + if y < miny: + miny = y + if x > maxx: + maxx = x + if y > maxy: + maxy = y return minx, miny, maxx, maxy + """ def boundsEdgeLoop(edges): minx = maxx = edges[0][0] # Set initial bounds. @@ -128,45 +134,51 @@ def boundsEdgeLoop(edges): # Only for UV's # only returns outline edges for intersection tests. and unique points. + def island2Edge(island): # Vert index edges edges = {} - unique_points= {} + unique_points = {} for f in island: - f_uvkey= map(tuple, f.uv) - + f_uvkey = map(tuple, f.uv) for vIdx, edkey in enumerate(f.edge_keys): unique_points[f_uvkey[vIdx]] = f.uv[vIdx] - if f.v[vIdx].index > f.v[vIdx-1].index: - i1= vIdx-1; i2= vIdx + if f.v[vIdx].index > f.v[vIdx - 1].index: + i1 = vIdx - 1 + i2 = vIdx else: - i1= vIdx; i2= vIdx-1 + i1 = vIdx + i2 = vIdx - 1 - try: edges[ f_uvkey[i1], f_uvkey[i2] ] *= 0 # sets any edge with more than 1 user to 0 are not returned. - except: edges[ f_uvkey[i1], f_uvkey[i2] ] = (f.uv[i1] - f.uv[i2]).length, + try: + edges[f_uvkey[i1], f_uvkey[i2]] *= 0 # sets any edge with more than 1 user to 0 are not returned. + except: + edges[f_uvkey[i1], f_uvkey[i2]] = (f.uv[i1] - f.uv[i2]).length, # If 2 are the same then they will be together, but full [a,b] order is not correct. # Sort by length - length_sorted_edges = [(Vector(key[0]), Vector(key[1]), value) for key, value in edges.items() if value != 0] - try: length_sorted_edges.sort(key = lambda A: -A[2]) # largest first - except: length_sorted_edges.sort(lambda A, B: cmp(B[2], A[2])) + try: + length_sorted_edges.sort(key=lambda A: -A[2]) # largest first + except: + length_sorted_edges.sort(lambda A, B: cmp(B[2], A[2])) # Its okay to leave the length in there. - #for e in length_sorted_edges: + # for e in length_sorted_edges: # e.pop(2) # return edges and unique points return length_sorted_edges, [v.to_3d() for v in unique_points.values()] + # ========================= NOT WORKING???? # Find if a points inside an edge loop, unordered. # pt is and x/y @@ -190,6 +202,7 @@ def pointInEdges(pt, edges): return intersectCount % 2 """ + def pointInIsland(pt, island): vec1, vec2, vec3 = Vector(), Vector(), Vector() for f in island: @@ -212,7 +225,7 @@ def pointInIsland(pt, island): # box is (left,bottom, right, top) def islandIntersectUvIsland(source, target, SourceOffset): # Is 1 point in the box, inside the vertLoops - edgeLoopsSource = source[6] # Pretend this is offset + edgeLoopsSource = source[6] # Pretend this is offset edgeLoopsTarget = target[6] # Edge intersect test @@ -220,24 +233,24 @@ def islandIntersectUvIsland(source, target, SourceOffset): for seg in edgeLoopsTarget: i = geometry.intersect_line_line_2d(seg[0], seg[1], - SourceOffset+ed[0], - SourceOffset+ed[1], + SourceOffset + ed[0], + SourceOffset + ed[1], ) if i: - return 1 # LINE INTERSECTION + return 1 # LINE INTERSECTION # 1 test for source being totally inside target SourceOffset.resize_3d() for pv in source[7]: - if pointInIsland(pv+SourceOffset, target[0]): - return 2 # SOURCE INSIDE TARGET + if pointInIsland(pv + SourceOffset, target[0]): + return 2 # SOURCE INSIDE TARGET # 2 test for a part of the target being totally inside the source. for pv in target[7]: - if pointInIsland(pv-SourceOffset, source[0]): - return 3 # PART OF TARGET INSIDE SOURCE. + if pointInIsland(pv - SourceOffset, source[0]): + return 3 # PART OF TARGET INSIDE SOURCE. - return 0 # NO INTERSECTION + return 0 # NO INTERSECTION def rotate_uvs(uv_points, angle): @@ -249,7 +262,7 @@ def rotate_uvs(uv_points, angle): def optiRotateUvIsland(faces): - uv_points = [uv for f in faces for uv in f.uv] + uv_points = [uv for f in faces for uv in f.uv] angle = geometry.box_fit_2d(uv_points) if angle != 0.0: @@ -270,81 +283,78 @@ def mergeUvIslands(islandList): global USER_FILL_HOLES global USER_FILL_HOLES_QUALITY - # Pack islands to bottom LHS # Sync with island - #islandTotFaceArea = [] # A list of floats, each island area - #islandArea = [] # a list of tuples ( area, w,h) - + # islandTotFaceArea = [] # A list of floats, each island area + # islandArea = [] # a list of tuples ( area, w,h) decoratedIslandList = [] islandIdx = len(islandList) while islandIdx: - islandIdx-=1 + islandIdx -= 1 minx, miny, maxx, maxy = boundsIsland(islandList[islandIdx]) - w, h = maxx-minx, maxy-miny + w, h = maxx - minx, maxy - miny totFaceArea = 0 - offset= Vector((minx, miny)) + offset = Vector((minx, miny)) for f in islandList[islandIdx]: for uv in f.uv: uv -= offset totFaceArea += f.area - islandBoundsArea = w*h + islandBoundsArea = w * h efficiency = abs(islandBoundsArea - totFaceArea) # UV Edge list used for intersections as well as unique points. edges, uniqueEdgePoints = island2Edge(islandList[islandIdx]) - decoratedIslandList.append([islandList[islandIdx], totFaceArea, efficiency, islandBoundsArea, w,h, edges, uniqueEdgePoints]) - + decoratedIslandList.append([islandList[islandIdx], totFaceArea, efficiency, islandBoundsArea, w, h, edges, uniqueEdgePoints]) # Sort by island bounding box area, smallest face area first. # no.. chance that to most simple edge loop first. - decoratedIslandListAreaSort =decoratedIslandList[:] + decoratedIslandListAreaSort = decoratedIslandList[:] - decoratedIslandListAreaSort.sort(key = lambda A: A[3]) + decoratedIslandListAreaSort.sort(key=lambda A: A[3]) # sort by efficiency, Least Efficient first. decoratedIslandListEfficSort = decoratedIslandList[:] # decoratedIslandListEfficSort.sort(lambda A, B: cmp(B[2], A[2])) - decoratedIslandListEfficSort.sort(key = lambda A: -A[2]) + decoratedIslandListEfficSort.sort(key=lambda A: -A[2]) # ================================================== THESE CAN BE TWEAKED. # This is a quality value for the number of tests. # from 1 to 4, generic quality value is from 1 to 100 - USER_STEP_QUALITY = ((USER_FILL_HOLES_QUALITY - 1) / 25.0) + 1 + USER_STEP_QUALITY = ((USER_FILL_HOLES_QUALITY - 1) / 25.0) + 1 # If 100 will test as long as there is enough free space. # this is rarely enough, and testing takes a while, so lower quality speeds this up. # 1 means they have the same quality - USER_FREE_SPACE_TO_TEST_QUALITY = 1 + (((100 - USER_FILL_HOLES_QUALITY)/100.0) *5) + USER_FREE_SPACE_TO_TEST_QUALITY = 1 + (((100 - USER_FILL_HOLES_QUALITY) / 100.0) * 5) - #print 'USER_STEP_QUALITY', USER_STEP_QUALITY - #print 'USER_FREE_SPACE_TO_TEST_QUALITY', USER_FREE_SPACE_TO_TEST_QUALITY + # print 'USER_STEP_QUALITY', USER_STEP_QUALITY + # print 'USER_FREE_SPACE_TO_TEST_QUALITY', USER_FREE_SPACE_TO_TEST_QUALITY removedCount = 0 areaIslandIdx = 0 ctrl = Window.Qual.CTRL - BREAK= False + BREAK = False while areaIslandIdx < len(decoratedIslandListAreaSort) and not BREAK: sourceIsland = decoratedIslandListAreaSort[areaIslandIdx] # Already packed? if not sourceIsland[0]: - areaIslandIdx+=1 + areaIslandIdx += 1 else: efficIslandIdx = 0 while efficIslandIdx < len(decoratedIslandListEfficSort) and not BREAK: if Window.GetKeyQualifiers() & ctrl: - BREAK= True + BREAK = True break # Now we have 2 islands, if the efficiency of the islands lowers theres an @@ -355,64 +365,60 @@ def mergeUvIslands(islandList): targetIsland = decoratedIslandListEfficSort[efficIslandIdx] - if sourceIsland[0] == targetIsland[0] or\ - not targetIsland[0] or\ - not sourceIsland[0]: + not targetIsland[0] or\ + not sourceIsland[0]: pass else: #~ ([island, totFaceArea, efficiency, islandArea, w,h]) # Wasted space on target is greater then UV bounding island area. - #~ if targetIsland[3] > (sourceIsland[2]) and\ # - #~ print USER_FREE_SPACE_TO_TEST_QUALITY + # ~ print USER_FREE_SPACE_TO_TEST_QUALITY if targetIsland[2] > (sourceIsland[1] * USER_FREE_SPACE_TO_TEST_QUALITY) and\ - targetIsland[4] > sourceIsland[4] and\ - targetIsland[5] > sourceIsland[5]: + targetIsland[4] > sourceIsland[4] and\ + targetIsland[5] > sourceIsland[5]: # DEBUG # print '%.10f %.10f' % (targetIsland[3], sourceIsland[1]) # These enough spare space lets move the box until it fits # How many times does the source fit into the target x/y - blockTestXUnit = targetIsland[4]/sourceIsland[4] - blockTestYUnit = targetIsland[5]/sourceIsland[5] + blockTestXUnit = targetIsland[4] / sourceIsland[4] + blockTestYUnit = targetIsland[5] / sourceIsland[5] boxLeft = 0 - # Distance we can move between whilst staying inside the targets bounds. testWidth = targetIsland[4] - sourceIsland[4] testHeight = targetIsland[5] - sourceIsland[5] # Increment we move each test. x/y - xIncrement = (testWidth / (blockTestXUnit * ((USER_STEP_QUALITY/50)+0.1))) - yIncrement = (testHeight / (blockTestYUnit * ((USER_STEP_QUALITY/50)+0.1))) + xIncrement = (testWidth / (blockTestXUnit * ((USER_STEP_QUALITY / 50) + 0.1))) + yIncrement = (testHeight / (blockTestYUnit * ((USER_STEP_QUALITY / 50) + 0.1))) # Make sure were not moving less then a 3rg of our width/height - if xIncrement testWidth: boxBottom += yIncrement boxLeft = 0.0 else: boxLeft += xIncrement - ##print testcount + # print testcount - efficIslandIdx+=1 - areaIslandIdx+=1 + efficIslandIdx += 1 + areaIslandIdx += 1 # Remove empty islands i = len(islandList) while i: - i-=1 + i -= 1 if not islandList[i]: - del islandList[i] # Can increment islands removed here. + del islandList[i] # Can increment islands removed here. # Takes groups of faces. assumes face groups are UV groups. + + def getUvIslands(faceGroups, me): # Get seams so we don't cross over seams - edge_seams = {} # should be a set + edge_seams = {} # should be a set for ed in me.edges: if ed.use_seam: - edge_seams[ed.key] = None # dummy var- use sets! + edge_seams[ed.key] = None # dummy var- use sets! # Done finding seams - islandList = [] -#XXX Window.DrawProgressBar(0.0, 'Splitting %d projection groups into UV islands:' % len(faceGroups)) - #print '\tSplitting %d projection groups into UV islands:' % len(faceGroups), +# XXX Window.DrawProgressBar(0.0, 'Splitting %d projection groups into UV islands:' % len(faceGroups)) + # print '\tSplitting %d projection groups into UV islands:' % len(faceGroups), # Find grouped faces faceGroupIdx = len(faceGroups) while faceGroupIdx: - faceGroupIdx-=1 + faceGroupIdx -= 1 faces = faceGroups[faceGroupIdx] if not faces: @@ -526,37 +531,38 @@ def getUvIslands(faceGroups, me): for i, f in enumerate(faces): for ed_key in f.edge_keys: - if ed_key in edge_seams: # DELIMIT SEAMS! ;) - edge_users[ed_key] = [] # so as not to raise an error + if ed_key in edge_seams: # DELIMIT SEAMS! ;) + edge_users[ed_key] = [] # so as not to raise an error else: - try: edge_users[ed_key].append(i) - except: edge_users[ed_key] = [i] + try: + edge_users[ed_key].append(i) + except: + edge_users[ed_key] = [i] # Modes # 0 - face not yet touched. # 1 - added to island list, and need to search # 2 - touched and searched - don't touch again. - face_modes = [0] * len(faces) # initialize zero - untested. + face_modes = [0] * len(faces) # initialize zero - untested. - face_modes[0] = 1 # start the search with face 1 + face_modes[0] = 1 # start the search with face 1 newIsland = [] newIsland.append(faces[0]) - ok = True while ok: ok = True while ok: - ok= False + ok = False for i in range(len(faces)): - if face_modes[i] == 1: # search + if face_modes[i] == 1: # search for ed_key in faces[i].edge_keys: for ii in edge_users[ed_key]: if i != ii and face_modes[ii] == 0: - face_modes[ii] = ok = 1 # mark as searched + face_modes[ii] = ok = 1 # mark as searched newIsland.append(faces[ii]) # mark as searched, don't look again. @@ -574,7 +580,7 @@ def getUvIslands(faceGroups, me): break # if not ok will stop looping -#XXX Window.DrawProgressBar(0.1, 'Optimizing Rotation for %i UV Islands' % len(islandList)) +# XXX Window.DrawProgressBar(0.1, 'Optimizing Rotation for %i UV Islands' % len(islandList)) for island in islandList: optiRotateUvIsland(island) @@ -584,9 +590,8 @@ def getUvIslands(faceGroups, me): def packIslands(islandList): if USER_FILL_HOLES: -#XXX Window.DrawProgressBar(0.1, 'Merging Islands (Ctrl: skip merge)...') - mergeUvIslands(islandList) # Modify in place - + # XXX Window.DrawProgressBar(0.1, 'Merging Islands (Ctrl: skip merge)...') + mergeUvIslands(islandList) # Modify in place # Now we have UV islands, we need to pack them. @@ -603,16 +608,16 @@ def packIslands(islandList): while islandIdx < len(islandList): minx, miny, maxx, maxy = boundsIsland(islandList[islandIdx]) - w, h = maxx-minx, maxy-miny + w, h = maxx - minx, maxy - miny if USER_ISLAND_MARGIN: - minx -= USER_ISLAND_MARGIN# *w - miny -= USER_ISLAND_MARGIN# *h - maxx += USER_ISLAND_MARGIN# *w - maxy += USER_ISLAND_MARGIN# *h + minx -= USER_ISLAND_MARGIN # *w + miny -= USER_ISLAND_MARGIN # *h + maxx += USER_ISLAND_MARGIN # *w + maxy += USER_ISLAND_MARGIN # *h # recalc width and height - w, h = maxx-minx, maxy-miny + w, h = maxx - minx, maxy - miny if w < SMALL_NUM: w = SMALL_NUM @@ -628,24 +633,24 @@ def packIslands(islandList): # Add to boxList. use the island idx for the BOX id. packBoxes.append([0, 0, w, h]) - islandIdx+=1 + islandIdx += 1 # Now we have a list of boxes to pack that syncs # with the islands. - #print '\tPacking UV Islands...' -#XXX Window.DrawProgressBar(0.7, "Packing %i UV Islands..." % len(packBoxes) ) + # print '\tPacking UV Islands...' +# XXX Window.DrawProgressBar(0.7, "Packing %i UV Islands..." % len(packBoxes) ) # time1 = time.time() packWidth, packHeight = geometry.box_pack_2d(packBoxes) # print 'Box Packing Time:', time.time() - time1 - #if len(pa ckedLs) != len(islandList): + # if len(pa ckedLs) != len(islandList): # raise ValueError("Packed boxes differs from original length") - #print '\tWriting Packed Data to faces' -#XXX Window.DrawProgressBar(0.8, "Writing Packed Data to faces") + # print '\tWriting Packed Data to faces' +# XXX Window.DrawProgressBar(0.8, "Writing Packed Data to faces") # Sort by ID, so there in sync again islandIdx = len(islandList) @@ -661,16 +666,16 @@ def packIslands(islandList): xfactor = yfactor = 1.0 / max(packWidth, packHeight) while islandIdx: - islandIdx -=1 + islandIdx -= 1 # Write the packed values to the UV's xoffset = packBoxes[islandIdx][0] - islandOffsetList[islandIdx][0] yoffset = packBoxes[islandIdx][1] - islandOffsetList[islandIdx][1] - for f in islandList[islandIdx]: # Offsetting the UV's so they fit in there packed box + for f in islandList[islandIdx]: # Offsetting the UV's so they fit in there packed box for uv in f.uv: - uv.x= (uv.x+xoffset) * xfactor - uv.y= (uv.y+yoffset) * yfactor + uv.x = (uv.x + xoffset) * xfactor + uv.y = (uv.y + yoffset) * yfactor def VectoQuat(vec): @@ -679,7 +684,8 @@ def VectoQuat(vec): class thickface: - __slost__= "v", "uv", "no", "area", "edge_keys" + __slost__ = "v", "uv", "no", "area", "edge_keys" + def __init__(self, face, uv_layer, mesh_verts): self.v = [mesh_verts[i] for i in face.vertices] self.uv = [uv_layer[i].uv for i in face.loop_indices] @@ -700,18 +706,20 @@ def main_consts(): ROTMAT_2D_POS_45D = Matrix.Rotation(radians(45.0), 2) RotMatStepRotation = [] - rot_angle = 22.5 #45.0/2 + rot_angle = 22.5 # 45.0/2 while rot_angle > 0.1: RotMatStepRotation.append([ Matrix.Rotation(radians(+rot_angle), 2), Matrix.Rotation(radians(-rot_angle), 2), - ]) + ]) - rot_angle = rot_angle/2.0 + rot_angle = rot_angle / 2.0 global ob ob = None + + def main(context, island_margin, projection_limit, @@ -741,18 +749,18 @@ def main(context, # Create the variables. USER_PROJECTION_LIMIT = projection_limit USER_ONLY_SELECTED_FACES = True - USER_SHARE_SPACE = 1 # Only for hole filling. + USER_SHARE_SPACE = 1 # Only for hole filling. USER_STRETCH_ASPECT = stretch_to_bounds - USER_ISLAND_MARGIN = island_margin # Only for hole filling. + USER_ISLAND_MARGIN = island_margin # Only for hole filling. USER_FILL_HOLES = 0 - USER_FILL_HOLES_QUALITY = 50 # Only for hole filling. - USER_VIEW_INIT = 0 # Only for hole filling. + USER_FILL_HOLES_QUALITY = 50 # Only for hole filling. + USER_VIEW_INIT = 0 # Only for hole filling. is_editmode = (context.active_object.mode == 'EDIT') if is_editmode: - obList = [ob for ob in [context.active_object] if ob and ob.type == 'MESH'] + obList = [ob for ob in [context.active_object] if ob and ob.type == 'MESH'] else: - obList = [ob for ob in context.selected_editable_objects if ob and ob.type == 'MESH'] + obList = [ob for ob in context.selected_editable_objects if ob and ob.type == 'MESH'] USER_ONLY_SELECTED_FACES = False if not obList: @@ -770,15 +778,14 @@ def main(context, time.sleep(10) ''' -#~ XXX if not Draw.PupBlock(ob % len(obList), pup_block): -#~ XXX return -#~ XXX del ob +# ~ XXX if not Draw.PupBlock(ob % len(obList), pup_block): +# ~ XXX return +# ~ XXX del ob # Convert from being button types USER_PROJECTION_LIMIT_CONVERTED = cos(USER_PROJECTION_LIMIT * DEG_TO_RAD) - USER_PROJECTION_LIMIT_HALF_CONVERTED = cos((USER_PROJECTION_LIMIT/2) * DEG_TO_RAD) - + USER_PROJECTION_LIMIT_HALF_CONVERTED = cos((USER_PROJECTION_LIMIT / 2) * DEG_TO_RAD) # Toggle Edit mode is_editmode = (context.active_object.mode == 'EDIT') @@ -788,19 +795,18 @@ def main(context, if USER_SHARE_SPACE: # Sort by data name so we get consistent results - obList.sort(key = lambda ob: ob.data.name) - collected_islandList= [] + obList.sort(key=lambda ob: ob.data.name) + collected_islandList = [] -#XXX Window.WaitCursor(1) +# XXX Window.WaitCursor(1) time1 = time.time() # Tag as False so we don't operate on the same mesh twice. -#XXX bpy.data.meshes.tag = False +# XXX bpy.data.meshes.tag = False for me in bpy.data.meshes: me.tag = False - for ob in obList: me = ob.data @@ -810,7 +816,7 @@ def main(context, # Tag as used me.tag = True - if not me.uv_textures: # Mesh has no UV Coords, don't bother. + if not me.uv_textures: # Mesh has no UV Coords, don't bother. me.uv_textures.new() uv_layer = me.uv_layers.active.data @@ -821,7 +827,7 @@ def main(context, else: meshFaces = [thickface(f, uv_layer, me_verts) for i, f in enumerate(me.polygons)] -#XXX Window.DrawProgressBar(0.1, 'SmartProj UV Unwrapper, mapping "%s", %i faces.' % (me.name, len(meshFaces))) +# XXX Window.DrawProgressBar(0.1, 'SmartProj UV Unwrapper, mapping "%s", %i faces.' % (me.name, len(meshFaces))) # ======= # Generate a projection list from face normals, this is meant to be smart :) @@ -849,17 +855,15 @@ def main(context, # 0d is 1.0 # 180 IS -0.59846 - # Initialize projectVecs if USER_VIEW_INIT: # Generate Projection - projectVecs = [Vector(Window.GetViewVector()) * ob.matrix_world.inverted().to_3x3()] # We add to this along the way + projectVecs = [Vector(Window.GetViewVector()) * ob.matrix_world.inverted().to_3x3()] # We add to this along the way else: projectVecs = [] newProjectVec = meshFaces[0].no - newProjectMeshFaces = [] # Popping stuffs it up. - + newProjectMeshFaces = [] # Popping stuffs it up. # Pretend that the most unique angle is ages away to start the loop off mostUniqueAngle = -1.0 @@ -867,14 +871,12 @@ def main(context, # This is popped tempMeshFaces = meshFaces[:] - - # This while only gathers projection vecs, faces are assigned later on. while 1: # If theres none there then start with the largest face # add all the faces that are close. - for fIdx in range(len(tempMeshFaces)-1, -1, -1): + for fIdx in range(len(tempMeshFaces) - 1, -1, -1): # Use half the angle limit so we don't overweight faces towards this # normal and hog all the faces. if newProjectVec.dot(tempMeshFaces[fIdx].no) > USER_PROJECTION_LIMIT_HALF_CONVERTED: @@ -892,24 +894,23 @@ def main(context, for fprop in newProjectMeshFaces: averageVec += fprop.no * ((fprop.area * user_area_weight) + (1.0 - user_area_weight)) - if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0: # Avoid NAN + if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0: # Avoid NAN projectVecs.append(averageVec.normalized()) - # Get the next vec! # Pick the face thats most different to all existing angles :) - mostUniqueAngle = 1.0 # 1.0 is 0d. no difference. - mostUniqueIndex = 0 # dummy + mostUniqueAngle = 1.0 # 1.0 is 0d. no difference. + mostUniqueIndex = 0 # dummy - for fIdx in range(len(tempMeshFaces)-1, -1, -1): - angleDifference = -1.0 # 180d difference. + for fIdx in range(len(tempMeshFaces) - 1, -1, -1): + angleDifference = -1.0 # 180d difference. # Get the closest vec angle we are to. for p in projectVecs: - temp_angle_diff= p.dot(tempMeshFaces[fIdx].no) + temp_angle_diff = p.dot(tempMeshFaces[fIdx].no) if angleDifference < temp_angle_diff: - angleDifference= temp_angle_diff + angleDifference = temp_angle_diff if angleDifference < mostUniqueAngle: # We have a new most different angle @@ -917,30 +918,28 @@ def main(context, mostUniqueAngle = angleDifference if mostUniqueAngle < USER_PROJECTION_LIMIT_CONVERTED: - #print 'adding', mostUniqueAngle, USER_PROJECTION_LIMIT, len(newProjectMeshFaces) + # print 'adding', mostUniqueAngle, USER_PROJECTION_LIMIT, len(newProjectMeshFaces) # Now weight the vector to all its faces, will give a more direct projection # if the face its self was not representative of the normal from surrounding faces. newProjectVec = tempMeshFaces[mostUniqueIndex].no newProjectMeshFaces = [tempMeshFaces.pop(mostUniqueIndex)] - else: - if len(projectVecs) >= 1: # Must have at least 2 projections + if len(projectVecs) >= 1: # Must have at least 2 projections break - # If there are only zero area faces then its possible # there are no projectionVecs if not len(projectVecs): Draw.PupMenu('error, no projection vecs where generated, 0 area faces can cause this.') return - faceProjectionGroupList =[[] for i in range(len(projectVecs)) ] + faceProjectionGroupList = [[] for i in range(len(projectVecs))] # MAP and Arrange # We know there are 3 or 4 faces here - for fIdx in range(len(meshFaces)-1, -1, -1): + for fIdx in range(len(meshFaces) - 1, -1, -1): fvec = meshFaces[fIdx].no i = len(projectVecs) @@ -949,11 +948,11 @@ def main(context, bestAngIdx = 0 # Cycle through the remaining, first already done - while i-1: - i-=1 + while i - 1: + i -= 1 newAng = fvec.dot(projectVecs[i]) - if newAng > bestAng: # Reverse logic for dotvecs + if newAng > bestAng: # Reverse logic for dotvecs bestAng = newAng bestAngIdx = i @@ -962,7 +961,6 @@ def main(context, # Cull faceProjectionGroupList, - # Now faceProjectionGroupList is full of faces that face match the project Vecs list for i in range(len(projectVecs)): # Account for projectVecs having no faces. @@ -979,7 +977,6 @@ def main(context, # XXX - note, between mathutils in 2.4 and 2.5 the order changed. f_uv[j][:] = (MatQuat * v.co).xy - if USER_SHARE_SPACE: # Should we collect and pack later? islandList = getUvIslands(faceProjectionGroupList, me) @@ -990,12 +987,11 @@ def main(context, islandList = getUvIslands(faceProjectionGroupList, me) packIslands(islandList) - # update the mesh here if we need to. # We want to pack all in 1 go, so pack now if USER_SHARE_SPACE: -#XXX Window.DrawProgressBar(0.9, "Box Packing for all objects...") + # XXX Window.DrawProgressBar(0.9, "Box Packing for all objects...") packIslands(collected_islandList) print("Smart Projection time: %.2f" % (time.time() - time1)) @@ -1006,31 +1002,32 @@ def main(context, bpy.ops.object.mode_set(mode='EDIT') if use_aspect: - import bmesh - aspect = context.scene.uvedit_aspect(context.active_object) - if aspect[0] > aspect[1]: - aspect[0] = aspect[1]/aspect[0]; - aspect[1] = 1.0 - else: - aspect[1] = aspect[0]/aspect[1]; - aspect[0] = 1.0 + import bmesh + aspect = context.scene.uvedit_aspect(context.active_object) + if aspect[0] > aspect[1]: + aspect[0] = aspect[1] / aspect[0] + aspect[1] = 1.0 + else: + aspect[1] = aspect[0] / aspect[1] + aspect[0] = 1.0 - bm = bmesh.from_edit_mesh(me) + bm = bmesh.from_edit_mesh(me) - uv_act = bm.loops.layers.uv.active + uv_act = bm.loops.layers.uv.active - faces = [f for f in bm.faces if f.select] + faces = [f for f in bm.faces if f.select] - for f in faces: - for l in f.loops: - l[uv_act].uv[0] *= aspect[0] - l[uv_act].uv[1] *= aspect[1] + for f in faces: + for l in f.loops: + l[uv_act].uv[0] *= aspect[0] + l[uv_act].uv[1] *= aspect[1] dict_matrix.clear() -#XXX Window.DrawProgressBar(1.0, "") -#XXX Window.WaitCursor(0) -#XXX Window.RedrawAll() +# XXX Window.DrawProgressBar(1.0, "") +# XXX Window.WaitCursor(0) +# XXX Window.RedrawAll() + """ pup_block = [\ @@ -1052,41 +1049,41 @@ def main(context, class SmartProject(Operator): """This script projection unwraps the selected faces of a mesh """ \ - """(it operates on all selected mesh objects, and can be used """ \ - """to unwrap selected faces, or all faces)""" + """(it operates on all selected mesh objects, and can be used """ \ + """to unwrap selected faces, or all faces)""" bl_idname = "uv.smart_project" bl_label = "Smart UV Project" bl_options = {'REGISTER', 'UNDO'} angle_limit = FloatProperty( - name="Angle Limit", - description="Lower for more projection groups, higher for less distortion", - min=1.0, max=89.0, - default=66.0, - ) + name="Angle Limit", + description="Lower for more projection groups, higher for less distortion", + min=1.0, max=89.0, + default=66.0, + ) island_margin = FloatProperty( - name="Island Margin", - description="Margin to reduce bleed from adjacent islands", - unit='LENGTH', subtype='DISTANCE', - min=0.0, max=1.0, - default=0.0, - ) + name="Island Margin", + description="Margin to reduce bleed from adjacent islands", + unit='LENGTH', subtype='DISTANCE', + min=0.0, max=1.0, + default=0.0, + ) user_area_weight = FloatProperty( - name="Area Weight", - description="Weight projections vector by faces with larger areas", - min=0.0, max=1.0, - default=0.0, - ) + name="Area Weight", + description="Weight projections vector by faces with larger areas", + min=0.0, max=1.0, + default=0.0, + ) use_aspect = BoolProperty( - name="Correct Aspect", - description="Map UVs taking image aspect ratio into account", - default=True - ) + name="Correct Aspect", + description="Map UVs taking image aspect ratio into account", + default=True + ) stretch_to_bounds = BoolProperty( - name="Stretch to UV Bounds", - description="Stretch the final output to texture bounds", - default=True, - ) + name="Stretch to UV Bounds", + description="Stretch the final output to texture bounds", + default=True, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/vertexpaint_dirt.py b/release/scripts/startup/bl_operators/vertexpaint_dirt.py index f12b76a76ba0..1173e0047bb3 100644 --- a/release/scripts/startup/bl_operators/vertexpaint_dirt.py +++ b/release/scripts/startup/bl_operators/vertexpaint_dirt.py @@ -139,36 +139,36 @@ class VertexPaintDirt(Operator): bl_options = {'REGISTER', 'UNDO'} blur_strength = FloatProperty( - name="Blur Strength", - description="Blur strength per iteration", - min=0.01, max=1.0, - default=1.0, - ) + name="Blur Strength", + description="Blur strength per iteration", + min=0.01, max=1.0, + default=1.0, + ) blur_iterations = IntProperty( - name="Blur Iterations", - description="Number of times to blur the colors (higher blurs more)", - min=0, max=40, - default=1, - ) + name="Blur Iterations", + description="Number of times to blur the colors (higher blurs more)", + min=0, max=40, + default=1, + ) clean_angle = FloatProperty( - name="Highlight Angle", - description="Less than 90 limits the angle used in the tonal range", - min=0.0, max=pi, - default=pi, - unit="ROTATION", - ) + name="Highlight Angle", + description="Less than 90 limits the angle used in the tonal range", + min=0.0, max=pi, + default=pi, + unit="ROTATION", + ) dirt_angle = FloatProperty( - name="Dirt Angle", - description="Less than 90 limits the angle used in the tonal range", - min=0.0, max=pi, - default=0.0, - unit="ROTATION", - ) + name="Dirt Angle", + description="Less than 90 limits the angle used in the tonal range", + min=0.0, max=pi, + default=0.0, + unit="ROTATION", + ) dirt_only = BoolProperty( - name="Dirt Only", - description="Don't calculate cleans for convex areas", - default=False, - ) + name="Dirt Only", + description="Don't calculate cleans for convex areas", + default=False, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/view3d.py b/release/scripts/startup/bl_operators/view3d.py index 18f911100539..f56c83be7d15 100644 --- a/release/scripts/startup/bl_operators/view3d.py +++ b/release/scripts/startup/bl_operators/view3d.py @@ -39,13 +39,16 @@ def execute(self, context): totface = mesh.total_face_sel totedge = mesh.total_edge_sel - #~ totvert = mesh.total_vert_sel + # totvert = mesh.total_vert_sel if select_mode[2] and totface == 1: - bpy.ops.mesh.extrude_region_move('INVOKE_REGION_WIN', - TRANSFORM_OT_translate={ - "constraint_orientation": 'NORMAL', - "constraint_axis": (False, False, True)}) + bpy.ops.mesh.extrude_region_move( + 'INVOKE_REGION_WIN', + TRANSFORM_OT_translate={ + "constraint_orientation": 'NORMAL', + "constraint_axis": (False, False, True), + } + ) elif select_mode[2] and totface > 1: bpy.ops.mesh.extrude_faces_move('INVOKE_REGION_WIN') elif select_mode[1] and totedge >= 1: @@ -77,25 +80,32 @@ def extrude_region(context, use_vert_normals): totface = mesh.total_face_sel totedge = mesh.total_edge_sel - #~ totvert = mesh.total_vert_sel + # totvert = mesh.total_vert_sel if totface >= 1: if use_vert_normals: - bpy.ops.mesh.extrude_region_shrink_fatten('INVOKE_REGION_WIN', - TRANSFORM_OT_shrink_fatten={}) + bpy.ops.mesh.extrude_region_shrink_fatten( + 'INVOKE_REGION_WIN', + TRANSFORM_OT_shrink_fatten={}, + ) else: - bpy.ops.mesh.extrude_region_move('INVOKE_REGION_WIN', - TRANSFORM_OT_translate={ - "constraint_orientation": 'NORMAL', - "constraint_axis": (False, False, True)}) - - elif totedge == 1: - bpy.ops.mesh.extrude_region_move('INVOKE_REGION_WIN', + bpy.ops.mesh.extrude_region_move( + 'INVOKE_REGION_WIN', TRANSFORM_OT_translate={ "constraint_orientation": 'NORMAL', - # not a popular choice, too restrictive for retopo. - #~ "constraint_axis": (True, True, False)}) - "constraint_axis": (False, False, False)}) + "constraint_axis": (False, False, True), + }, + ) + + elif totedge == 1: + bpy.ops.mesh.extrude_region_move( + 'INVOKE_REGION_WIN', + TRANSFORM_OT_translate={ + "constraint_orientation": 'NORMAL', + # not a popular choice, too restrictive for retopo. + # "constraint_axis": (True, True, False)}) + "constraint_axis": (False, False, False), + }) else: bpy.ops.mesh.extrude_region_move('INVOKE_REGION_WIN') @@ -134,40 +144,40 @@ class VIEW3D_OT_select_or_deselect_all(Operator): bl_options = {'UNDO'} extend = BoolProperty( - name="Extend", - description="Extend selection instead of deselecting everything first", - default=False, - ) + name="Extend", + description="Extend selection instead of deselecting everything first", + default=False, + ) toggle = BoolProperty( - name="Toggle", - description="Toggle the selection", - default=False, - ) + name="Toggle", + description="Toggle the selection", + default=False, + ) deselect = BoolProperty( - name="Deselect", - description="Remove from selection", - default=False, - ) + name="Deselect", + description="Remove from selection", + default=False, + ) center = BoolProperty( - name="Center", - description="Use the object center when selecting, in editmode used to extend object selection", - default=False, - ) + name="Center", + description="Use the object center when selecting, in editmode used to extend object selection", + default=False, + ) enumerate = BoolProperty( - name="Enumerate", - description="List objects under the mouse (object mode only)", - default=False, - ) + name="Enumerate", + description="List objects under the mouse (object mode only)", + default=False, + ) object = BoolProperty( - name="Object", - description="Use object selection (editmode only)", - default=False, - ) + name="Object", + description="Use object selection (editmode only)", + default=False, + ) @classmethod def poll(cls, context): diff --git a/release/scripts/startup/bl_operators/wm.py b/release/scripts/startup/bl_operators/wm.py index 022ee1576d80..edca3a521eeb 100644 --- a/release/scripts/startup/bl_operators/wm.py +++ b/release/scripts/startup/bl_operators/wm.py @@ -32,28 +32,28 @@ rna_path_prop = StringProperty( - name="Context Attributes", - description="RNA context string", - maxlen=1024, - ) + name="Context Attributes", + description="RNA context string", + maxlen=1024, +) rna_reverse_prop = BoolProperty( - name="Reverse", - description="Cycle backwards", - default=False, - ) + name="Reverse", + description="Cycle backwards", + default=False, +) rna_wrap_prop = BoolProperty( - name="Wrap", - description="Wrap back to the first/last values", - default=False, - ) + name="Wrap", + description="Wrap back to the first/last values", + default=False, +) rna_relative_prop = BoolProperty( - name="Relative", - description="Apply relative to the current value (delta)", - default=False, - ) + name="Relative", + description="Apply relative to the current value (delta)", + default=False, +) def context_path_validate(context, data_path): @@ -150,14 +150,14 @@ class BRUSH_OT_active_index_set(Operator): bl_label = "Set Brush Number" mode = StringProperty( - name="Mode", - description="Paint mode to set brush for", - maxlen=1024, - ) + name="Mode", + description="Paint mode to set brush for", + maxlen=1024, + ) index = IntProperty( - name="Number", - description="Brush number", - ) + name="Number", + description="Brush number", + ) _attr_dict = { "sculpt": "use_paint_sculpt", @@ -188,10 +188,10 @@ class WM_OT_context_set_boolean(Operator): data_path = rna_path_prop value = BoolProperty( - name="Value", - description="Assignment value", - default=True, - ) + name="Value", + description="Assignment value", + default=True, + ) execute = execute_context_assign @@ -204,10 +204,10 @@ class WM_OT_context_set_int(Operator): # same as enum data_path = rna_path_prop value = IntProperty( - name="Value", - description="Assign value", - default=0, - ) + name="Value", + description="Assign value", + default=0, + ) relative = rna_relative_prop execute = execute_context_assign @@ -221,10 +221,10 @@ class WM_OT_context_scale_float(Operator): data_path = rna_path_prop value = FloatProperty( - name="Value", - description="Assign value", - default=1.0, - ) + name="Value", + description="Assign value", + default=1.0, + ) def execute(self, context): data_path = self.data_path @@ -249,15 +249,15 @@ class WM_OT_context_scale_int(Operator): data_path = rna_path_prop value = FloatProperty( - name="Value", - description="Assign value", - default=1.0, - ) + name="Value", + description="Assign value", + default=1.0, + ) always_step = BoolProperty( - name="Always Step", - description="Always adjust the value by a minimum of 1 when 'value' is not 1.0", - default=True, - ) + name="Always Step", + description="Always adjust the value by a minimum of 1 when 'value' is not 1.0", + default=True, + ) def execute(self, context): data_path = self.data_path @@ -292,10 +292,10 @@ class WM_OT_context_set_float(Operator): # same as enum data_path = rna_path_prop value = FloatProperty( - name="Value", - description="Assignment value", - default=0.0, - ) + name="Value", + description="Assignment value", + default=0.0, + ) relative = rna_relative_prop execute = execute_context_assign @@ -309,10 +309,10 @@ class WM_OT_context_set_string(Operator): # same as enum data_path = rna_path_prop value = StringProperty( - name="Value", - description="Assign value", - maxlen=1024, - ) + name="Value", + description="Assign value", + maxlen=1024, + ) execute = execute_context_assign @@ -325,10 +325,10 @@ class WM_OT_context_set_enum(Operator): data_path = rna_path_prop value = StringProperty( - name="Value", - description="Assignment value (as a string)", - maxlen=1024, - ) + name="Value", + description="Assignment value (as a string)", + maxlen=1024, + ) execute = execute_context_assign @@ -341,10 +341,10 @@ class WM_OT_context_set_value(Operator): data_path = rna_path_prop value = StringProperty( - name="Value", - description="Assignment value (as a string)", - maxlen=1024, - ) + name="Value", + description="Assignment value (as a string)", + maxlen=1024, + ) def execute(self, context): data_path = self.data_path @@ -381,15 +381,15 @@ class WM_OT_context_toggle_enum(Operator): data_path = rna_path_prop value_1 = StringProperty( - name="Value", - description="Toggle enum", - maxlen=1024, - ) + name="Value", + description="Toggle enum", + maxlen=1024, + ) value_2 = StringProperty( - name="Value", - description="Toggle enum", - maxlen=1024, - ) + name="Value", + description="Toggle enum", + maxlen=1024, + ) def execute(self, context): data_path = self.data_path @@ -413,7 +413,7 @@ def execute(self, context): class WM_OT_context_cycle_int(Operator): """Set a context value (useful for cycling active material, """ \ - """vertex keys, groups, etc.)""" + """vertex keys, groups, etc.)""" bl_idname = "wm.context_cycle_int" bl_label = "Context Int Cycle" bl_options = {'UNDO', 'INTERNAL'} @@ -506,7 +506,7 @@ def execute(self, context): class WM_OT_context_cycle_array(Operator): """Set a context array value """ \ - """(useful for cycling the active mesh edit mode)""" + """(useful for cycling the active mesh edit mode)""" bl_idname = "wm.context_cycle_array" bl_label = "Context Array Cycle" bl_options = {'UNDO', 'INTERNAL'} @@ -590,15 +590,15 @@ class WM_OT_operator_pie_enum(Operator): bl_label = "Operator Enum Pie" bl_options = {'UNDO', 'INTERNAL'} data_path = StringProperty( - name="Operator", - description="Operator name (in python as string)", - maxlen=1024, - ) + name="Operator", + description="Operator name (in python as string)", + maxlen=1024, + ) prop_string = StringProperty( - name="Property", - description="Property name (as a string)", - maxlen=1024, - ) + name="Property", + description="Property name (as a string)", + maxlen=1024, + ) def invoke(self, context, event): wm = context.window_manager @@ -635,10 +635,10 @@ class WM_OT_context_set_id(Operator): data_path = rna_path_prop value = StringProperty( - name="Value", - description="Assign value", - maxlen=1024, - ) + name="Value", + description="Assign value", + maxlen=1024, + ) def execute(self, context): value = self.value @@ -666,16 +666,16 @@ def execute(self, context): doc_id = StringProperty( - name="Doc ID", - maxlen=1024, - options={'HIDDEN'}, - ) + name="Doc ID", + maxlen=1024, + options={'HIDDEN'}, +) data_path_iter = StringProperty( - description="The data path relative to the context, must point to an iterable") + description="The data path relative to the context, must point to an iterable") data_path_item = StringProperty( - description="The data path from each iterable to the value (int or float)") + description="The data path from each iterable to the value (int or float)") class WM_OT_context_collection_boolean_set(Operator): @@ -688,12 +688,12 @@ class WM_OT_context_collection_boolean_set(Operator): data_path_item = data_path_item type = EnumProperty( - name="Type", - items=(('TOGGLE', "Toggle", ""), - ('ENABLE', "Enable", ""), - ('DISABLE', "Disable", ""), - ), - ) + name="Type", + items=(('TOGGLE', "Toggle", ""), + ('ENABLE', "Enable", ""), + ('DISABLE', "Disable", ""), + ), + ) def execute(self, context): data_path_iter = self.data_path_iter @@ -746,18 +746,18 @@ class WM_OT_context_modal_mouse(Operator): data_path_iter = data_path_iter data_path_item = data_path_item header_text = StringProperty( - name="Header Text", - description="Text to display in header during scale", - ) + name="Header Text", + description="Text to display in header during scale", + ) input_scale = FloatProperty( - description="Scale the mouse movement by this value before applying the delta", - default=0.01, - ) + description="Scale the mouse movement by this value before applying the delta", + default=0.01, + ) invert = BoolProperty( - description="Invert the mouse input", - default=False, - ) + description="Invert the mouse input", + default=False, + ) initial_x = IntProperty(options={'HIDDEN'}) def _values_store(self, context): @@ -852,9 +852,9 @@ class WM_OT_url_open(Operator): bl_options = {'INTERNAL'} url = StringProperty( - name="URL", - description="URL to open", - ) + name="URL", + description="URL to open", + ) def execute(self, context): import webbrowser @@ -869,9 +869,9 @@ class WM_OT_path_open(Operator): bl_options = {'INTERNAL'} filepath = StringProperty( - subtype='FILE_PATH', - options={'SKIP_SAVE'}, - ) + subtype='FILE_PATH', + options={'SKIP_SAVE'}, + ) def execute(self, context): import sys @@ -1055,39 +1055,39 @@ def execute(self, context): rna_path = StringProperty( - name="Property Edit", - description="Property data_path edit", - maxlen=1024, - options={'HIDDEN'}, - ) + name="Property Edit", + description="Property data_path edit", + maxlen=1024, + options={'HIDDEN'}, +) rna_value = StringProperty( - name="Property Value", - description="Property value edit", - maxlen=1024, - ) + name="Property Value", + description="Property value edit", + maxlen=1024, +) rna_property = StringProperty( - name="Property Name", - description="Property name edit", - maxlen=1024, - ) + name="Property Name", + description="Property name edit", + maxlen=1024, +) rna_min = FloatProperty( - name="Min", - default=-10000.0, - precision=3, - ) + name="Min", + default=-10000.0, + precision=3, +) rna_max = FloatProperty( - name="Max", - default=10000.0, - precision=3, - ) + name="Max", + default=10000.0, + precision=3, +) rna_use_soft_limits = BoolProperty( - name="Use Soft Limits", - ) + name="Use Soft Limits", +) class WM_OT_properties_edit(Operator): @@ -1105,8 +1105,8 @@ class WM_OT_properties_edit(Operator): soft_min = rna_min soft_max = rna_max description = StringProperty( - name="Tooltip", - ) + name="Tooltip", + ) def _cmp_props_get(self): # Changing these properties will refresh the UI @@ -1339,9 +1339,9 @@ class WM_OT_properties_context_change(Operator): bl_options = {'INTERNAL'} context = StringProperty( - name="Context", - maxlen=64, - ) + name="Context", + maxlen=64, + ) def execute(self, context): context.space_data.context = self.context @@ -1377,8 +1377,8 @@ class WM_OT_keyconfig_activate(Operator): bl_label = "Activate Keyconfig" filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) def execute(self, context): if bpy.utils.keyconfig_set(self.filepath, report=self.report): @@ -1412,8 +1412,8 @@ class WM_OT_appconfig_activate(Operator): bl_label = "Activate Application Configuration" filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) def execute(self, context): import os @@ -1437,9 +1437,9 @@ class WM_OT_sysinfo(Operator): bl_label = "Save System Info" filepath = StringProperty( - subtype='FILE_PATH', - options={'SKIP_SAVE'}, - ) + subtype='FILE_PATH', + options={'SKIP_SAVE'}, + ) def execute(self, context): import sys_info @@ -1451,7 +1451,7 @@ def invoke(self, context, event): if not self.filepath: self.filepath = os.path.join( - os.path.expanduser("~"), "system-info.txt") + os.path.expanduser("~"), "system-info.txt") wm = context.window_manager wm.fileselect_add(self) @@ -1563,29 +1563,29 @@ class WM_OT_keyconfig_import(Operator): bl_label = "Import Key Configuration..." filepath = StringProperty( - subtype='FILE_PATH', - default="keymap.py", - ) + subtype='FILE_PATH', + default="keymap.py", + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_text = BoolProperty( - name="Filter text", - default=True, - options={'HIDDEN'}, - ) + name="Filter text", + default=True, + options={'HIDDEN'}, + ) filter_python = BoolProperty( - name="Filter python", - default=True, - options={'HIDDEN'}, - ) + name="Filter python", + default=True, + options={'HIDDEN'}, + ) keep_original = BoolProperty( - name="Keep original", - description="Keep original file after copying to configuration folder", - default=True, - ) + name="Keep original", + description="Keep original file after copying to configuration folder", + default=True, + ) def execute(self, context): import os @@ -1629,25 +1629,30 @@ class WM_OT_keyconfig_export(Operator): bl_idname = "wm.keyconfig_export" bl_label = "Export Key Configuration..." + all = BoolProperty( + name="All Keymaps", + default=False, + description="Write all keymaps (not just user modified)", + ) filepath = StringProperty( - subtype='FILE_PATH', - default="keymap.py", - ) + subtype='FILE_PATH', + default="keymap.py", + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_text = BoolProperty( - name="Filter text", - default=True, - options={'HIDDEN'}, - ) + name="Filter text", + default=True, + options={'HIDDEN'}, + ) filter_python = BoolProperty( - name="Filter python", - default=True, - options={'HIDDEN'}, - ) + name="Filter python", + default=True, + options={'HIDDEN'}, + ) def execute(self, context): from bpy_extras import keyconfig_utils @@ -1664,6 +1669,7 @@ def execute(self, context): wm, wm.keyconfigs.active, self.filepath, + all_keymaps=self.all, ) return {'FINISHED'} @@ -1680,9 +1686,9 @@ class WM_OT_keymap_restore(Operator): bl_label = "Restore Key Map(s)" all = BoolProperty( - name="All Keymaps", - description="Restore all keymaps to default", - ) + name="All Keymaps", + description="Restore all keymaps to default", + ) def execute(self, context): wm = context.window_manager @@ -1703,9 +1709,9 @@ class WM_OT_keyitem_restore(Operator): bl_label = "Restore Key Map Item" item_id = IntProperty( - name="Item Identifier", - description="Identifier of the item to remove", - ) + name="Item Identifier", + description="Identifier of the item to remove", + ) @classmethod def poll(cls, context): @@ -1750,9 +1756,9 @@ class WM_OT_keyitem_remove(Operator): bl_label = "Remove Key Map Item" item_id = IntProperty( - name="Item Identifier", - description="Identifier of the item to remove", - ) + name="Item Identifier", + description="Identifier of the item to remove", + ) @classmethod def poll(cls, context): @@ -1818,9 +1824,9 @@ class WM_OT_addon_enable(Operator): bl_label = "Enable Add-on" module = StringProperty( - name="Module", - description="Module name of the add-on to enable", - ) + name="Module", + description="Module name of the add-on to enable", + ) def execute(self, context): import addon_utils @@ -1864,9 +1870,9 @@ class WM_OT_addon_disable(Operator): bl_label = "Disable Add-on" module = StringProperty( - name="Module", - description="Module name of the add-on to disable", - ) + name="Module", + description="Module name of the add-on to disable", + ) def execute(self, context): import addon_utils @@ -1893,22 +1899,22 @@ class WM_OT_theme_install(Operator): bl_label = "Install Theme..." overwrite = BoolProperty( - name="Overwrite", - description="Remove existing theme file if exists", - default=True, - ) + name="Overwrite", + description="Remove existing theme file if exists", + default=True, + ) filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_glob = StringProperty( - default="*.xml", - options={'HIDDEN'}, - ) + default="*.xml", + options={'HIDDEN'}, + ) def execute(self, context): import os @@ -1970,33 +1976,33 @@ class WM_OT_addon_install(Operator): bl_label = "Install Add-on from File..." overwrite = BoolProperty( - name="Overwrite", - description="Remove existing add-ons with the same ID", - default=True, - ) + name="Overwrite", + description="Remove existing add-ons with the same ID", + default=True, + ) target = EnumProperty( - name="Target Path", - items=(('DEFAULT', "Default", ""), - ('PREFS', "User Prefs", "")), - ) + name="Target Path", + items=(('DEFAULT', "Default", ""), + ('PREFS', "User Prefs", "")), + ) filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_python = BoolProperty( - name="Filter python", - default=True, - options={'HIDDEN'}, - ) + name="Filter python", + default=True, + options={'HIDDEN'}, + ) filter_glob = StringProperty( - default="*.py;*.zip", - options={'HIDDEN'}, - ) + default="*.py;*.zip", + options={'HIDDEN'}, + ) def execute(self, context): import addon_utils @@ -2124,9 +2130,9 @@ class WM_OT_addon_remove(Operator): bl_label = "Remove Add-on" module = StringProperty( - name="Module", - description="Module name of the add-on to remove", - ) + name="Module", + description="Module name of the add-on to remove", + ) @staticmethod def path_from_addon(module): @@ -2184,9 +2190,9 @@ class WM_OT_addon_expand(Operator): bl_options = {'INTERNAL'} module = StringProperty( - name="Module", - description="Module name of the add-on to expand", - ) + name="Module", + description="Module name of the add-on to expand", + ) def execute(self, context): import addon_utils @@ -2208,9 +2214,9 @@ class WM_OT_addon_userpref_show(Operator): bl_options = {'INTERNAL'} module = StringProperty( - name="Module", - description="Module name of the add-on to expand", - ) + name="Module", + description="Module name of the add-on to expand", + ) def execute(self, context): import addon_utils @@ -2239,23 +2245,23 @@ class WM_OT_app_template_install(Operator): bl_label = "Install Template from File..." overwrite = BoolProperty( - name="Overwrite", - description="Remove existing template with the same ID", - default=True, - ) + name="Overwrite", + description="Remove existing template with the same ID", + default=True, + ) filepath = StringProperty( - subtype='FILE_PATH', - ) + subtype='FILE_PATH', + ) filter_folder = BoolProperty( - name="Filter folders", - default=True, - options={'HIDDEN'}, - ) + name="Filter folders", + default=True, + options={'HIDDEN'}, + ) filter_glob = StringProperty( - default="*.zip", - options={'HIDDEN'}, - ) + default="*.zip", + options={'HIDDEN'}, + ) def execute(self, context): import traceback diff --git a/release/scripts/startup/bl_ui/properties_data_modifier.py b/release/scripts/startup/bl_ui/properties_data_modifier.py index 290b08342be9..1a80a160ea5b 100644 --- a/release/scripts/startup/bl_ui/properties_data_modifier.py +++ b/release/scripts/startup/bl_ui/properties_data_modifier.py @@ -734,23 +734,25 @@ def PARTICLE_INSTANCE(self, layout, ob, md): row.prop(md, "particle_amount", text="Amount") row.prop(md, "particle_offset", text="Offset") + row = layout.row(align=True) + row.prop(md, "axis", expand=True) + layout.separator() layout.prop(md, "use_path", text="Create Along Paths") - split = layout.split() - split.active = md.use_path - col = split.column() - col.row().prop(md, "axis", expand=True) + col = layout.column() + col.active = md.use_path col.prop(md, "use_preserve_shape") - col = split.column() - col2 = col.column(align=True) - col2.prop(md, "position", slider=True) - col2.prop(md, "random_position", text="Random", slider=True) - col2 = col.column(align=True) - col2.prop(md, "rotation", slider=True) - col2.prop(md, "random_rotation", text="Random", slider=True) + row = col.row(align=True) + row.prop(md, "position", slider=True) + row.prop(md, "random_position", text="Random", slider=True) + row = col.row(align=True) + row.prop(md, "rotation", slider=True) + row.prop(md, "random_rotation", text="Random", slider=True) + + layout.separator() col = layout.column() col.prop_search(md, "index_layer_name", ob.data, "vertex_colors", text="Index Layer") @@ -990,7 +992,7 @@ def SUBSURF(self, layout, ob, md): render = max(scene.cycles.dicing_rate * ob.cycles.dicing_rate, 0.1) preview = max(scene.cycles.preview_dicing_rate * ob.cycles.dicing_rate, 0.1) - col.label("Render %.2f px, Preview %.2f px" % (render, preview)) + col.label(f"Render {render:10.2f} px, Preview {preview:10.2f} px") def SURFACE(self, layout, ob, md): layout.label(text="Settings are inside the Physics tab") diff --git a/release/scripts/startup/bl_ui/properties_physics_rigidbody_constraint.py b/release/scripts/startup/bl_ui/properties_physics_rigidbody_constraint.py index 84a4cbb4b68b..8f6b5b5d8b2c 100644 --- a/release/scripts/startup/bl_ui/properties_physics_rigidbody_constraint.py +++ b/release/scripts/startup/bl_ui/properties_physics_rigidbody_constraint.py @@ -140,6 +140,11 @@ def draw(self, context): sub.prop(rbc, "motor_ang_max_impulse", text="Max Impulse") elif rbc.type in {'GENERIC', 'GENERIC_SPRING'}: + if rbc.type == 'GENERIC_SPRING': + row = layout.row() + row.label("Spring Type:") + row.prop(rbc, "spring_type", text="") + col = layout.column(align=True) col.label("Limits:") diff --git a/release/scripts/startup/bl_ui/properties_render.py b/release/scripts/startup/bl_ui/properties_render.py index a5ce345a93c0..bd5d926d4cdd 100644 --- a/release/scripts/startup/bl_ui/properties_render.py +++ b/release/scripts/startup/bl_ui/properties_render.py @@ -101,10 +101,10 @@ def _draw_framerate_label(*args): custom_framerate = (fps_rate not in {23.98, 24, 25, 29.97, 30, 50, 59.94, 60}) if custom_framerate is True: - fps_label_text = "Custom (%r fps)" % fps_rate + fps_label_text = f"Custom ({fps_rate!r} fps)" show_framerate = True else: - fps_label_text = "%r fps" % fps_rate + fps_label_text = f"{fps_rate!r} fps" show_framerate = (preset_label == "Custom") RENDER_PT_dimensions._frame_rate_args_prev = args diff --git a/release/scripts/startup/bl_ui/properties_texture.py b/release/scripts/startup/bl_ui/properties_texture.py index e74b1f6fdee0..0ab12822d1c9 100644 --- a/release/scripts/startup/bl_ui/properties_texture.py +++ b/release/scripts/startup/bl_ui/properties_texture.py @@ -1475,7 +1475,7 @@ def factor_but(layout, toggle, factor, name): col.prop(tex, "invert", text="Negative") col.prop(tex, "use_stencil") - if isinstance(idblock, Material) or isinstance(idblock, World): + if isinstance(idblock, (Material, World)): col.prop(tex, "default_value", text="DVar", slider=True) if isinstance(idblock, Material): diff --git a/release/scripts/startup/bl_ui/space_image.py b/release/scripts/startup/bl_ui/space_image.py index 9cbb27bcedb0..9a2215969cfb 100644 --- a/release/scripts/startup/bl_ui/space_image.py +++ b/release/scripts/startup/bl_ui/space_image.py @@ -104,7 +104,11 @@ def draw(self, context): ratios = ((1, 8), (1, 4), (1, 2), (1, 1), (2, 1), (4, 1), (8, 1)) for a, b in ratios: - layout.operator("image.view_zoom_ratio", text=iface_("Zoom %d:%d") % (a, b), translate=False).ratio = a / b + layout.operator( + "image.view_zoom_ratio", + text=iface_(f"Zoom {a:d}:{b:d}"), + translate=False, + ).ratio = a / b layout.separator() diff --git a/release/scripts/startup/bl_ui/space_info.py b/release/scripts/startup/bl_ui/space_info.py index 8b39b84dc72f..84e0e813c9f3 100644 --- a/release/scripts/startup/bl_ui/space_info.py +++ b/release/scripts/startup/bl_ui/space_info.py @@ -317,7 +317,6 @@ def draw(self, context): layout.separator() layout.operator("screen.screenshot") - layout.operator("screen.screencast") if sys.platform[:3] == "win": layout.separator() diff --git a/release/scripts/startup/bl_ui/space_sequencer.py b/release/scripts/startup/bl_ui/space_sequencer.py index 0697cf8e56b9..c3ca26efcb79 100644 --- a/release/scripts/startup/bl_ui/space_sequencer.py +++ b/release/scripts/startup/bl_ui/space_sequencer.py @@ -338,9 +338,21 @@ def draw(self, context): layout.operator("sequencer.image_strip_add", text="Image") layout.operator("sequencer.sound_strip_add", text="Sound") + layout.menu("SEQUENCER_MT_add_generate") layout.menu("SEQUENCER_MT_add_effect") +class SEQUENCER_MT_add_generate(Menu): + bl_label = "Generate" + + def draw(self, context): + layout = self.layout + + layout.operator_context = 'INVOKE_REGION_WIN' + layout.operator("sequencer.effect_strip_add", text="Color").type = 'COLOR' + layout.operator("sequencer.effect_strip_add", text="Text").type = 'TEXT' + + class SEQUENCER_MT_add_effect(Menu): bl_label = "Effect Strip" @@ -360,10 +372,8 @@ def draw(self, context): layout.operator("sequencer.effect_strip_add", text="Over Drop").type = 'OVER_DROP' layout.operator("sequencer.effect_strip_add", text="Wipe").type = 'WIPE' layout.operator("sequencer.effect_strip_add", text="Glow").type = 'GLOW' - layout.operator("sequencer.effect_strip_add", text="Text").type = 'TEXT' layout.operator("sequencer.effect_strip_add", text="Color Mix").type = 'COLORMIX' layout.operator("sequencer.effect_strip_add", text="Transform").type = 'TRANSFORM' - layout.operator("sequencer.effect_strip_add", text="Color").type = 'COLOR' layout.operator("sequencer.effect_strip_add", text="Speed Control").type = 'SPEED' layout.operator("sequencer.effect_strip_add", text="Multicam Selector").type = 'MULTICAM' layout.operator("sequencer.effect_strip_add", text="Adjustment Layer").type = 'ADJUSTMENT' @@ -708,11 +718,11 @@ def draw(self, context): if i == strip.multicam_source: sub = row.row(align=True) sub.enabled = False - sub.operator("sequencer.cut_multicam", text="%d" % i).camera = i + sub.operator("sequencer.cut_multicam", text=f"{i:d}").camera = i else: sub_1 = row.row(align=True) sub_1.enabled = True - sub_1.operator("sequencer.cut_multicam", text="%d" % i).camera = i + sub_1.operator("sequencer.cut_multicam", text=f"{i:d}").camera = i if strip.channel > BT_ROW and (strip_channel - 1) % BT_ROW: for i in range(strip.channel, strip_channel + ((BT_ROW + 1 - strip_channel) % BT_ROW)): @@ -1303,6 +1313,7 @@ class SEQUENCER_PT_custom_props(SequencerButtonsPanel, PropertyPanel, Panel): SEQUENCER_MT_marker, SEQUENCER_MT_frame, SEQUENCER_MT_add, + SEQUENCER_MT_add_generate, SEQUENCER_MT_add_effect, SEQUENCER_MT_strip, SEQUENCER_MT_strip_transform, diff --git a/release/scripts/startup/bl_ui/space_text.py b/release/scripts/startup/bl_ui/space_text.py index 98a7da855ca2..fc93956b14b2 100644 --- a/release/scripts/startup/bl_ui/space_text.py +++ b/release/scripts/startup/bl_ui/space_text.py @@ -50,9 +50,9 @@ def draw(self, context): row.prop(st, "show_syntax_highlight", text="") if text: - osl = text.name.endswith(".osl") or text.name.endswith(".oso") + is_osl = text.name.endswith((".osl", ".osl")) - if osl: + if is_osl: row = layout.row() row.operator("node.shader_script_update") else: @@ -66,15 +66,21 @@ def draw(self, context): row = layout.row() if text.filepath: if text.is_dirty: - row.label(text=iface_("File: *%r (unsaved)") % - text.filepath, translate=False) + row.label( + iface_(f"File: *{text.filepath:s} (unsaved)"), + translate=False, + ) else: - row.label(text=iface_("File: %r") % - text.filepath, translate=False) + row.label( + iface_(f"File: {text.filepath:s}"), + translate=False, + ) else: - row.label(text="Text: External" - if text.library - else "Text: Internal") + row.label( + "Text: External" + if text.library + else "Text: Internal" + ) class TEXT_MT_editor_menus(Menu): diff --git a/release/scripts/startup/bl_ui/space_userpref.py b/release/scripts/startup/bl_ui/space_userpref.py index 8db9d63c0aa2..26facd251748 100644 --- a/release/scripts/startup/bl_ui/space_userpref.py +++ b/release/scripts/startup/bl_ui/space_userpref.py @@ -223,6 +223,7 @@ def draw(self, context): col.prop(view, "ui_line_width", text="Line Width") col.prop(view, "show_tooltips") col.prop(view, "show_tooltips_python") + col.prop(view, "show_developer_ui") col.prop(view, "show_object_info", text="Object Info") col.prop(view, "show_large_cursors") col.prop(view, "show_view_name", text="View Name") @@ -493,12 +494,6 @@ def draw(self, context): col.separator() - col.label(text="Screencast:") - col.prop(system, "screencast_fps") - col.prop(system, "screencast_wait_time") - - col.separator() - if bpy.app.build_options.cycles: addon = userpref.addons.get("cycles") if addon is not None: @@ -543,7 +538,10 @@ def draw(self, context): col.separator() col.label(text="Text Draw Options:") - col.prop(system, "use_text_antialiasing") + col.prop(system, "use_text_antialiasing", text="Anti-aliasing") + sub = col.column() + sub.active = system.use_text_antialiasing + sub.prop(system, "text_hinting", text="Hinting") col.separator() @@ -939,7 +937,7 @@ def draw(self, context): col = split.column() for i, ui in enumerate(theme.bone_color_sets, 1): - col.label(text=iface_("Color Set %d:") % i, translate=False) + col.label(iface_(f"Color Set {i:d}"), translate=False) row = col.row() diff --git a/release/scripts/startup/bl_ui/space_view3d.py b/release/scripts/startup/bl_ui/space_view3d.py index 50397a0012ad..275a1a1ab8b3 100644 --- a/release/scripts/startup/bl_ui/space_view3d.py +++ b/release/scripts/startup/bl_ui/space_view3d.py @@ -3395,11 +3395,6 @@ class VIEW3D_PT_view3d_properties(Panel): bl_region_type = 'UI' bl_label = "View" - @classmethod - def poll(cls, context): - view = context.space_data - return (view) - def draw(self, context): layout = self.layout @@ -3443,11 +3438,6 @@ class VIEW3D_PT_view3d_cursor(Panel): bl_region_type = 'UI' bl_label = "3D Cursor" - @classmethod - def poll(cls, context): - view = context.space_data - return (view is not None) - def draw(self, context): layout = self.layout @@ -3462,7 +3452,7 @@ class VIEW3D_PT_view3d_name(Panel): @classmethod def poll(cls, context): - return (context.space_data and context.active_object) + return (context.active_object is not None) def draw(self, context): layout = self.layout @@ -3486,11 +3476,6 @@ class VIEW3D_PT_view3d_display(Panel): bl_label = "Display" bl_options = {'DEFAULT_CLOSED'} - @classmethod - def poll(cls, context): - view = context.space_data - return (view) - def draw(self, context): layout = self.layout @@ -3554,9 +3539,7 @@ class VIEW3D_PT_view3d_stereo(Panel): @classmethod def poll(cls, context): scene = context.scene - - multiview = scene.render.use_multiview - return context.space_data and multiview + return scene.render.use_multiview def draw(self, context): layout = self.layout @@ -3637,11 +3620,6 @@ class VIEW3D_PT_view3d_motion_tracking(Panel): bl_label = "Motion Tracking" bl_options = {'DEFAULT_CLOSED'} - @classmethod - def poll(cls, context): - view = context.space_data - return (view) - def draw_header(self, context): view = context.space_data @@ -3725,7 +3703,7 @@ def draw(self, context): col.label(text="Face Info:") col.prop(mesh, "show_extra_face_area", text="Area") col.prop(mesh, "show_extra_face_angle", text="Angle") - if bpy.app.debug: + if context.user_preferences.view.show_developer_ui: layout.prop(mesh, "show_extra_indices") @@ -3782,8 +3760,7 @@ class VIEW3D_PT_view3d_curvedisplay(Panel): @classmethod def poll(cls, context): - editmesh = context.mode == 'EDIT_CURVE' - return (editmesh) + return (context.mode == 'EDIT_CURVE') def draw(self, context): layout = self.layout @@ -3910,11 +3887,6 @@ class VIEW3D_PT_transform_orientations(Panel): bl_label = "Transform Orientations" bl_options = {'DEFAULT_CLOSED'} - @classmethod - def poll(cls, context): - view = context.space_data - return (view) - def draw(self, context): layout = self.layout diff --git a/release/scripts/startup/keyingsets_builtins.py b/release/scripts/startup/keyingsets_builtins.py index 390c043bb31c..0d904de1d276 100644 --- a/release/scripts/startup/keyingsets_builtins.py +++ b/release/scripts/startup/keyingsets_builtins.py @@ -527,6 +527,8 @@ def doCustomProps(ksi, ks, bone): ksi.addProp(ks, bone, prop) # All properties that are likely to get animated in a character rig, only selected bones. + + class BUILTIN_KSI_WholeCharacterSelected(KeyingSetInfo): """Insert a keyframe for all properties that are likely to get animated in a character rig """ """(only selected bones)""" @@ -557,6 +559,8 @@ def iterator(ksi, context, ks): ############################### # Delta Location + + class BUILTIN_KSI_DeltaLocation(KeyingSetInfo): """Insert keyframes for additional location offset""" bl_label = "Delta Location" @@ -643,6 +647,7 @@ def generate(ksi, context, ks, data): ############################### + # Note that this controls order of options in 'insert keyframe' menu. # Better try to keep some logical order here beyond mere alphabetical one, also because of menu entries shortcut. # See also T51867. diff --git a/release/scripts/startup/nodeitems_builtins.py b/release/scripts/startup/nodeitems_builtins.py index d6f98bf6d0a9..90c6006f2d1e 100644 --- a/release/scripts/startup/nodeitems_builtins.py +++ b/release/scripts/startup/nodeitems_builtins.py @@ -69,12 +69,13 @@ def group_tools_draw(self, layout, context): layout.operator("node.group_ungroup") layout.separator() + # maps node tree type to group node type node_tree_group_type = { 'CompositorNodeTree': 'CompositorNodeGroup', 'ShaderNodeTree': 'ShaderNodeGroup', 'TextureNodeTree': 'TextureNodeGroup', - } +} # generic node group items generator for shader, compositor and texture node groups @@ -161,18 +162,18 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeParticleInfo"), NodeItem("ShaderNodeObjectInfo"), NodeItem("NodeGroupInput", poll=group_input_output_item_poll), - ]), + ]), ShaderOldNodeCategory("SH_OUTPUT", "Output", items=[ NodeItem("ShaderNodeOutput"), NodeItem("NodeGroupOutput", poll=group_input_output_item_poll), - ]), + ]), ShaderOldNodeCategory("SH_OP_COLOR", "Color", items=[ NodeItem("ShaderNodeMixRGB"), NodeItem("ShaderNodeRGBCurve"), NodeItem("ShaderNodeInvert"), NodeItem("ShaderNodeHueSaturation"), NodeItem("ShaderNodeGamma"), - ]), + ]), ShaderOldNodeCategory("SH_OP_VECTOR", "Vector", items=[ NodeItem("ShaderNodeNormal"), NodeItem("ShaderNodeMapping"), @@ -180,7 +181,7 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeVectorCurve"), NodeItem("ShaderNodeVectorTransform"), NodeItem("ShaderNodeNormalMap"), - ]), + ]), ShaderOldNodeCategory("SH_CONVERTOR", "Converter", items=[ NodeItem("ShaderNodeValToRGB"), NodeItem("ShaderNodeRGBToBW"), @@ -191,12 +192,12 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeCombineRGB"), NodeItem("ShaderNodeSeparateHSV"), NodeItem("ShaderNodeCombineHSV"), - ]), + ]), ShaderOldNodeCategory("SH_GROUP", "Group", items=node_group_items), ShaderOldNodeCategory("SH_LAYOUT", "Layout", items=[ NodeItem("NodeFrame"), NodeItem("NodeReroute"), - ]), + ]), # New Shader Nodes (Cycles) ShaderNewNodeCategory("SH_NEW_INPUT", "Input", items=[ @@ -219,14 +220,14 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeUVMap"), NodeItem("ShaderNodeUVAlongStroke", poll=line_style_shader_nodes_poll), NodeItem("NodeGroupInput", poll=group_input_output_item_poll), - ]), + ]), ShaderNewNodeCategory("SH_NEW_OUTPUT", "Output", items=[ NodeItem("ShaderNodeOutputMaterial", poll=object_shader_nodes_poll), NodeItem("ShaderNodeOutputLamp", poll=object_shader_nodes_poll), NodeItem("ShaderNodeOutputWorld", poll=world_shader_nodes_poll), NodeItem("ShaderNodeOutputLineStyle", poll=line_style_shader_nodes_poll), NodeItem("NodeGroupOutput", poll=group_input_output_item_poll), - ]), + ]), ShaderNewNodeCategory("SH_NEW_SHADER", "Shader", items=[ NodeItem("ShaderNodeMixShader"), NodeItem("ShaderNodeAddShader"), @@ -248,7 +249,8 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeVolumeAbsorption"), NodeItem("ShaderNodeVolumeScatter"), NodeItem("ShaderNodeVolumePrincipled"), - ]), + NodeItem("ShaderNodeBsdfHairPrincipled", poll=object_shader_nodes_poll) + ]), ShaderNewNodeCategory("SH_NEW_TEXTURE", "Texture", items=[ NodeItem("ShaderNodeTexImage"), NodeItem("ShaderNodeTexEnvironment"), @@ -263,7 +265,7 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeTexBrick"), NodeItem("ShaderNodeTexPointDensity"), NodeItem("ShaderNodeTexIES"), - ]), + ]), ShaderNewNodeCategory("SH_NEW_OP_COLOR", "Color", items=[ NodeItem("ShaderNodeMixRGB"), NodeItem("ShaderNodeRGBCurve"), @@ -272,7 +274,7 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeHueSaturation"), NodeItem("ShaderNodeGamma"), NodeItem("ShaderNodeBrightContrast"), - ]), + ]), ShaderNewNodeCategory("SH_NEW_OP_VECTOR", "Vector", items=[ NodeItem("ShaderNodeMapping"), NodeItem("ShaderNodeBump"), @@ -283,7 +285,7 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeParallax"), NodeItem("ShaderNodeVectorCurve"), NodeItem("ShaderNodeVectorTransform"), - ]), + ]), ShaderNewNodeCategory("SH_NEW_CONVERTOR", "Converter", items=[ NodeItem("ShaderNodeMath"), NodeItem("ShaderNodeValToRGB"), @@ -297,16 +299,16 @@ def object_shader_nodes_poll(context): NodeItem("ShaderNodeCombineHSV"), NodeItem("ShaderNodeWavelength"), NodeItem("ShaderNodeBlackbody"), - ]), + ]), ShaderNewNodeCategory("SH_NEW_SCRIPT", "Script", items=[ NodeItem("ShaderNodeScript"), - ]), + ]), ShaderNewNodeCategory("SH_NEW_GROUP", "Group", items=node_group_items), ShaderNewNodeCategory("SH_NEW_LAYOUT", "Layout", items=[ NodeItem("NodeFrame"), NodeItem("NodeReroute"), - ]), - ] + ]), +] compositor_node_categories = [ # Compositor Nodes @@ -322,7 +324,7 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeTime"), NodeItem("CompositorNodeTrackPos"), NodeItem("NodeGroupInput", poll=group_input_output_item_poll), - ]), + ]), CompositorNodeCategory("CMP_OUTPUT", "Output", items=[ NodeItem("CompositorNodeComposite"), NodeItem("CompositorNodeViewer"), @@ -330,7 +332,7 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeOutputFile"), NodeItem("CompositorNodeLevels"), NodeItem("NodeGroupOutput", poll=group_input_output_item_poll), - ]), + ]), CompositorNodeCategory("CMP_OP_COLOR", "Color", items=[ NodeItem("CompositorNodeMixRGB"), NodeItem("CompositorNodeAlphaOver"), @@ -344,7 +346,7 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeColorCorrection"), NodeItem("CompositorNodeTonemap"), NodeItem("CompositorNodeZcombine"), - ]), + ]), CompositorNodeCategory("CMP_CONVERTOR", "Converter", items=[ NodeItem("CompositorNodeMath"), NodeItem("CompositorNodeValToRGB"), @@ -361,7 +363,7 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeSepYCCA"), NodeItem("CompositorNodeCombYCCA"), NodeItem("CompositorNodeSwitchView"), - ]), + ]), CompositorNodeCategory("CMP_OP_FILTER", "Filter", items=[ NodeItem("CompositorNodeBlur"), NodeItem("CompositorNodeBilateralblur"), @@ -376,14 +378,14 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeDBlur"), NodeItem("CompositorNodePixelate"), NodeItem("CompositorNodeSunBeams"), - ]), + ]), CompositorNodeCategory("CMP_OP_VECTOR", "Vector", items=[ NodeItem("CompositorNodeNormal"), NodeItem("CompositorNodeMapValue"), NodeItem("CompositorNodeMapRange"), NodeItem("CompositorNodeNormalize"), NodeItem("CompositorNodeCurveVec"), - ]), + ]), CompositorNodeCategory("CMP_MATTE", "Matte", items=[ NodeItem("CompositorNodeKeying"), NodeItem("CompositorNodeKeyingScreen"), @@ -397,7 +399,8 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeChromaMatte"), NodeItem("CompositorNodeColorMatte"), NodeItem("CompositorNodeDoubleEdgeMask"), - ]), + NodeItem("CompositorNodeCryptomatte"), + ]), CompositorNodeCategory("CMP_DISTORT", "Distort", items=[ NodeItem("CompositorNodeScale"), NodeItem("CompositorNodeLensdist"), @@ -412,14 +415,14 @@ def object_shader_nodes_poll(context): NodeItem("CompositorNodeStabilize"), NodeItem("CompositorNodePlaneTrackDeform"), NodeItem("CompositorNodeCornerPin"), - ]), + ]), CompositorNodeCategory("CMP_GROUP", "Group", items=node_group_items), CompositorNodeCategory("CMP_LAYOUT", "Layout", items=[ NodeItem("NodeFrame"), NodeItem("NodeReroute"), NodeItem("CompositorNodeSwitch"), - ]), - ] + ]), +] texture_node_categories = [ # Texture Nodes @@ -429,12 +432,12 @@ def object_shader_nodes_poll(context): NodeItem("TextureNodeTexture"), NodeItem("TextureNodeImage"), NodeItem("NodeGroupInput", poll=group_input_output_item_poll), - ]), + ]), TextureNodeCategory("TEX_OUTPUT", "Output", items=[ NodeItem("TextureNodeOutput"), NodeItem("TextureNodeViewer"), NodeItem("NodeGroupOutput", poll=group_input_output_item_poll), - ]), + ]), TextureNodeCategory("TEX_OP_COLOR", "Color", items=[ NodeItem("TextureNodeMixRGB"), NodeItem("TextureNodeCurveRGB"), @@ -442,11 +445,11 @@ def object_shader_nodes_poll(context): NodeItem("TextureNodeHueSaturation"), NodeItem("TextureNodeCompose"), NodeItem("TextureNodeDecompose"), - ]), + ]), TextureNodeCategory("TEX_PATTERN", "Pattern", items=[ NodeItem("TextureNodeChecker"), NodeItem("TextureNodeBricks"), - ]), + ]), TextureNodeCategory("TEX_TEXTURE", "Textures", items=[ NodeItem("TextureNodeTexNoise"), NodeItem("TextureNodeTexDistNoise"), @@ -458,26 +461,26 @@ def object_shader_nodes_poll(context): NodeItem("TextureNodeTexWood"), NodeItem("TextureNodeTexMusgrave"), NodeItem("TextureNodeTexStucci"), - ]), + ]), TextureNodeCategory("TEX_CONVERTOR", "Converter", items=[ NodeItem("TextureNodeMath"), NodeItem("TextureNodeValToRGB"), NodeItem("TextureNodeRGBToBW"), NodeItem("TextureNodeValToNor"), NodeItem("TextureNodeDistance"), - ]), + ]), TextureNodeCategory("TEX_DISTORT", "Distort", items=[ NodeItem("TextureNodeScale"), NodeItem("TextureNodeTranslate"), NodeItem("TextureNodeRotate"), NodeItem("TextureNodeAt"), - ]), + ]), TextureNodeCategory("TEX_GROUP", "Group", items=node_group_items), TextureNodeCategory("TEX_LAYOUT", "Layout", items=[ NodeItem("NodeFrame"), NodeItem("NodeReroute"), - ]), - ] + ]), +] def register(): diff --git a/release/scripts/templates_py/addon_add_object.py b/release/scripts/templates_py/addon_add_object.py index 56e6e79b94ff..b74c0f8ee25e 100644 --- a/release/scripts/templates_py/addon_add_object.py +++ b/release/scripts/templates_py/addon_add_object.py @@ -8,7 +8,7 @@ "warning": "", "wiki_url": "", "category": "Add Mesh", - } +} import bpy @@ -22,11 +22,12 @@ def add_object(self, context): scale_x = self.scale.x scale_y = self.scale.y - verts = [Vector((-1 * scale_x, 1 * scale_y, 0)), - Vector((1 * scale_x, 1 * scale_y, 0)), - Vector((1 * scale_x, -1 * scale_y, 0)), - Vector((-1 * scale_x, -1 * scale_y, 0)), - ] + verts = [ + Vector((-1 * scale_x, 1 * scale_y, 0)), + Vector((1 * scale_x, 1 * scale_y, 0)), + Vector((1 * scale_x, -1 * scale_y, 0)), + Vector((-1 * scale_x, -1 * scale_y, 0)), + ] edges = [] faces = [[0, 1, 2, 3]] @@ -45,11 +46,11 @@ class OBJECT_OT_add_object(Operator, AddObjectHelper): bl_options = {'REGISTER', 'UNDO'} scale = FloatVectorProperty( - name="scale", - default=(1.0, 1.0, 1.0), - subtype='TRANSLATION', - description="scaling", - ) + name="scale", + default=(1.0, 1.0, 1.0), + subtype='TRANSLATION', + description="scaling", + ) def execute(self, context): @@ -72,7 +73,7 @@ def add_object_manual_map(): url_manual_prefix = "https://docs.blender.org/manual/en/dev/" url_manual_mapping = ( ("bpy.ops.mesh.add_object", "editors/3dview/object"), - ) + ) return url_manual_prefix, url_manual_mapping diff --git a/release/scripts/templates_py/background_job.py b/release/scripts/templates_py/background_job.py index ddd8ce1384e6..2f444641a512 100644 --- a/release/scripts/templates_py/background_job.py +++ b/release/scripts/templates_py/background_job.py @@ -73,21 +73,27 @@ def main(): # When --help or no args are given, print this help usage_text = ( - "Run blender in background mode with this script:" - " blender --background --python " + __file__ + " -- [options]" - ) + "Run blender in background mode with this script:" + " blender --background --python " + __file__ + " -- [options]" + ) parser = argparse.ArgumentParser(description=usage_text) # Example utility, add some text and renders or saves it (with options) # Possible types are: string, int, long, choice, float and complex. - parser.add_argument("-t", "--text", dest="text", type=str, required=True, - help="This text will be used to render an image") - - parser.add_argument("-s", "--save", dest="save_path", metavar='FILE', - help="Save the generated file to the specified path") - parser.add_argument("-r", "--render", dest="render_path", metavar='FILE', - help="Render an image to the specified path") + parser.add_argument( + "-t", "--text", dest="text", type=str, required=True, + help="This text will be used to render an image", + ) + + parser.add_argument( + "-s", "--save", dest="save_path", metavar='FILE', + help="Save the generated file to the specified path", + ) + parser.add_argument( + "-r", "--render", dest="render_path", metavar='FILE', + help="Render an image to the specified path", + ) args = parser.parse_args(argv) # In this example we wont use the args diff --git a/release/scripts/templates_py/batch_export.py b/release/scripts/templates_py/batch_export.py index 6c77c5d6a1ab..0fc888a2d4e9 100644 --- a/release/scripts/templates_py/batch_export.py +++ b/release/scripts/templates_py/batch_export.py @@ -28,7 +28,7 @@ bpy.ops.export_scene.fbx(filepath=fn + ".fbx", use_selection=True) - ## Can be used for multiple formats + # Can be used for multiple formats # bpy.ops.export_scene.x3d(filepath=fn + ".x3d", use_selection=True) obj.select = False diff --git a/release/scripts/templates_py/custom_nodes.py b/release/scripts/templates_py/custom_nodes.py index 8ca748c1d660..23d8ee55e725 100644 --- a/release/scripts/templates_py/custom_nodes.py +++ b/release/scripts/templates_py/custom_nodes.py @@ -124,6 +124,8 @@ def draw_label(self): # our own base class with an appropriate poll function, # so the categories only show up in our own tree type + + class MyNodeCategory(NodeCategory): @classmethod def poll(cls, context): @@ -159,6 +161,7 @@ def poll(cls, context): MyCustomNode, ) + def register(): from bpy.utils import register_class for cls in classes: diff --git a/release/scripts/templates_py/gamelogic.py b/release/scripts/templates_py/gamelogic.py index e589ad43e63f..e3bb4a7bb787 100644 --- a/release/scripts/templates_py/gamelogic.py +++ b/release/scripts/templates_py/gamelogic.py @@ -70,4 +70,5 @@ def main(): print(own["life"]) """ + main() diff --git a/release/scripts/templates_py/gamelogic_simple.py b/release/scripts/templates_py/gamelogic_simple.py index dbfcf948b185..31cb18857176 100644 --- a/release/scripts/templates_py/gamelogic_simple.py +++ b/release/scripts/templates_py/gamelogic_simple.py @@ -14,4 +14,5 @@ def main(): else: cont.deactivate(actu) + main() diff --git a/release/scripts/templates_py/operator_file_export.py b/release/scripts/templates_py/operator_file_export.py index 38c880698454..8a1eb4ae54cd 100644 --- a/release/scripts/templates_py/operator_file_export.py +++ b/release/scripts/templates_py/operator_file_export.py @@ -26,26 +26,28 @@ class ExportSomeData(Operator, ExportHelper): filename_ext = ".txt" filter_glob = StringProperty( - default="*.txt", - options={'HIDDEN'}, - maxlen=255, # Max internal buffer length, longer would be clamped. - ) + default="*.txt", + options={'HIDDEN'}, + maxlen=255, # Max internal buffer length, longer would be clamped. + ) # List of operator properties, the attributes will be assigned # to the class instance from the operator settings before calling. use_setting = BoolProperty( - name="Example Boolean", - description="Example Tooltip", - default=True, - ) + name="Example Boolean", + description="Example Tooltip", + default=True, + ) type = EnumProperty( - name="Example Enum", - description="Choose between two items", - items=(('OPT_A', "First Option", "Description one"), - ('OPT_B', "Second Option", "Description two")), - default='OPT_A', - ) + name="Example Enum", + description="Choose between two items", + items=( + ('OPT_A', "First Option", "Description one"), + ('OPT_B', "Second Option", "Description two"), + ), + default='OPT_A', + ) def execute(self, context): return write_some_data(context, self.filepath, self.use_setting) diff --git a/release/scripts/templates_py/operator_file_import.py b/release/scripts/templates_py/operator_file_import.py index 0ec57544f3d4..9856b6a90408 100644 --- a/release/scripts/templates_py/operator_file_import.py +++ b/release/scripts/templates_py/operator_file_import.py @@ -29,26 +29,28 @@ class ImportSomeData(Operator, ImportHelper): filename_ext = ".txt" filter_glob = StringProperty( - default="*.txt", - options={'HIDDEN'}, - maxlen=255, # Max internal buffer length, longer would be clamped. - ) + default="*.txt", + options={'HIDDEN'}, + maxlen=255, # Max internal buffer length, longer would be clamped. + ) # List of operator properties, the attributes will be assigned # to the class instance from the operator settings before calling. use_setting = BoolProperty( - name="Example Boolean", - description="Example Tooltip", - default=True, - ) + name="Example Boolean", + description="Example Tooltip", + default=True, + ) type = EnumProperty( - name="Example Enum", - description="Choose between two items", - items=(('OPT_A', "First Option", "Description one"), - ('OPT_B', "Second Option", "Description two")), - default='OPT_A', - ) + name="Example Enum", + description="Choose between two items", + items=( + ('OPT_A', "First Option", "Description one"), + ('OPT_B', "Second Option", "Description two"), + ), + default='OPT_A', + ) def execute(self, context): return read_some_data(context, self.filepath, self.use_setting) diff --git a/release/scripts/templates_py/operator_mesh_add.py b/release/scripts/templates_py/operator_mesh_add.py index 3231214c7738..407956a0fdaa 100644 --- a/release/scripts/templates_py/operator_mesh_add.py +++ b/release/scripts/templates_py/operator_mesh_add.py @@ -8,23 +8,25 @@ def add_box(width, height, depth): no actual mesh data creation is done here. """ - verts = [(+1.0, +1.0, -1.0), - (+1.0, -1.0, -1.0), - (-1.0, -1.0, -1.0), - (-1.0, +1.0, -1.0), - (+1.0, +1.0, +1.0), - (+1.0, -1.0, +1.0), - (-1.0, -1.0, +1.0), - (-1.0, +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), - (4, 0, 3, 7), - ] + verts = [ + (+1.0, +1.0, -1.0), + (+1.0, -1.0, -1.0), + (-1.0, -1.0, -1.0), + (-1.0, +1.0, -1.0), + (+1.0, +1.0, +1.0), + (+1.0, -1.0, +1.0), + (-1.0, -1.0, +1.0), + (-1.0, +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), + (4, 0, 3, 7), + ] # apply size for i, v in enumerate(verts): @@ -48,50 +50,51 @@ class AddBox(bpy.types.Operator): bl_options = {'REGISTER', 'UNDO'} width = FloatProperty( - name="Width", - description="Box Width", - min=0.01, max=100.0, - default=1.0, - ) + name="Width", + description="Box Width", + min=0.01, max=100.0, + default=1.0, + ) height = FloatProperty( - name="Height", - description="Box Height", - min=0.01, max=100.0, - default=1.0, - ) + name="Height", + description="Box Height", + min=0.01, max=100.0, + default=1.0, + ) depth = FloatProperty( - name="Depth", - description="Box Depth", - min=0.01, max=100.0, - default=1.0, - ) + name="Depth", + description="Box Depth", + min=0.01, max=100.0, + default=1.0, + ) layers = BoolVectorProperty( - name="Layers", - description="Object Layers", - size=20, - options={'HIDDEN', 'SKIP_SAVE'}, - ) + name="Layers", + description="Object Layers", + size=20, + options={'HIDDEN', 'SKIP_SAVE'}, + ) # generic transform props view_align = BoolProperty( - name="Align to View", - default=False, - ) + name="Align to View", + default=False, + ) location = FloatVectorProperty( - name="Location", - subtype='TRANSLATION', - ) + name="Location", + subtype='TRANSLATION', + ) rotation = FloatVectorProperty( - name="Rotation", - subtype='EULER', - ) + name="Rotation", + subtype='EULER', + ) def execute(self, context): - verts_loc, faces = add_box(self.width, - self.height, - self.depth, - ) + verts_loc, faces = add_box( + self.width, + self.height, + self.depth, + ) mesh = bpy.data.meshes.new("Box") @@ -127,6 +130,7 @@ def unregister(): bpy.utils.unregister_class(AddBox) bpy.types.INFO_MT_mesh_add.remove(menu_func) + if __name__ == "__main__": register() diff --git a/release/scripts/templates_py/operator_modal_draw.py b/release/scripts/templates_py/operator_modal_draw.py index d11ddf0b4677..6f75d6c632e4 100644 --- a/release/scripts/templates_py/operator_modal_draw.py +++ b/release/scripts/templates_py/operator_modal_draw.py @@ -75,5 +75,6 @@ def register(): def unregister(): bpy.utils.unregister_class(ModalDrawOperator) + if __name__ == "__main__": register() diff --git a/release/scripts/templates_py/operator_modal_view3d.py b/release/scripts/templates_py/operator_modal_view3d.py index c870bbffdcfa..65bab3489b4b 100644 --- a/release/scripts/templates_py/operator_modal_view3d.py +++ b/release/scripts/templates_py/operator_modal_view3d.py @@ -9,9 +9,9 @@ class ViewOperator(bpy.types.Operator): bl_label = "Simple View Operator" offset = FloatVectorProperty( - name="Offset", - size=3, - ) + name="Offset", + size=3, + ) def execute(self, context): v3d = context.space_data diff --git a/release/scripts/templates_py/ui_menu.py b/release/scripts/templates_py/ui_menu.py index a21e5ed86c87..36391a54f4ec 100644 --- a/release/scripts/templates_py/ui_menu.py +++ b/release/scripts/templates_py/ui_menu.py @@ -42,6 +42,7 @@ def unregister(): bpy.types.INFO_HT_header.remove(draw_item) + if __name__ == "__main__": register() diff --git a/release/scripts/templates_py/ui_menu_simple.py b/release/scripts/templates_py/ui_menu_simple.py index 2129dfd81a44..aaad92d0e193 100644 --- a/release/scripts/templates_py/ui_menu_simple.py +++ b/release/scripts/templates_py/ui_menu_simple.py @@ -19,6 +19,7 @@ def register(): def unregister(): bpy.utils.unregister_class(SimpleCustomMenu) + if __name__ == "__main__": register() diff --git a/release/scripts/templates_py/ui_previews_dynamic_enum.py b/release/scripts/templates_py/ui_previews_dynamic_enum.py index 0cfa232116dc..39a3750bfee6 100644 --- a/release/scripts/templates_py/ui_previews_dynamic_enum.py +++ b/release/scripts/templates_py/ui_previews_dynamic_enum.py @@ -89,19 +89,19 @@ def draw(self, context): def register(): from bpy.types import WindowManager from bpy.props import ( - StringProperty, - EnumProperty, - ) + StringProperty, + EnumProperty, + ) WindowManager.my_previews_dir = StringProperty( - name="Folder Path", - subtype='DIR_PATH', - default="" - ) + name="Folder Path", + subtype='DIR_PATH', + default="" + ) WindowManager.my_previews = EnumProperty( - items=enum_previews_from_directory_items, - ) + items=enum_previews_from_directory_items, + ) # Note that preview collections returned by bpy.utils.previews # are regular Python objects - you can use them to store custom data. diff --git a/release/windows/blendthumb/CMakeLists.txt b/release/windows/blendthumb/CMakeLists.txt index 1e5f5131a36c..f0da43c26141 100644 --- a/release/windows/blendthumb/CMakeLists.txt +++ b/release/windows/blendthumb/CMakeLists.txt @@ -26,17 +26,18 @@ #----------------------------------------------------------------------------- cmake_minimum_required(VERSION 2.8) project(BlendThumb) - + #Bring the headers, such as Student.h into the project include_directories(${ZLIB_INCLUDE}) - + #Can manually add the sources using the set command as follows: -set(SOURCES src/BlenderThumb.cpp - src/BlendThumb.def - src/BlendThumb.rc - src/Dll.cpp +set(SRC + src/BlenderThumb.cpp + src/BlendThumb.def + src/BlendThumb.rc + src/Dll.cpp ) - -add_library(BlendThumb SHARED ${SOURCES}) + +add_library(BlendThumb SHARED ${SRC}) target_link_libraries(BlendThumb ${ZLIB_LIBS}) install (TARGETS BlendThumb DESTINATION bin) diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index c696719e6501..1c7801fb59e3 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -28,4 +28,3 @@ add_subdirectory(blender) if(WITH_GAMEENGINE) add_subdirectory(gameengine) endif() - diff --git a/source/blender/alembic/intern/abc_customdata.cc b/source/blender/alembic/intern/abc_customdata.cc index b98d82f0c7df..f2ae1c831d11 100644 --- a/source/blender/alembic/intern/abc_customdata.cc +++ b/source/blender/alembic/intern/abc_customdata.cc @@ -26,6 +26,7 @@ #include #include +#include extern "C" { #include "DNA_customdata_types.h" @@ -51,6 +52,29 @@ using Alembic::Abc::V2fArraySample; using Alembic::AbcGeom::OV2fGeomParam; using Alembic::AbcGeom::OC4fGeomParam; + +typedef std::unordered_map uv_index_map; + +static inline uint64_t uv_to_hash_key(Imath::V2f v) +{ + /* Convert -0.0f to 0.0f, so bitwise comparison works. */ + if (v.x == 0.0f) { + v.x = 0.0f; + } + if (v.y == 0.0f) { + v.y = 0.0f; + } + + /* Pack floats in 64bit. */ + union { + float xy[2]; + uint64_t key; + } tmp; + tmp.xy[0] = v.x; + tmp.xy[1] = v.y; + return tmp.key; +} + static void get_uvs(const CDStreamConfig &config, std::vector &uvs, std::vector &uvidx, @@ -84,6 +108,9 @@ static void get_uvs(const CDStreamConfig &config, } } else { + uv_index_map idx_map; + int idx_count = 0; + for (int i = 0; i < num_poly; ++i) { MPoly ¤t_poly = polygons[i]; MLoopUV *loopuvpoly = mloopuv_array + current_poly.loopstart + current_poly.totloop; @@ -91,15 +118,15 @@ static void get_uvs(const CDStreamConfig &config, for (int j = 0; j < current_poly.totloop; ++j) { loopuvpoly--; Imath::V2f uv(loopuvpoly->uv[0], loopuvpoly->uv[1]); - - std::vector::iterator it = std::find(uvs.begin(), uvs.end(), uv); - - if (it == uvs.end()) { - uvidx.push_back(uvs.size()); + uint64_t k = uv_to_hash_key(uv); + uv_index_map::iterator it = idx_map.find(k); + if (it == idx_map.end()) { + idx_map[k] = idx_count; uvs.push_back(uv); + uvidx.push_back(idx_count++); } else { - uvidx.push_back(std::distance(uvs.begin(), it)); + uvidx.push_back(it->second); } } } diff --git a/source/blender/alembic/intern/abc_exporter.cc b/source/blender/alembic/intern/abc_exporter.cc index 7e8f4e3cd15c..6c1eeb9854f1 100644 --- a/source/blender/alembic/intern/abc_exporter.cc +++ b/source/blender/alembic/intern/abc_exporter.cc @@ -396,7 +396,7 @@ void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Object *ob, Obje DupliObject *link = static_cast(lb->first); Object *dupli_ob = NULL; Object *dupli_parent = NULL; - + for (; link; link = link->next) { /* This skips things like custom bone shapes. */ if (m_settings.renderable_only && link->no_draw) { @@ -505,7 +505,7 @@ void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Object *ob, Object } createShapeWriter(ob, dupliObParent); - + ListBase *lb = object_duplilist(m_bmain, eval_ctx, m_scene, ob); if (lb) { @@ -563,7 +563,7 @@ void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent) else { name = get_object_dag_path_name(ob, dupliObParent); } - + AbcTransformWriter *xform = getXForm(name); if (!xform) { diff --git a/source/blender/alembic/intern/abc_mesh.h b/source/blender/alembic/intern/abc_mesh.h index 77c352d7cd31..70d92f894d2a 100644 --- a/source/blender/alembic/intern/abc_mesh.h +++ b/source/blender/alembic/intern/abc_mesh.h @@ -81,7 +81,7 @@ class AbcMeshWriter : public AbcObjectWriter { void writeArbGeoParams(DerivedMesh *dm); void getGeoGroups(DerivedMesh *dm, std::map > &geoGroups); - + /* fluid surfaces support */ void getVelocities(DerivedMesh *dm, std::vector &vels); diff --git a/source/blender/avi/AVI_avi.h b/source/blender/avi/AVI_avi.h index 5e9fe378c381..210195234be6 100644 --- a/source/blender/avi/AVI_avi.h +++ b/source/blender/avi/AVI_avi.h @@ -68,7 +68,7 @@ typedef struct _AviList { typedef struct _AviMainHeader { int fcc; - int size; + int size; int MicroSecPerFrame; /* MicroSecPerFrame - timing between frames */ int MaxBytesPerSec; /* MaxBytesPerSec - approx bps system must handle */ int PaddingGranularity; @@ -79,7 +79,7 @@ typedef struct _AviMainHeader { #define AVIF_TRUSTCKTYPE 0x00000800 #define AVIF_WASCAPTUREFILE 0x00010000 /* specially allocated used for capturing real time video */ #define AVIF_COPYRIGHTED 0x00020000 /* contains copyrighted data */ - + int TotalFrames; int InitialFrames; /* InitialFrames - initial frame before interleaving */ int Streams; @@ -91,18 +91,18 @@ typedef struct _AviMainHeader { typedef struct _AviStreamHeader { int fcc; - int size; + int size; int Type; #define AVIST_VIDEO FCC("vids") #define AVIST_AUDIO FCC("auds") #define AVIST_MIDI FCC("mids") #define AVIST_TEXT FCC("txts") - + int Handler; int Flags; #define AVISF_DISABLED 0x00000001 #define AVISF_VIDEO_PALCHANGES 0x00010000 - + short Priority; short Language; int InitialFrames; @@ -121,7 +121,7 @@ typedef struct _AviStreamHeader { typedef struct _AviBitmapInfoHeader { int fcc; - int size; + int size; int Size; int Width; int Height; @@ -149,7 +149,7 @@ typedef struct _AviIndexEntry { int ChunkId; int Flags; #define AVIIF_LIST 0x00000001 -#define AVIIF_KEYFRAME 0x00000010 +#define AVIIF_KEYFRAME 0x00000010 #define AVIIF_NO_TIME 0x00000100 #define AVIIF_COMPRESSOR 0x0FFF0000 int Offset; @@ -178,22 +178,22 @@ typedef struct _AviStreamRec { typedef struct _AviMovie { FILE *fp; - + int type; #define AVI_MOVIE_READ 0 #define AVI_MOVIE_WRITE 1 - + int64_t size; AviMainHeader *header; AviStreamRec *streams; AviIndexEntry *entries; int index_entries; - + int64_t movi_offset; int64_t read_offset; int64_t *offset_table; - + /* Local data goes here */ int interlace; int odd_fields; @@ -214,7 +214,7 @@ typedef enum { /* belongs to the option-setting function. */ typedef enum { AVI_OPTION_WIDTH = 0, - AVI_OPTION_HEIGHT, + AVI_OPTION_HEIGHT, AVI_OPTION_QUALITY, AVI_OPTION_FRAMERATE } AviOption; diff --git a/source/blender/avi/CMakeLists.txt b/source/blender/avi/CMakeLists.txt index 5009bd2a30b3..d019863faa59 100644 --- a/source/blender/avi/CMakeLists.txt +++ b/source/blender/avi/CMakeLists.txt @@ -23,7 +23,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . ../blenlib ../imbuf diff --git a/source/blender/avi/intern/avi.c b/source/blender/avi/intern/avi.c index 6695998fd359..2d8a0b0038f9 100644 --- a/source/blender/avi/intern/avi.c +++ b/source/blender/avi/intern/avi.c @@ -210,7 +210,7 @@ bool AVI_is_avi(char *name) { FILE *fp; int ret; - + fp = BLI_fopen(name, "rb"); if (fp == NULL) return 0; @@ -237,7 +237,7 @@ bool AVI_is_avi(const char *name) AviMainHeader header; AviBitmapInfoHeader bheader; int movie_tracks = 0; - + DEBUG_PRINT("opening movie\n"); movie.type = AVI_MOVIE_READ; @@ -267,7 +267,7 @@ bool AVI_is_avi(const char *name) fclose(movie.fp); return 0; } - + movie.header->MicroSecPerFrame = GET_FCC(movie.fp); movie.header->MaxBytesPerSec = GET_FCC(movie.fp); movie.header->PaddingGranularity = GET_FCC(movie.fp); @@ -292,7 +292,7 @@ bool AVI_is_avi(const char *name) fclose(movie.fp); return 0; } - + movie.streams = (AviStreamRec *) MEM_calloc_arrayN(movie.header->Streams, sizeof(AviStreamRec), "moviestreams"); for (temp = 0; temp < movie.header->Streams; temp++) { @@ -304,7 +304,7 @@ bool AVI_is_avi(const char *name) !(movie.streams[temp].sh.size = GET_FCC(movie.fp))) { DEBUG_PRINT("bad stream header information\n"); - + MEM_freeN(movie.streams); fclose(movie.fp); return 0; @@ -314,7 +314,7 @@ bool AVI_is_avi(const char *name) movie.streams[temp].sh.Handler = GET_FCC(movie.fp); fcca = movie.streams[temp].sh.Handler; - + if (movie.streams[temp].sh.Type == FCC("vids")) { if (fcca == FCC("DIB ") || fcca == FCC("RGB ") || @@ -334,7 +334,7 @@ bool AVI_is_avi(const char *name) } movie_tracks++; } - + movie.streams[temp].sh.Flags = GET_FCC(movie.fp); movie.streams[temp].sh.Priority = GET_TCC(movie.fp); movie.streams[temp].sh.Language = GET_TCC(movie.fp); @@ -365,10 +365,10 @@ bool AVI_is_avi(const char *name) j = movie.streams[temp].sf_size - (sizeof(AviBitmapInfoHeader) - 8); if (j >= 0) { AviBitmapInfoHeader *bi; - + movie.streams[temp].sf = &bheader; bi = (AviBitmapInfoHeader *) movie.streams[temp].sf; - + bi->fcc = FCC("strf"); bi->size = movie.streams[temp].sf_size; bi->Size = GET_FCC(movie.fp); @@ -382,7 +382,7 @@ bool AVI_is_avi(const char *name) bi->YPelsPerMeter = GET_FCC(movie.fp); bi->ClrUsed = GET_FCC(movie.fp); bi->ClrImportant = GET_FCC(movie.fp); - + fcca = bi->Compression; if (movie.streams[temp].format == AVI_FORMAT_AVI_RGB) { @@ -418,7 +418,7 @@ bool AVI_is_avi(const char *name) temp = GET_FCC(movie.fp); if (temp < 0 || ftell(movie.fp) > movie.size) { DEBUG_PRINT("incorrect size in header or error in AVI\n"); - + MEM_freeN(movie.streams); fclose(movie.fp); return 0; @@ -428,19 +428,19 @@ bool AVI_is_avi(const char *name) fseek(movie.fp, -4L, SEEK_CUR); } - + MEM_freeN(movie.streams); fclose(movie.fp); /* at least one video track is needed */ - return (movie_tracks != 0); + return (movie_tracks != 0); } AviError AVI_open_movie(const char *name, AviMovie *movie) { int temp, fcca, size, j; - + DEBUG_PRINT("opening movie\n"); memset(movie, 0, sizeof(AviMovie)); @@ -470,7 +470,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) DEBUG_PRINT("bad initial header info\n"); return AVI_ERROR_FORMAT; } - + movie->header->MicroSecPerFrame = GET_FCC(movie->fp); movie->header->MaxBytesPerSec = GET_FCC(movie->fp); movie->header->PaddingGranularity = GET_FCC(movie->fp); @@ -494,7 +494,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) DEBUG_PRINT("Number of streams should be in range 1-65536\n"); return AVI_ERROR_FORMAT; } - + movie->streams = (AviStreamRec *) MEM_calloc_arrayN(movie->header->Streams, sizeof(AviStreamRec), "moviestreams"); for (temp = 0; temp < movie->header->Streams; temp++) { @@ -513,7 +513,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) movie->streams[temp].sh.Handler = GET_FCC(movie->fp); fcca = movie->streams[temp].sh.Handler; - + if (movie->streams[temp].sh.Type == FCC("vids")) { if (fcca == FCC("DIB ") || fcca == FCC("RGB ") || @@ -530,7 +530,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) return AVI_ERROR_COMPRESSION; } } - + movie->streams[temp].sh.Flags = GET_FCC(movie->fp); movie->streams[temp].sh.Priority = GET_TCC(movie->fp); movie->streams[temp].sh.Language = GET_TCC(movie->fp); @@ -559,11 +559,11 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) j = movie->streams[temp].sf_size - (sizeof(AviBitmapInfoHeader) - 8); if (j >= 0) { AviBitmapInfoHeader *bi; - + movie->streams[temp].sf = MEM_mallocN(sizeof(AviBitmapInfoHeader), "streamformat"); - + bi = (AviBitmapInfoHeader *) movie->streams[temp].sf; - + bi->fcc = FCC("strf"); bi->size = movie->streams[temp].sf_size; bi->Size = GET_FCC(movie->fp); @@ -577,7 +577,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) bi->YPelsPerMeter = GET_FCC(movie->fp); bi->ClrUsed = GET_FCC(movie->fp); bi->ClrImportant = GET_FCC(movie->fp); - + fcca = bi->Compression; if (movie->streams[temp].format == @@ -617,7 +617,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) } fseek(movie->fp, temp, SEEK_CUR); } - + fseek(movie->fp, -4L, SEEK_CUR); } @@ -645,7 +645,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) movie->movi_offset = ftell(movie->fp); movie->read_offset = movie->movi_offset; - + /* Read in the index if the file has one, otherwise create one */ if (movie->header->Flags & AVIF_HASINDEX) { fseek(movie->fp, size - 4, SEEK_CUR); @@ -668,7 +668,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie) movie->entries[temp].Flags = GET_FCC(movie->fp); movie->entries[temp].Offset = GET_FCC(movie->fp); movie->entries[temp].Size = GET_FCC(movie->fp); - + if (AVI_DEBUG) { printf("Index entry %04d: ChunkId:%s Flags:%d Offset:%d Size:%d\n", temp, fcc_to_char(movie->entries[temp].ChunkId), movie->entries[temp].Flags, @@ -696,7 +696,7 @@ void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream) int cur_frame = -1, i = 0, rewind = 1; void *buffer; - /* Retrieve the record number of the desired frame in the index + /* Retrieve the record number of the desired frame in the index * If a chunk has Size 0 we need to rewind to previous frame */ while (rewind && frame > -1) { i = 0; @@ -732,7 +732,7 @@ void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream) return NULL; } - + buffer = avi_format_convert(movie, stream, buffer, movie->streams[stream].format, format, &size); return buffer; @@ -780,7 +780,7 @@ AviError AVI_open_compress(char *name, AviMovie *movie, int streams, ...) return AVI_ERROR_OPEN; movie->offset_table = (int64_t *) MEM_mallocN((1 + streams * 2) * sizeof(int64_t), "offsettable"); - + for (i = 0; i < 1 + streams * 2; i++) movie->offset_table[i] = -1L; @@ -1009,7 +1009,7 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...) for (stream = 0; stream < movie->header->Streams; stream++) { unsigned int tbuf = 0; - + format = va_arg(ap, AviFormat); buffer = va_arg(ap, void *); size_t size = va_arg(ap, int); @@ -1023,9 +1023,9 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...) chunk.fcc = avi_get_data_id(format, stream); chunk.size = size; - + if (size % 4) chunk.size += 4 - size % 4; - + awrite(movie, &chunk, 1, sizeof(AviChunk), movie->fp, AVI_CHUNK); /* Write the index entry for this data chunk */ diff --git a/source/blender/avi/intern/avi_intern.h b/source/blender/avi/intern/avi_intern.h index b2fec1edfc1b..6261b8140bec 100644 --- a/source/blender/avi/intern/avi_intern.h +++ b/source/blender/avi/intern/avi_intern.h @@ -67,4 +67,3 @@ int avi_get_format_fcc(AviFormat format); int avi_get_format_compression(AviFormat format); #endif - diff --git a/source/blender/avi/intern/avi_mjpeg.c b/source/blender/avi/intern/avi_mjpeg.c index 258426809fb1..3146aebb0d08 100644 --- a/source/blender/avi/intern/avi_mjpeg.c +++ b/source/blender/avi/intern/avi_mjpeg.c @@ -157,7 +157,7 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign { struct jpeg_decompress_struct dinfo; struct jpeg_error_mgr jerr; - + (void)width; /* unused */ numbytes = 0; @@ -182,7 +182,7 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign jpeg_finish_decompress(&dinfo); if (dinfo.output_height >= height) return 0; - + inBuffer += numbytes; jpegmemsrcmgr_build(&dinfo, inBuffer, bufsize - numbytes); @@ -200,7 +200,7 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign } jpeg_finish_decompress(&dinfo); jpeg_destroy_decompress(&dinfo); - + return 1; } @@ -221,7 +221,7 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned jpeg_set_defaults(&cinfo); jpeg_set_colorspace(&cinfo, JCS_YCbCr); - + jpeg_set_quality(&cinfo, quality, true); cinfo.dc_huff_tbl_ptrs[0]->sent_table = true; @@ -267,11 +267,11 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned static void interlace(unsigned char *to, unsigned char *from, int width, int height) { size_t i, rowstride = width * 3; - + for (i = 0; i < height; i++) { if (i & 1) memcpy(&to[i * rowstride], &from[(i / 2 + height / 2) * rowstride], rowstride); - else + else memcpy(&to[i * rowstride], &from[(i / 2) * rowstride], rowstride); } } @@ -279,11 +279,11 @@ static void interlace(unsigned char *to, unsigned char *from, int width, int hei static void deinterlace(int odd, unsigned char *to, unsigned char *from, int width, int height) { size_t i, rowstride = width * 3; - + for (i = 0; i < height; i++) { if ((i & 1) == odd) memcpy(&to[(i / 2 + height / 2) * rowstride], &from[i * rowstride], rowstride); - else + else memcpy(&to[(i / 2) * rowstride], &from[i * rowstride], rowstride); } } @@ -301,19 +301,19 @@ void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffe } deint = Decode_JPEG(buffer, buf, movie->header->Width, movie->header->Height, *size); - + MEM_freeN(buffer); - + if (deint) { buffer = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_from_mjpeg 2"); if (buffer) { interlace(buffer, buf, movie->header->Width, movie->header->Height); } MEM_freeN(buf); - + buf = buffer; } - + return buf; } @@ -321,7 +321,7 @@ void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, { unsigned char *buf; size_t bufsize = *size; - + numbytes = 0; *size = 0; @@ -341,7 +341,7 @@ void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, else { deinterlace(movie->odd_fields, buf, buffer, movie->header->Width, movie->header->Height); MEM_freeN(buffer); - + buffer = buf; buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_to_mjpeg 1"); @@ -390,14 +390,14 @@ static void jpegmemdestmgr_term_destination(j_compress_ptr cinfo) static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, size_t bufsize) { cinfo->dest = MEM_mallocN(sizeof(*(cinfo->dest)), "avi.jpegmemdestmgr_build"); - + cinfo->dest->init_destination = jpegmemdestmgr_init_destination; cinfo->dest->empty_output_buffer = jpegmemdestmgr_empty_output_buffer; cinfo->dest->term_destination = jpegmemdestmgr_term_destination; cinfo->dest->next_output_byte = buffer; cinfo->dest->free_in_buffer = bufsize; - + numbytes = bufsize; } @@ -411,16 +411,16 @@ static void jpegmemsrcmgr_init_source(j_decompress_ptr dinfo) static boolean jpegmemsrcmgr_fill_input_buffer(j_decompress_ptr dinfo) { unsigned char *buf = (unsigned char *) dinfo->src->next_input_byte - 2; - + /* if we get called, must have run out of data */ WARNMS(dinfo, JWRN_JPEG_EOF); - + buf[0] = (JOCTET) 0xFF; buf[1] = (JOCTET) JPEG_EOI; - + dinfo->src->next_input_byte = buf; dinfo->src->bytes_in_buffer = 2; - + return true; } @@ -436,20 +436,20 @@ static void jpegmemsrcmgr_skip_input_data(j_decompress_ptr dinfo, long skipcnt) static void jpegmemsrcmgr_term_source(j_decompress_ptr dinfo) { numbytes -= dinfo->src->bytes_in_buffer; - + MEM_freeN(dinfo->src); } static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, size_t bufsize) { dinfo->src = MEM_mallocN(sizeof(*(dinfo->src)), "avi.jpegmemsrcmgr_build"); - + dinfo->src->init_source = jpegmemsrcmgr_init_source; dinfo->src->fill_input_buffer = jpegmemsrcmgr_fill_input_buffer; dinfo->src->skip_input_data = jpegmemsrcmgr_skip_input_data; dinfo->src->resync_to_restart = jpeg_resync_to_restart; dinfo->src->term_source = jpegmemsrcmgr_term_source; - + dinfo->src->bytes_in_buffer = bufsize; dinfo->src->next_input_byte = buffer; diff --git a/source/blender/avi/intern/avi_options.c b/source/blender/avi/intern/avi_options.c index 47c18831cbdf..d59a8a0118a9 100644 --- a/source/blender/avi/intern/avi_options.c +++ b/source/blender/avi/intern/avi_options.c @@ -49,7 +49,7 @@ AviError AVI_set_compress_option(AviMovie *movie, int option_type, int stream, A int useconds; (void)stream; /* unused */ - + if (movie->header->TotalFrames != 0) /* Can't change params after we have already started writing frames */ return AVI_ERROR_OPTION; @@ -129,4 +129,3 @@ AviError AVI_set_compress_option(AviMovie *movie, int option_type, int stream, A return AVI_ERROR_NONE; } - diff --git a/source/blender/avi/intern/avi_rgb.c b/source/blender/avi/intern/avi_rgb.c index f0baf7c6c143..6997a0d8be44 100644 --- a/source/blender/avi/intern/avi_rgb.c +++ b/source/blender/avi/intern/avi_rgb.c @@ -49,7 +49,7 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf unsigned char *buf; AviBitmapInfoHeader *bi; short bits = 32; - + (void)size; /* unused */ bi = (AviBitmapInfoHeader *) movie->streams[stream].sf; @@ -70,7 +70,7 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf while (y--) { pxl = (unsigned short *) (buffer + y * movie->header->Width * 2); - + #ifdef __BIG_ENDIAN__ pxla = (unsigned char *)pxl; #endif @@ -94,12 +94,12 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf } MEM_freeN(buffer); - + return buf; } else { buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromavirgbbuf"); - + if (buf) { size_t rowstride = movie->header->Width * 3; if ((bits != 16) && (movie->header->Width % 2)) rowstride++; diff --git a/source/blender/avi/intern/avi_rgb32.c b/source/blender/avi/intern/avi_rgb32.c index 051fdba1cd27..f5f48b9eeb45 100644 --- a/source/blender/avi/intern/avi_rgb32.c +++ b/source/blender/avi/intern/avi_rgb32.c @@ -87,7 +87,7 @@ void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, to = buf; from = buffer; size_t i = (size_t)movie->header->Height * (size_t)movie->header->Width; - + while (i--) { memcpy(to, from, 3); to += 4; from += 3; diff --git a/source/blender/blenfont/BLF_api.h b/source/blender/blenfont/BLF_api.h index eafcf74b6116..0a4212ff2337 100644 --- a/source/blender/blenfont/BLF_api.h +++ b/source/blender/blenfont/BLF_api.h @@ -44,9 +44,6 @@ void BLF_exit(void); void BLF_default_dpi(int dpi); void BLF_default_set(int fontid); -void BLF_antialias_set(bool enabled); -bool BLF_antialias_get(void); - void BLF_cache_clear(void); int BLF_load(const char *name) ATTR_NONNULL(); @@ -221,8 +218,11 @@ void BLF_state_print(int fontid); #define BLF_KERNING_DEFAULT (1 << 3) #define BLF_MATRIX (1 << 4) #define BLF_ASPECT (1 << 5) -#define BLF_HINTING (1 << 6) -#define BLF_WORD_WRAP (1 << 7) +#define BLF_WORD_WRAP (1 << 6) +#define BLF_MONOCHROME (1 << 7) /* no-AA */ +#define BLF_HINTING_NONE (1 << 8) +#define BLF_HINTING_SLIGHT (1 << 9) +#define BLF_HINTING_FULL (1 << 10) #define BLF_DRAW_STR_DUMMY_MAX 1024 diff --git a/source/blender/blenfont/intern/blf.c b/source/blender/blenfont/intern/blf.c index 2a8fc14f4ae2..75aabf1f7139 100644 --- a/source/blender/blenfont/intern/blf.c +++ b/source/blender/blenfont/intern/blf.c @@ -84,7 +84,6 @@ static FontBLF *global_font[BLF_MAX_FONT] = {NULL}; static int global_font_default = -1; static int global_font_points = 11; static int global_font_dpi = 72; -static bool global_use_antialias = true; /* XXX, should these be made into global_font_'s too? */ int blf_mono_font = -1; @@ -176,16 +175,6 @@ void BLF_default_set(int fontid) } } -void BLF_antialias_set(bool enabled) -{ - global_use_antialias = enabled; -} - -bool BLF_antialias_get(void) -{ - return global_use_antialias; -} - int BLF_load(const char *name) { FontBLF *font; diff --git a/source/blender/blenfont/intern/blf_glyph.c b/source/blender/blenfont/intern/blf_glyph.c index 9af347908e15..c19c85282325 100644 --- a/source/blender/blenfont/intern/blf_glyph.c +++ b/source/blender/blenfont/intern/blf_glyph.c @@ -221,8 +221,6 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c) GlyphBLF *g; FT_Error err; FT_Bitmap bitmap, tempbitmap; - const bool is_sharp = !BLF_antialias_get(); - int flags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP; FT_BBox bbox; unsigned int key; @@ -243,13 +241,29 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c) return g; } - if (font->flags & BLF_HINTING) - flags &= ~FT_LOAD_NO_HINTING; - - if (is_sharp) + if (font->flags & BLF_MONOCHROME) { err = FT_Load_Glyph(font->face, (FT_UInt)index, FT_LOAD_TARGET_MONO); - else + } + else { + int flags = FT_LOAD_NO_BITMAP; + + if (font->flags & BLF_HINTING_NONE) { + flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING; + } + else if (font->flags & BLF_HINTING_SLIGHT) { + flags |= FT_LOAD_TARGET_LIGHT; + } + else if (font->flags & BLF_HINTING_FULL) { + flags |= FT_LOAD_TARGET_NORMAL; + } + else { + /* Default, hinting disabled until FreeType has been upgraded + * to give good results on all platforms. */ + flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING; + } + err = FT_Load_Glyph(font->face, (FT_UInt)index, flags); + } if (err) { BLI_spin_unlock(font->ft_lib_mutex); @@ -259,7 +273,7 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c) /* get the glyph. */ slot = font->face->glyph; - if (is_sharp) { + if (font->flags & BLF_MONOCHROME) { err = FT_Render_Glyph(slot, FT_RENDER_MODE_MONO); /* Convert result from 1 bit per pixel to 8 bit per pixel */ @@ -288,7 +302,7 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c) g->height = (int)bitmap.rows; if (g->width && g->height) { - if (is_sharp) { + if (font->flags & BLF_MONOCHROME) { /* Font buffer uses only 0 or 1 values, Blender expects full 0..255 range */ int i; for (i = 0; i < (g->width * g->height); i++) { diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 7b3df5771118..89f3431fec8a 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -301,12 +301,12 @@ struct DerivedMesh { CustomData *(*getTessFaceDataLayout)(DerivedMesh * dm); CustomData *(*getLoopDataLayout)(DerivedMesh * dm); CustomData *(*getPolyDataLayout)(DerivedMesh * dm); - + /** Copies all customdata for an element source into dst at index dest */ void (*copyFromVertCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); void (*copyFromEdgeCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); void (*copyFromFaceCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); - + /** Optional grid access for subsurf */ int (*getNumGrids)(DerivedMesh *dm); int (*getGridSize)(DerivedMesh *dm); @@ -315,7 +315,7 @@ struct DerivedMesh { void (*getGridKey)(DerivedMesh *dm, struct CCGKey *key); DMFlagMat *(*getGridFlagMats)(DerivedMesh * dm); unsigned int **(*getGridHidden)(DerivedMesh * dm); - + /** Iterate over each mapped vertex in the derived mesh, calling the * given function with the original vert and the mapped vert's new @@ -397,7 +397,7 @@ struct DerivedMesh { * Also called for *final* editmode DerivedMeshes */ void (*drawEdges)(DerivedMesh *dm, bool drawLooseEdges, bool drawAllEdges); - + /** Draw all loose edges (edges w/ no adjoining faces) */ void (*drawLooseEdges)(DerivedMesh *dm); @@ -478,7 +478,7 @@ struct DerivedMesh { * * NOTE: This routine is optional! */ - void (*drawMappedEdgesInterp)(DerivedMesh *dm, + void (*drawMappedEdgesInterp)(DerivedMesh *dm, DMSetDrawOptions setDrawOptions, DMSetDrawInterpOptions setDrawInterpOptions, void *userData); diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h index 1fda7f07343b..4e6fb89ba895 100644 --- a/source/blender/blenkernel/BKE_action.h +++ b/source/blender/blenkernel/BKE_action.h @@ -69,7 +69,7 @@ void BKE_action_make_local(struct Main *bmain, struct bAction *act, const bool l /* Action API ----------------- */ -/* types of transforms applied to the given item +/* types of transforms applied to the given item * - these are the return falgs for action_get_item_transforms() */ typedef enum eAction_TransformFlags { @@ -79,21 +79,21 @@ typedef enum eAction_TransformFlags { ACT_TRANS_ROT = (1 << 1), /* scaling */ ACT_TRANS_SCALE = (1 << 2), - + /* bbone shape - for all the parameters, provided one is set */ ACT_TRANS_BBONE = (1 << 3), - + /* strictly not a transform, but custom properties are also * quite often used in modern rigs */ ACT_TRANS_PROP = (1 << 4), - + /* all flags */ ACT_TRANS_ONLY = (ACT_TRANS_LOC | ACT_TRANS_ROT | ACT_TRANS_SCALE), ACT_TRANS_ALL = (ACT_TRANS_ONLY | ACT_TRANS_PROP) } eAction_TransformFlags; -/* Return flags indicating which transforms the given object/posechannel has +/* Return flags indicating which transforms the given object/posechannel has * - if 'curves' is provided, a list of links to these curves are also returned * whose nodes WILL NEED FREEING */ @@ -132,7 +132,7 @@ struct bActionGroup *BKE_action_group_find_name(struct bAction *act, const char /* Clear all 'temp' flags on all groups */ void action_groups_clear_tempflags(struct bAction *act); -/* Pose API ----------------- */ +/* Pose API ----------------- */ void BKE_pose_channel_free(struct bPoseChannel *pchan); void BKE_pose_channel_free_ex(struct bPoseChannel *pchan, bool do_id_user); @@ -188,7 +188,7 @@ bool BKE_pose_channel_in_IK_chain(struct Object *ob, struct bPoseChannel *pchan) // XXX to be deprecated for a more general solution in animsys... void framechange_poses_clear_unkeyed(struct Main *bmain); -/* Bone Groups API --------------------- */ +/* Bone Groups API --------------------- */ /* Adds a new bone-group */ struct bActionGroup *BKE_pose_add_group(struct bPose *pose, const char *name); @@ -198,7 +198,7 @@ void BKE_pose_remove_group(struct bPose *pose, struct bActionGroup *grp, const i /* Remove the matching bone-group from its index */ void BKE_pose_remove_group_index(struct bPose *pose, const int index); -/* Assorted Evaluation ----------------- */ +/* Assorted Evaluation ----------------- */ /* Used for the Action Constraint */ void what_does_obaction(struct Object *ob, struct Object *workob, struct bPose *pose, struct bAction *act, char groupname[], float cframe); @@ -216,4 +216,3 @@ void BKE_pose_tag_recalc(struct Main *bmain, struct bPose *pose); #endif #endif - diff --git a/source/blender/blenkernel/BKE_addon.h b/source/blender/blenkernel/BKE_addon.h index e631d1d65376..a463525d6442 100644 --- a/source/blender/blenkernel/BKE_addon.h +++ b/source/blender/blenkernel/BKE_addon.h @@ -51,7 +51,9 @@ void BKE_addon_pref_type_init(void); void BKE_addon_pref_type_free(void); struct bAddon *BKE_addon_new(void); -struct bAddon *BKE_addon_ensure(struct ListBase *addons, const char *module); +struct bAddon *BKE_addon_find(struct ListBase *addon_list, const char *module); +struct bAddon *BKE_addon_ensure(struct ListBase *addon_list, const char *module); +bool BKE_addon_remove_safe(struct ListBase *addon_list, const char *module); void BKE_addon_free(struct bAddon *addon); #endif /* __BKE_ADDON_H__ */ diff --git a/source/blender/blenkernel/BKE_animsys.h b/source/blender/blenkernel/BKE_animsys.h index b25f57b4be25..5cce1e090a93 100644 --- a/source/blender/blenkernel/BKE_animsys.h +++ b/source/blender/blenkernel/BKE_animsys.h @@ -80,10 +80,10 @@ void BKE_animdata_copy_id_action(struct Main *bmain, struct ID *id, const bool s typedef enum eAnimData_MergeCopy_Modes { /* Keep destination action */ ADT_MERGECOPY_KEEP_DST = 0, - + /* Use src action (make a new copy) */ ADT_MERGECOPY_SRC_COPY = 1, - + /* Use src action (but just reference the existing version) */ ADT_MERGECOPY_SRC_REF = 2 } eAnimData_MergeCopy_Modes; diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h index f6de39c897e1..d0386c8b6ca9 100644 --- a/source/blender/blenkernel/BKE_armature.h +++ b/source/blender/blenkernel/BKE_armature.h @@ -53,10 +53,10 @@ typedef struct PoseTarget { typedef struct PoseTree { struct PoseTree *next, *prev; - + int type; /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */ int totchannel; /* number of pose channels */ - + struct ListBase targets; /* list of targets of the tree */ struct bPoseChannel **pchan; /* array of pose channels */ int *parent; /* and their parents */ @@ -211,4 +211,3 @@ void BKE_pose_eval_proxy_copy(struct EvaluationContext *eval_ctx, #endif #endif - diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index 729e7d57e374..0912b8dc6d49 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -28,7 +28,7 @@ * and keep comment above the defines. * Use STRINGIFY() rather than defining with quotes */ #define BLENDER_VERSION 279 -#define BLENDER_SUBVERSION 5 +#define BLENDER_SUBVERSION 6 /* Several breakages with 270, e.g. constraint deg vs rad */ #define BLENDER_MINVERSION 270 #define BLENDER_MINSUBVERSION 6 diff --git a/source/blender/blenkernel/BKE_bmfont.h b/source/blender/blenkernel/BKE_bmfont.h index 64daa311b9a6..3be84c83892c 100644 --- a/source/blender/blenkernel/BKE_bmfont.h +++ b/source/blender/blenkernel/BKE_bmfont.h @@ -59,4 +59,3 @@ void matrixGlyph(struct ImBuf *ibuf, unsigned short unicode, #endif #endif - diff --git a/source/blender/blenkernel/BKE_bmfont_types.h b/source/blender/blenkernel/BKE_bmfont_types.h index a5be0be69970..31513e4b8f17 100644 --- a/source/blender/blenkernel/BKE_bmfont_types.h +++ b/source/blender/blenkernel/BKE_bmfont_types.h @@ -56,4 +56,3 @@ typedef struct bmFont { } bmFont; #endif - diff --git a/source/blender/blenkernel/BKE_brush.h b/source/blender/blenkernel/BKE_brush.h index 9f326d979379..eda1c51bbc21 100644 --- a/source/blender/blenkernel/BKE_brush.h +++ b/source/blender/blenkernel/BKE_brush.h @@ -121,4 +121,3 @@ void BKE_brush_scale_size( void BKE_brush_debug_print_state(struct Brush *br); #endif - diff --git a/source/blender/blenkernel/BKE_bullet.h b/source/blender/blenkernel/BKE_bullet.h index dc522d1b22cf..84fcd20374f7 100644 --- a/source/blender/blenkernel/BKE_bullet.h +++ b/source/blender/blenkernel/BKE_bullet.h @@ -41,4 +41,3 @@ extern struct BulletSoftBody *bsbNew(void); extern void bsbFree(struct BulletSoftBody *sb); #endif - diff --git a/source/blender/blenkernel/BKE_camera.h b/source/blender/blenkernel/BKE_camera.h index 3695aa4a2e10..8eb8ef22b497 100644 --- a/source/blender/blenkernel/BKE_camera.h +++ b/source/blender/blenkernel/BKE_camera.h @@ -152,4 +152,3 @@ bool BKE_camera_multiview_spherical_stereo(struct RenderData *rd, stru #endif #endif - diff --git a/source/blender/blenkernel/BKE_cdderivedmesh.h b/source/blender/blenkernel/BKE_cdderivedmesh.h index 4876461bfe07..761b679983d5 100644 --- a/source/blender/blenkernel/BKE_cdderivedmesh.h +++ b/source/blender/blenkernel/BKE_cdderivedmesh.h @@ -174,4 +174,3 @@ void CDDM_set_mloop(struct DerivedMesh *dm, struct MLoop *mloop); void CDDM_set_mpoly(struct DerivedMesh *dm, struct MPoly *mpoly); #endif - diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h index 6c517bd02df0..6b76ec33c066 100644 --- a/source/blender/blenkernel/BKE_cloth.h +++ b/source/blender/blenkernel/BKE_cloth.h @@ -67,7 +67,7 @@ typedef struct ClothHairData { typedef struct ClothSolverResult { int status; - + int max_iterations, min_iterations; float avg_iterations; float max_error, min_error, avg_error; @@ -138,7 +138,7 @@ typedef struct ClothSpring { int flags; /* defined in BKE_cloth.h, e.g. deactivated due to tearing */ float stiffness; /* stiffness factor from the vertex groups */ float editrestlen; - + /* angular bending spring target and derivatives */ float target[3]; } @@ -203,7 +203,7 @@ struct CollPair; typedef struct ColliderContacts { struct Object *ob; struct CollisionModifierData *collmd; - + struct CollPair *collisions; int totcollisions; } ColliderContacts; @@ -242,4 +242,3 @@ void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3] //////////////////////////////////////////////// #endif - diff --git a/source/blender/blenkernel/BKE_collision.h b/source/blender/blenkernel/BKE_collision.h index 8fedcd4ab065..98dc7d69c0dc 100644 --- a/source/blender/blenkernel/BKE_collision.h +++ b/source/blender/blenkernel/BKE_collision.h @@ -168,4 +168,3 @@ void free_collider_cache(struct ListBase **colliders); ///////////////////////////////////////////////// #endif - diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h index 4e0eb5c65acf..5e7a3f4af725 100644 --- a/source/blender/blenkernel/BKE_constraint.h +++ b/source/blender/blenkernel/BKE_constraint.h @@ -51,10 +51,10 @@ typedef struct bConstraintOb { struct Scene *scene; /* for system time, part of deglobalization, code nicer later with local time (ton) */ struct Object *ob; /* if pchan, then armature that it comes from, otherwise constraint owner */ struct bPoseChannel *pchan; /* pose channel that owns the constraints being evaluated */ - + float matrix[4][4]; /* matrix where constraints are accumulated + solved */ float startmat[4][4]; /* original matrix (before constraint solving) */ - + short type; /* type of owner */ short rotOrder; /* rotation order for constraint owner (as defined in eEulerRotationOrders in BLI_math.h) */ } bConstraintOb; @@ -83,7 +83,7 @@ typedef struct bConstraintTypeInfo { short size; /* size in bytes of the struct */ char name[32]; /* name of constraint in interface */ char structName[32]; /* name of struct for SDNA */ - + /* data management function pointers - special handling */ /* free any data that is allocated separately (optional) */ void (*free_data)(struct bConstraint *con); @@ -93,13 +93,13 @@ typedef struct bConstraintTypeInfo { void (*copy_data)(struct bConstraint *con, struct bConstraint *src); /* set settings for data that will be used for bConstraint.data (memory already allocated using MEM_callocN) */ void (*new_data)(void *cdata); - + /* target handling function pointers */ /* for multi-target constraints: return that list; otherwise make a temporary list (returns number of targets) */ int (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list); /* for single-target constraints only: flush data back to source data, and the free memory used */ void (*flush_constraint_targets)(struct bConstraint *con, struct ListBase *list, bool no_copy); - + /* evaluation */ /* set the ct->matrix for the given constraint target (at the given ctime) */ void (*get_target_matrix)(struct bConstraint *con, struct bConstraintOb *cob, struct bConstraintTarget *ct, float ctime); @@ -156,4 +156,3 @@ void BKE_constraints_solve(struct ListBase *conlist, struct bConstraintOb *cob, #endif #endif - diff --git a/source/blender/blenkernel/BKE_context.h b/source/blender/blenkernel/BKE_context.h index 6de323258bdd..4db365b7307b 100644 --- a/source/blender/blenkernel/BKE_context.h +++ b/source/blender/blenkernel/BKE_context.h @@ -304,6 +304,5 @@ int CTX_data_editable_gpencil_strokes(const bContext *C, ListBase *list); #ifdef __cplusplus } #endif - -#endif +#endif diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h index 175fa1dad799..08cff0c369d1 100644 --- a/source/blender/blenkernel/BKE_curve.h +++ b/source/blender/blenkernel/BKE_curve.h @@ -98,7 +98,7 @@ void BKE_curve_transform(struct Curve *cu, float mat[4][4], const bool do_keys, void BKE_curve_translate(struct Curve *cu, float offset[3], const bool do_keys); void BKE_curve_material_index_remove(struct Curve *cu, int index); void BKE_curve_material_index_clear(struct Curve *cu); -int BKE_curve_material_index_validate(struct Curve *cu); +bool BKE_curve_material_index_validate(struct Curve *cu); void BKE_curve_material_remap(struct Curve *cu, const unsigned int *remap, unsigned int remap_len); ListBase *BKE_curve_nurbs_get(struct Curve *cu); @@ -156,9 +156,14 @@ struct Nurb *BKE_nurb_copy(struct Nurb *src, int pntsu, int pntsv); void BKE_nurb_test2D(struct Nurb *nu); void BKE_nurb_minmax(struct Nurb *nu, bool use_radius, float min[3], float max[3]); - -void BKE_nurb_makeFaces(struct Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv); -void BKE_nurb_makeCurve(struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, int resolu, int stride); +float BKE_nurb_calc_length(const struct Nurb *nu, int resolution); + +void BKE_nurb_makeFaces( + const struct Nurb *nu, float *coord_array, + int rowstride, int resolu, int resolv); +void BKE_nurb_makeCurve( + const struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, + int resolu, int stride); unsigned int BKE_curve_calc_coords_axis_len( const unsigned int bezt_array_len, const unsigned int resolu, diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index 2cdda34b9b50..95718fa04700 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -221,8 +221,8 @@ void CustomData_copy_data_named(const struct CustomData *source, struct CustomData *dest, int source_index, int dest_index, int count); void CustomData_copy_elements(int type, void *src_data_ofs, void *dst_data_ofs, int count); -void CustomData_bmesh_copy_data(const struct CustomData *source, - struct CustomData *dest, void *src_block, +void CustomData_bmesh_copy_data(const struct CustomData *source, + struct CustomData *dest, void *src_block, void **dest_block); /* frees data in a CustomData object @@ -348,9 +348,9 @@ void CustomData_bmesh_free_block_data(struct CustomData *data, void *block); /* copy custom data to/from layers as in mesh/derivedmesh, to editmesh * blocks of data. the CustomData's must not be compatible */ -void CustomData_to_bmesh_block(const struct CustomData *source, +void CustomData_to_bmesh_block(const struct CustomData *source, struct CustomData *dest, int src_index, void **dest_block, bool use_default_init); -void CustomData_from_bmesh_block(const struct CustomData *source, +void CustomData_from_bmesh_block(const struct CustomData *source, struct CustomData *dest, void *src_block, int dest_index); void CustomData_file_write_prepare( @@ -487,4 +487,3 @@ void CustomData_data_transfer(const struct MeshPairRemap *me_remap, const Custom #endif #endif - diff --git a/source/blender/blenkernel/BKE_customdata_file.h b/source/blender/blenkernel/BKE_customdata_file.h index 242897f968ff..d7712c9d6d2b 100644 --- a/source/blender/blenkernel/BKE_customdata_file.h +++ b/source/blender/blenkernel/BKE_customdata_file.h @@ -58,4 +58,3 @@ CDataFileLayer *cdf_layer_find(CDataFile *cdf, int type, const char *name); CDataFileLayer *cdf_layer_add(CDataFile *cdf, int type, const char *name, size_t datasize); #endif /* __BKE_CUSTOMDATA_FILE_H__ */ - diff --git a/source/blender/blenkernel/BKE_depsgraph.h b/source/blender/blenkernel/BKE_depsgraph.h index 0b81cfd4477f..4af4f696b075 100644 --- a/source/blender/blenkernel/BKE_depsgraph.h +++ b/source/blender/blenkernel/BKE_depsgraph.h @@ -177,5 +177,5 @@ bool DAG_is_acyclic(struct Scene *scene); #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_displist.h b/source/blender/blenkernel/BKE_displist.h index f5c6fb37ccc7..a9cfa7b14ed8 100644 --- a/source/blender/blenkernel/BKE_displist.h +++ b/source/blender/blenkernel/BKE_displist.h @@ -1,4 +1,4 @@ -/* +/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or diff --git a/source/blender/blenkernel/BKE_dynamicpaint.h b/source/blender/blenkernel/BKE_dynamicpaint.h index cc1ff1a23754..937ed08a5273 100644 --- a/source/blender/blenkernel/BKE_dynamicpaint.h +++ b/source/blender/blenkernel/BKE_dynamicpaint.h @@ -54,7 +54,7 @@ typedef struct PaintPoint { } PaintPoint; /* heigh field waves */ -typedef struct PaintWavePoint { +typedef struct PaintWavePoint { float height; float velocity; diff --git a/source/blender/blenkernel/BKE_editmesh.h b/source/blender/blenkernel/BKE_editmesh.h index 55a9db9b1e5b..92e311bb53f5 100644 --- a/source/blender/blenkernel/BKE_editmesh.h +++ b/source/blender/blenkernel/BKE_editmesh.h @@ -56,7 +56,7 @@ typedef struct BMEditMesh { /*this is for undoing failed operations*/ struct BMEditMesh *emcopy; int emcopyusers; - + /* we store tessellations as triplets of three loops, * which each define a triangle.*/ struct BMLoop *(*looptris)[3]; diff --git a/source/blender/blenkernel/BKE_effect.h b/source/blender/blenkernel/BKE_effect.h index aa45132cbe98..bb5048a00f02 100644 --- a/source/blender/blenkernel/BKE_effect.h +++ b/source/blender/blenkernel/BKE_effect.h @@ -97,7 +97,7 @@ typedef struct EffectorCache { struct Object *ob; struct ParticleSystem *psys; struct SurfaceModifierData *surmd; - + struct PartDeflect *pd; /* precalculated for guides */ @@ -167,10 +167,10 @@ unsigned int BKE_sim_debug_data_hash_combine(unsigned int kx, unsigned int ky); typedef struct SimDebugElement { unsigned int category_hash; unsigned int hash; - + int type; float color[3]; - + float v1[3], v2[3]; char str[64]; } SimDebugElement; @@ -226,4 +226,3 @@ void BKE_sim_debug_data_clear(void); void BKE_sim_debug_data_clear_category(const char *category); #endif - diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h index 09f5ecce0504..1dfcfd5e54f9 100644 --- a/source/blender/blenkernel/BKE_fcurve.h +++ b/source/blender/blenkernel/BKE_fcurve.h @@ -66,7 +66,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, struct BezTriple *bezt); /* ************** F-Curve Drivers ***************** */ -/* With these iterators for convenience, the variables "tarIndex" and "dtar" can be +/* With these iterators for convenience, the variables "tarIndex" and "dtar" can be * accessed directly from the code using them, but it is not recommended that their * values be changed to point at other slots... */ @@ -77,14 +77,14 @@ void bezt_add_to_cfra_elem(ListBase *lb, struct BezTriple *bezt); DriverTarget *dtar = &dvar->targets[0]; \ int tarIndex = 0; \ for (; tarIndex < MAX_DRIVER_TARGETS; tarIndex++, dtar++) - + /* convenience looper over USED driver targets only */ #define DRIVER_TARGETS_USED_LOOPER(dvar) \ { \ DriverTarget *dtar = &dvar->targets[0]; \ int tarIndex = 0; \ for (; tarIndex < dvar->num_targets; tarIndex++, dtar++) - + /* tidy up for driver targets loopers */ #define DRIVER_TARGETS_LOOPER_END \ } @@ -133,7 +133,7 @@ typedef struct FModifierTypeInfo { short requires; /* eFMI_Requirement_Flags */ char name[64]; /* name of modifier in interface */ char structName[64]; /* name of struct for SDNA */ - + /* data management function pointers - special handling */ /* free any data that is allocated separately (optional) */ void (*free_data)(struct FModifier *fcm); @@ -143,7 +143,7 @@ typedef struct FModifierTypeInfo { void (*new_data)(void *mdata); /* verifies that the modifier settings are valid */ void (*verify_data)(struct FModifier *fcm); - + /* evaluation */ /* evaluate time that the modifier requires the F-Curve to be evaluated at */ float (*evaluate_modifier_time)(struct FCurve *fcu, struct FModifier *fcm, float cvalue, float evaltime); @@ -229,7 +229,7 @@ struct FCurve *iter_step_fcurve(struct FCurve *fcu_iter, const char rna_path[]); /* high level function to get an fcurve from C without having the rna */ struct FCurve *id_data_find_fcurve(ID *id, void *data, struct StructRNA *type, const char *prop_name, int index, bool *r_driven); -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated * e.g. numMatches = list_find_data_fcurves(matches, &act->curves, "pose.bones[", "MyFancyBone"); */ int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, const char *dataName); @@ -290,7 +290,7 @@ float calculate_fcurve(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, flo /* -------- Defines -------- */ -/* Basic signature for F-Curve sample-creation function +/* Basic signature for F-Curve sample-creation function * - fcu: the F-Curve being operated on * - data: pointer to some specific data that may be used by one of the callbacks */ @@ -303,7 +303,7 @@ float fcurve_samplingcb_evalcurve(struct FCurve *fcu, void *data, float evaltime /* -------- Main Methods -------- */ -/* Main API function for creating a set of sampled curve data, given some callback function +/* Main API function for creating a set of sampled curve data, given some callback function * used to retrieve the values to store. */ void fcurve_store_samples(struct FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb); diff --git a/source/blender/blenkernel/BKE_fluidsim.h b/source/blender/blenkernel/BKE_fluidsim.h index 6501c968abcc..af5b146906a8 100644 --- a/source/blender/blenkernel/BKE_fluidsim.h +++ b/source/blender/blenkernel/BKE_fluidsim.h @@ -51,4 +51,3 @@ void fluid_get_bb(struct MVert *mvert, int totvert, float obmat[4][4], void fluid_estimate_memory(struct Object *ob, struct FluidsimSettings *fss, char *value); #endif - diff --git a/source/blender/blenkernel/BKE_font.h b/source/blender/blenkernel/BKE_font.h index bb1f97e83e62..3f6d67f5ded4 100644 --- a/source/blender/blenkernel/BKE_font.h +++ b/source/blender/blenkernel/BKE_font.h @@ -58,7 +58,7 @@ typedef struct EditFontSelBox { typedef struct EditFont { wchar_t *textbuf; struct CharInfo *textbufinfo; - + /* array of rectangles & rotation */ float textcurs[4][2]; EditFontSelBox *selboxes; @@ -68,7 +68,7 @@ typedef struct EditFont { * a copy of these is kept in Curve, but use these in editmode */ int len, pos; int selstart, selend; - + } EditFont; @@ -76,7 +76,7 @@ bool BKE_vfont_is_builtin(struct VFont *vfont); void BKE_vfont_builtin_register(void *mem, int size); void BKE_vfont_free_data(struct VFont *vfont); -void BKE_vfont_free(struct VFont *sc); +void BKE_vfont_free(struct VFont *sc); void BKE_vfont_init(struct VFont *vfont); void BKE_vfont_copy_data(struct Main *bmain, struct VFont *vfont_dst, const struct VFont *vfont_src, const int flag); struct VFont *BKE_vfont_builtin_get(void); @@ -108,4 +108,3 @@ void BKE_vfont_clipboard_get( #endif #endif - diff --git a/source/blender/blenkernel/BKE_freestyle.h b/source/blender/blenkernel/BKE_freestyle.h index 1045fde00394..ab527e9b393a 100644 --- a/source/blender/blenkernel/BKE_freestyle.h +++ b/source/blender/blenkernel/BKE_freestyle.h @@ -70,4 +70,3 @@ void BKE_freestyle_lineset_unique_name(FreestyleConfig *config, FreestyleLineSet #endif #endif - diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index db816cb9e14d..0ce560532d5f 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -50,7 +50,7 @@ typedef struct Global { /* active pointers */ struct Main *main; - + /* strings: lastsaved */ char ima[1024], lib[1024]; /* 1024 = FILE_MAX */ @@ -190,12 +190,12 @@ enum { /* On write, make backup `.blend1`, `.blend2` ... files, when the users preference is enabled */ #define G_FILE_HISTORY (1 << 25) /* BMesh option to save as older mesh format */ -#define G_FILE_MESH_COMPAT (1 << 26) +// #define G_FILE_MESH_COMPAT (1 << 26) /* On write, restore paths after editing them (G_FILE_RELATIVE_REMAP) */ #define G_FILE_SAVE_COPY (1 << 27) #define G_FILE_GLSL_NO_ENV_LIGHTING (1 << 28) -#define G_FILE_FLAGS_RUNTIME (G_FILE_NO_UI | G_FILE_RELATIVE_REMAP | G_FILE_MESH_COMPAT | G_FILE_SAVE_COPY) +#define G_FILE_FLAGS_RUNTIME (G_FILE_NO_UI | G_FILE_RELATIVE_REMAP | G_FILE_SAVE_COPY) /* ENDIAN_ORDER: indicates what endianness the platform where the file was * written had. */ @@ -229,5 +229,5 @@ extern Global G; #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_gpencil.h b/source/blender/blenkernel/BKE_gpencil.h index c7ea73463e3b..3a951b7860d8 100644 --- a/source/blender/blenkernel/BKE_gpencil.h +++ b/source/blender/blenkernel/BKE_gpencil.h @@ -88,7 +88,7 @@ bool gpencil_layer_is_editable(const struct bGPDlayer *gpl); typedef enum eGP_GetFrame_Mode { /* Use the preceeding gp-frame (i.e. don't add anything) */ GP_GETFRAME_USE_PREV = 0, - + /* Add a new empty/blank frame */ GP_GETFRAME_ADD_NEW = 1, /* Make a copy of the active frame */ diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h index 8a2cdd7b37c5..48a00462dd19 100644 --- a/source/blender/blenkernel/BKE_idprop.h +++ b/source/blender/blenkernel/BKE_idprop.h @@ -19,7 +19,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BKE_IDPROP_H__ #define __BKE_IDPROP_H__ diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h index fc018dbfe815..bd9aeb1ab11b 100644 --- a/source/blender/blenkernel/BKE_image.h +++ b/source/blender/blenkernel/BKE_image.h @@ -216,7 +216,7 @@ void BKE_image_verify_viewer_views(const struct RenderData *rd, struct Image *im void BKE_image_user_frame_calc(struct ImageUser *iuser, int cfra, int fieldnr); void BKE_image_user_check_frame_calc(struct ImageUser *iuser, int cfra, int fieldnr); int BKE_image_user_frame_get(const struct ImageUser *iuser, int cfra, int fieldnr, bool *r_is_in_range); -void BKE_image_user_file_path(struct ImageUser *iuser, struct Image *ima, char *path); +void BKE_image_user_file_path(struct ImageUser *iuser, struct Image *ima, char *path); void BKE_image_update_frame(const struct Main *bmain, int cfra); /* sets index offset for multilayer files */ @@ -301,4 +301,3 @@ struct ImBuf *BKE_image_get_first_ibuf(struct Image *image); #endif #endif - diff --git a/source/blender/blenkernel/BKE_ipo.h b/source/blender/blenkernel/BKE_ipo.h index ca86e90f192c..2370908332d9 100644 --- a/source/blender/blenkernel/BKE_ipo.h +++ b/source/blender/blenkernel/BKE_ipo.h @@ -52,4 +52,3 @@ void BKE_ipo_free(struct Ipo *ipo); #endif #endif - diff --git a/source/blender/blenkernel/BKE_library.h b/source/blender/blenkernel/BKE_library.h index 935e90d7ed05..c2b971a91cd1 100644 --- a/source/blender/blenkernel/BKE_library.h +++ b/source/blender/blenkernel/BKE_library.h @@ -200,6 +200,8 @@ void BKE_library_make_local( void BKE_id_tag_set_atomic(struct ID *id, int tag); void BKE_id_tag_clear_atomic(struct ID *id, int tag); +bool BKE_id_is_in_gobal_main(struct ID *id); + /* use when "" is given to new_id() */ #define ID_FALLBACK_NAME N_("Untitled") diff --git a/source/blender/blenkernel/BKE_material.h b/source/blender/blenkernel/BKE_material.h index 431d1df1ff6c..e2f5fb23465a 100644 --- a/source/blender/blenkernel/BKE_material.h +++ b/source/blender/blenkernel/BKE_material.h @@ -115,7 +115,7 @@ void free_matcopybuf(void); void copy_matcopybuf(struct Main *bmain, struct Material *ma); void paste_matcopybuf(struct Main *bmain, struct Material *ma); -/* handle backward compatibility for tface/materials called from doversion */ +/* handle backward compatibility for tface/materials called from doversion */ int do_version_tface(struct Main *main); #ifdef __cplusplus diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index 3d69358960f9..6d2a431f6677 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -347,9 +347,6 @@ void BKE_mesh_recalc_looptri( const struct MVert *mvert, int totloop, int totpoly, struct MLoopTri *mlooptri); -int BKE_mesh_mpoly_to_mface( - struct CustomData *fdata, struct CustomData *ldata, - struct CustomData *pdata, int totface, int totloop, int totpoly); void BKE_mesh_convert_mfaces_to_mpolys(struct Mesh *mesh); void BKE_mesh_do_versions_convert_mfaces_to_mpolys(struct Mesh *mesh); void BKE_mesh_convert_mfaces_to_mpolys_ex( @@ -409,9 +406,9 @@ void BKE_mesh_calc_relative_deform( /* *** mesh_validate.c *** */ -int BKE_mesh_validate(struct Mesh *me, const int do_verbose, const int cddata_check_mask); +bool BKE_mesh_validate(struct Mesh *me, const bool do_verbose, const bool cddata_check_mask); void BKE_mesh_cd_validate(struct Mesh *me); -int BKE_mesh_validate_material_indices(struct Mesh *me); +bool BKE_mesh_validate_material_indices(struct Mesh *me); bool BKE_mesh_validate_arrays( struct Mesh *me, diff --git a/source/blender/blenkernel/BKE_mesh_mapping.h b/source/blender/blenkernel/BKE_mesh_mapping.h index b5b5443574c0..1005a50a2146 100644 --- a/source/blender/blenkernel/BKE_mesh_mapping.h +++ b/source/blender/blenkernel/BKE_mesh_mapping.h @@ -50,8 +50,12 @@ typedef struct UvVertMap { typedef struct UvMapVert { struct UvMapVert *next; - unsigned int f; - unsigned char tfindex, separate, flag; + unsigned int poly_index; + unsigned short loop_of_poly_index; + bool separate; + /* Zero-ed by map creation, left for use by specific areas. Is not + * initialized to anything. */ + unsigned char flag; } UvMapVert; /* UvElement stores per uv information so that we can quickly access information for a uv. @@ -63,9 +67,9 @@ typedef struct UvElement { /* Face the element belongs to */ struct BMLoop *l; /* index in loop. */ - unsigned short tfindex; + unsigned short loop_of_poly_index; /* Whether this element is the first of coincident elements */ - unsigned char separate; + bool separate; /* general use flag */ unsigned char flag; /* If generating element map with island sorting, this stores the island index */ @@ -100,9 +104,9 @@ typedef struct MeshElemMap { /* mapping */ UvVertMap *BKE_mesh_uv_vert_map_create( - struct MPoly *mpoly, struct MLoop *mloop, struct MLoopUV *mloopuv, - unsigned int totpoly, unsigned int totvert, - const float limit[2], const bool selected, const bool use_winding); + const struct MPoly *mpoly, const struct MLoop *mloop, const struct MLoopUV *mloopuv, + unsigned int totpoly, unsigned int totvert, const float limit[2], + const bool selected, const bool use_winding); UvMapVert *BKE_mesh_uv_vert_map_get_vert(UvVertMap *vmap, unsigned int v); void BKE_mesh_uv_vert_map_free(UvVertMap *vmap); diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index e9ce91996e08..2d39ac4d1028 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -197,7 +197,7 @@ typedef struct ModifierTypeInfo { * * The derivedData argument should always be non-NULL; the modifier * should read the object data from the derived object instead of the - * actual object data. + * actual object data. * * The useRenderParams argument indicates if the modifier is being * applied in the service of the renderer which may alter quality @@ -217,7 +217,7 @@ typedef struct ModifierTypeInfo { /* Like applyModifier but called during editmode (for supporting * modifiers). - * + * * The derived object that is returned must support the operations that * are expected from editmode objects. The same qualifications regarding * derivedData apply as for applyModifier. @@ -232,7 +232,7 @@ typedef struct ModifierTypeInfo { /* Initialize new instance data for this modifier type, this function * should set modifier variables to their default values. - * + * * This function is optional. */ void (*initData)(struct ModifierData *md); @@ -273,7 +273,7 @@ typedef struct ModifierTypeInfo { bool (*isDisabled)(struct ModifierData *md, int userRenderParams); /* Add the appropriate relations to the DEP graph depending on the - * modifier data. + * modifier data. * * This function is optional. */ @@ -299,7 +299,7 @@ typedef struct ModifierTypeInfo { /* True when a deform modifier uses normals, the requiredDataMask * cant be used here because that refers to a normal layer where as * in this case we need to know if the deform modifier uses normals. - * + * * this is needed because applying 2 deform modifiers will give the * second modifier bogus normals. * */ @@ -458,4 +458,3 @@ void modwrap_deformVertsEM( float (*vertexCos)[3], int numVerts); #endif - diff --git a/source/blender/blenkernel/BKE_nla.h b/source/blender/blenkernel/BKE_nla.h index 6f0b6d599845..37929bae0426 100644 --- a/source/blender/blenkernel/BKE_nla.h +++ b/source/blender/blenkernel/BKE_nla.h @@ -141,4 +141,3 @@ enum eNlaTime_ConvertModes { float BKE_nla_tweakedit_remap(struct AnimData *adt, float cframe, short mode); #endif - diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index b7e17254c651..d63e7533ec11 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -99,7 +99,7 @@ typedef struct bNodeSocketTemplate { float min, max; int subtype; /* would use PropertySubType but this is a bad level include to use RNA */ int flag; - + /* after this line is used internal only */ struct bNodeSocket *sock; /* used to hold verified socket */ char identifier[64]; /* generated from name */ @@ -110,21 +110,21 @@ typedef struct bNodeSocketTemplate { */ typedef struct bNodeSocketType { char idname[64]; /* identifier name */ - + void (*draw)(struct bContext *C, struct uiLayout *layout, struct PointerRNA *ptr, struct PointerRNA *node_ptr, const char *text); void (*draw_color)(struct bContext *C, struct PointerRNA *ptr, struct PointerRNA *node_ptr, float *r_color); - + void (*interface_draw)(struct bContext *C, struct uiLayout *layout, struct PointerRNA *ptr); void (*interface_draw_color)(struct bContext *C, struct PointerRNA *ptr, float *r_color); void (*interface_register_properties)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct StructRNA *data_srna); void (*interface_init_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock, const char *data_path); void (*interface_verify_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock, const char *data_path); void (*interface_from_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock); - + /* RNA integration */ ExtensionRNA ext_socket; ExtensionRNA ext_interface; - + /* for standard socket types in C */ int type, subtype; } bNodeSocketType; @@ -141,23 +141,23 @@ typedef int (*NodeGPUExecFunction)(struct GPUMaterial *mat, struct bNode *node, typedef struct bNodeType { void *next, *prev; short needs_free; /* set for allocated types that need to be freed */ - + char idname[64]; /* identifier name */ int type; char ui_name[64]; /* MAX_NAME */ char ui_description[256]; int ui_icon; - + float width, minwidth, maxwidth; float height, minheight, maxheight; short nclass, flag, compatibility; - + /* templates for static sockets */ bNodeSocketTemplate *inputs, *outputs; - + char storagename[64]; /* struct name for DNA */ - + /* Main draw function for the node */ void (*draw_nodetype)(const struct bContext *C, struct ARegion *ar, struct SpaceNode *snode, struct bNodeTree *ntree, struct bNode *node, bNodeInstanceKey key); @@ -183,41 +183,41 @@ typedef struct bNodeType { int (*select_area_func)(struct bNode *node, int x, int y); /// Optional tweak area polling (for grabbing). int (*tweak_area_func)(struct bNode *node, int x, int y); - + /// Called when the node is updated in the editor. void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node); /// Check and update if internal ID data has changed. void (*verifyfunc)(struct bNodeTree *ntree, struct bNode *node, struct ID *id); - + /// Initialize a new node instance of this type after creation. void (*initfunc)(struct bNodeTree *ntree, struct bNode *node); /// Free the node instance. void (*freefunc)(struct bNode *node); /// Make a copy of the node instance. void (*copyfunc)(struct bNodeTree *dest_ntree, struct bNode *dest_node, struct bNode *src_node); - + /* Registerable API callback versions, called in addition to C callbacks */ void (*initfunc_api)(const struct bContext *C, struct PointerRNA *ptr); void (*freefunc_api)(struct PointerRNA *ptr); void (*copyfunc_api)(struct PointerRNA *ptr, struct bNode *src_node); - + /* can this node type be added to a node tree */ - int (*poll)(struct bNodeType *ntype, struct bNodeTree *nodetree); + bool (*poll)(struct bNodeType *ntype, struct bNodeTree *nodetree); /* can this node be added to a node tree */ - int (*poll_instance)(struct bNode *node, struct bNodeTree *nodetree); - + bool (*poll_instance)(struct bNode *node, struct bNodeTree *nodetree); + /* optional handling of link insertion */ void (*insert_link)(struct bNodeTree *ntree, struct bNode *node, struct bNodeLink *link); /* Update the internal links list, for muting and disconnect operators. */ void (*update_internal_links)(struct bNodeTree *, struct bNode *node); - + /* **** execution callbacks **** */ NodeInitExecFunction initexecfunc; NodeFreeExecFunction freeexecfunc; NodeExecFunction execfunc; /* gpu */ NodeGPUExecFunction gpufunc; - + /* RNA integration */ ExtensionRNA ext; } bNodeType; @@ -277,13 +277,13 @@ typedef struct bNodeTreeType { char ui_name[64]; char ui_description[256]; int ui_icon; - + /* callbacks */ void (*free_cache)(struct bNodeTree *ntree); void (*free_node_cache)(struct bNodeTree *ntree, struct bNode *node); void (*foreach_nodeclass)(struct Scene *scene, void *calldata, bNodeClassCallback func); /* iteration over all node classes */ /* Check visibility in the node editor */ - int (*poll)(const struct bContext *C, struct bNodeTreeType *ntreetype); + bool (*poll)(const struct bContext *C, struct bNodeTreeType *ntreetype); /* Select a node tree from the context */ void (*get_from_context)(const struct bContext *C, struct bNodeTreeType *ntreetype, struct bNodeTree **r_ntree, struct ID **r_id, struct ID **r_from); @@ -295,11 +295,11 @@ typedef struct bNodeTreeType { /* Tree update. Overrides nodetype->updatetreefunc! */ void (*update)(struct bNodeTree *ntree); - - int (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link); + + bool (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link); void (*node_add_init)(struct bNodeTree *ntree, struct bNode *bnode); - + /* RNA integration */ ExtensionRNA ext; } bNodeTreeType; @@ -794,6 +794,8 @@ struct ShadeResult; #define SH_NODE_DISPLACEMENT 198 #define SH_NODE_VECTOR_DISPLACEMENT 199 #define SH_NODE_VOLUME_PRINCIPLED 200 +/* 201..700 occupied by other node types, continue from 701 */ +#define SH_NODE_BSDF_HAIR_PRINCIPLED 701 #define SH_NODE_OBJECT 1000 #define SH_NODE_TIME 1001 @@ -949,6 +951,7 @@ void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMateria #define CMP_NODE_PLANETRACKDEFORM 320 #define CMP_NODE_CORNERPIN 321 #define CMP_NODE_SWITCH_VIEW 322 +#define CMP_NODE_CRYPTOMATTE 323 /* channel toggles */ #define CMP_CHAN_RGB 1 @@ -1001,6 +1004,11 @@ void ntreeCompositOutputFileUniqueLayer(struct ListBase *list, struct bNodeSocke void ntreeCompositColorBalanceSyncFromLGG(bNodeTree *ntree, bNode *node); void ntreeCompositColorBalanceSyncFromCDL(bNodeTree *ntree, bNode *node); +void ntreeCompositCryptomatteSyncFromAdd(bNodeTree *ntree, bNode *node); +void ntreeCompositCryptomatteSyncFromRemove(bNodeTree *ntree, bNode *node); +struct bNodeSocket *ntreeCompositCryptomatteAddSocket(struct bNodeTree *ntree, struct bNode *node); +int ntreeCompositCryptomatteRemoveSocket(struct bNodeTree *ntree, struct bNode *node); + /** \} */ /* -------------------------------------------------------------------- */ diff --git a/source/blender/blenkernel/BKE_ocean.h b/source/blender/blenkernel/BKE_ocean.h index 7a4c7d670403..3ea104e656aa 100644 --- a/source/blender/blenkernel/BKE_ocean.h +++ b/source/blender/blenkernel/BKE_ocean.h @@ -1,4 +1,4 @@ -/* +/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or @@ -35,7 +35,7 @@ typedef struct OceanResult { float disp[3]; float normal[3]; float foam; - + /* raw eigenvalues/vectors */ float Jminus; float Jplus; @@ -47,25 +47,25 @@ typedef struct OceanCache { struct ImBuf **ibufs_disp; struct ImBuf **ibufs_foam; struct ImBuf **ibufs_norm; - + const char *bakepath; const char *relbase; - + /* precalculated for time range */ float *time; - + /* constant for time range */ float wave_scale; float chop_amount; float foam_coverage; float foam_fade; - + int start; int end; int duration; int resolution_x; int resolution_y; - + int baked; } OceanCache; @@ -93,7 +93,7 @@ struct OceanCache *BKE_ocean_init_cache( int start, int end, float wave_scale, float chop_amount, float foam_coverage, float foam_fade, int resolution); void BKE_ocean_simulate_cache(struct OceanCache *och, int frame); - + void BKE_ocean_bake(struct Ocean *o, struct OceanCache *och, void (*update_cb)(void *, float progress, int *cancel), void *update_cb_data); void BKE_ocean_cache_eval_uv(struct OceanCache *och, struct OceanResult *ocr, int f, float u, float v); void BKE_ocean_cache_eval_ij(struct OceanCache *och, struct OceanResult *ocr, int f, int i, int j); diff --git a/source/blender/blenkernel/BKE_packedFile.h b/source/blender/blenkernel/BKE_packedFile.h index ed6d66906d15..1056c5d2119d 100644 --- a/source/blender/blenkernel/BKE_packedFile.h +++ b/source/blender/blenkernel/BKE_packedFile.h @@ -83,4 +83,3 @@ bool BKE_pack_check(struct ID *id); void BKE_unpack_id(struct Main *bmain, struct ID *id, struct ReportList *reports, int how); #endif - diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h index 253a615712c8..abb9000b024d 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -181,7 +181,7 @@ typedef struct SculptSession { int totvert, totpoly; struct KeyBlock *kb; float *vmask; - + /* Mesh connectivity */ const struct MeshElemMap *pmap; @@ -206,7 +206,7 @@ typedef struct SculptSession { /* Partial redraw */ bool partial_redraw; - + /* Used to cache the render of the active texture */ unsigned int texcache_side, *texcache, texcache_actual; struct ImagePool *tex_pool; diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h index cba92eabb0bf..ddbf40255963 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -60,7 +60,7 @@ struct LinkNode; struct KDTree; struct RNG; struct BVHTreeRay; -struct BVHTreeRayHit; +struct BVHTreeRayHit; struct EdgeHash; #define PARTICLE_COLLISION_MAX_COLLISIONS 10 @@ -192,7 +192,7 @@ typedef struct ParticleCollisionElement { /* values interpolated from original data*/ float x0[3], x1[3], x2[3], p[3]; - + /* results for found intersection point */ float nor[3], vel[3], uv[2]; diff --git a/source/blender/blenkernel/BKE_pbvh.h b/source/blender/blenkernel/BKE_pbvh.h index f619133ee4bc..1fede116193f 100644 --- a/source/blender/blenkernel/BKE_pbvh.h +++ b/source/blender/blenkernel/BKE_pbvh.h @@ -74,7 +74,6 @@ void BKE_pbvh_build_grids(PBVH *bvh, struct CCGElem **grid_elems, struct CCGKey *key, void **gridfaces, struct DMFlagMat *flagmats, unsigned int **grid_hidden); void BKE_pbvh_build_bmesh(PBVH *bvh, struct BMesh *bm, bool smooth_shading, struct BMLog *log, const int cd_vert_node_offset, const int cd_face_node_offset); -void BKE_pbvh_set_ccgdm(PBVH *bvh, struct CCGDerivedMesh *ccgdm); void BKE_pbvh_free(PBVH *bvh); void BKE_pbvh_free_layer_disp(PBVH *bvh); @@ -155,7 +154,6 @@ int BKE_pbvh_count_grid_quads(BLI_bitmap **grid_hidden, /* multires level, only valid for type == PBVH_GRIDS */ void BKE_pbvh_get_grid_key(const PBVH *pbvh, struct CCGKey *key); -struct CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh); /* Only valid for type == PBVH_BMESH */ struct BMesh *BKE_pbvh_get_bmesh(PBVH *pbvh); diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h index c787e8e8ed15..d917a6b55e6b 100644 --- a/source/blender/blenkernel/BKE_property.h +++ b/source/blender/blenkernel/BKE_property.h @@ -49,5 +49,5 @@ void BKE_bproperty_set(struct bProperty *prop, const char *str); void BKE_bproperty_add(struct bProperty *prop, const char *str); /* should really be called '_get_valstr()' or '_as_string()' */ void BKE_bproperty_set_valstr(struct bProperty *prop, char str[MAX_PROPSTRING]); - + #endif diff --git a/source/blender/blenkernel/BKE_report.h b/source/blender/blenkernel/BKE_report.h index 70feff17151d..2175b54a4a17 100644 --- a/source/blender/blenkernel/BKE_report.h +++ b/source/blender/blenkernel/BKE_report.h @@ -74,6 +74,5 @@ bool BKE_report_write_file(const char *filepath, ReportList *reports, const char #ifdef __cplusplus } #endif - -#endif +#endif diff --git a/source/blender/blenkernel/BKE_rigidbody.h b/source/blender/blenkernel/BKE_rigidbody.h index 3c7274ca3c5b..470aae40df9d 100644 --- a/source/blender/blenkernel/BKE_rigidbody.h +++ b/source/blender/blenkernel/BKE_rigidbody.h @@ -29,7 +29,7 @@ * \ingroup blenkernel * \brief API for Blender-side Rigid Body stuff */ - + #ifndef __BKE_RIGIDBODY_H__ #define __BKE_RIGIDBODY_H__ diff --git a/source/blender/blenkernel/BKE_sca.h b/source/blender/blenkernel/BKE_sca.h index 35bcd91a9b17..653fc1afa64a 100644 --- a/source/blender/blenkernel/BKE_sca.h +++ b/source/blender/blenkernel/BKE_sca.h @@ -89,4 +89,3 @@ void BKE_sca_actuators_id_loop(struct ListBase *atclist, SCAActuatorIDFunc func, const char *sca_state_name_get(Object *ob, short bit); #endif - diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index ae809641480e..e85867fcbe71 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -114,6 +114,8 @@ int BKE_scene_camera_switch_update(struct Scene *scene); char *BKE_scene_find_marker_name(struct Scene *scene, int frame); char *BKE_scene_find_last_marker_name(struct Scene *scene, int frame); +int BKE_scene_frame_snap_by_seconds(struct Scene *scene, double interval_in_seconds, int cfra); + /* checks for cycle, returns 1 if it's all OK */ bool BKE_scene_validate_setscene(struct Main *bmain, struct Scene *sce); diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h index 09390ab87760..b33b9e455f10 100644 --- a/source/blender/blenkernel/BKE_screen.h +++ b/source/blender/blenkernel/BKE_screen.h @@ -185,7 +185,7 @@ typedef struct PanelType { int flag; /* verify if the panel should draw or not */ - int (*poll)(const struct bContext *C, struct PanelType *pt); + bool (*poll)(const struct bContext *C, struct PanelType *pt); /* draw header (optional) */ void (*draw_header)(const struct bContext *C, struct Panel *pa); /* draw entirely, view changes should be handled here */ @@ -256,7 +256,7 @@ typedef struct MenuType { const char *description; /* verify if the menu should draw or not */ - int (*poll)(const struct bContext *C, struct MenuType *mt); + bool (*poll)(const struct bContext *C, struct MenuType *mt); /* draw entirely, view changes should be handled here */ void (*draw)(const struct bContext *C, struct Menu *menu); diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h index e00e2403dfc9..c408597de324 100644 --- a/source/blender/blenkernel/BKE_sequencer.h +++ b/source/blender/blenkernel/BKE_sequencer.h @@ -135,38 +135,38 @@ struct SeqEffectHandle { /* constructors & destructor */ /* init is _only_ called on first creation */ void (*init)(struct Sequence *seq); - - /* number of input strips needed + + /* number of input strips needed * (called directly after construction) */ int (*num_inputs)(void); - + /* load is called first time after readblenfile in * get_sequence_effect automatically */ void (*load)(struct Sequence *seq); - + /* duplicate */ void (*copy)(struct Sequence *dst, struct Sequence *src); - + /* destruct */ void (*free)(struct Sequence *seq); - + /* returns: -1: no input needed, * 0: no early out, * 1: out = ibuf1, * 2: out = ibuf2 */ - int (*early_out)(struct Sequence *seq, float facf0, float facf1); - + int (*early_out)(struct Sequence *seq, float facf0, float facf1); + /* stores the y-range of the effect IPO */ void (*store_icu_yrange)(struct Sequence *seq, short adrcode, float *ymin, float *ymax); - + /* stores the default facf0 and facf1 if no IPO is present */ void (*get_default_fac)(struct Sequence *seq, float cfra, float *facf0, float *facf1); - + /* execute the effect * sequence effects are only required to either support * float-rects or byte-rects * (mixed cases are handled one layer up...) */ - + struct ImBuf * (*execute)(const SeqRenderData *context, struct Sequence *seq, float cfra, float facf0, float facf1, struct ImBuf *ibuf1, struct ImBuf *ibuf2, struct ImBuf *ibuf3); @@ -273,7 +273,7 @@ void BKE_sequencer_cache_cleanup(void); /* returned ImBuf is properly refed and has to be freed */ struct ImBuf *BKE_sequencer_cache_get(const SeqRenderData *context, struct Sequence *seq, float cfra, eSeqStripElemIBuf type); -/* passed ImBuf is properly refed, so ownership is *not* +/* passed ImBuf is properly refed, so ownership is *not* * transferred to the cache. * you can pass the same ImBuf multiple times to the cache without problems. */ @@ -392,7 +392,7 @@ typedef struct SeqLoadInfo { /* seq_dupli' flags */ -#define SEQ_DUPE_UNIQUE_NAME (1 << 0) +#define SEQ_DUPE_UNIQUE_NAME (1 << 0) /* WARNING: does NOT work when duplicating Meta strips! */ #define SEQ_DUPE_CONTEXT (1 << 1) #define SEQ_DUPE_ANIM (1 << 2) #define SEQ_DUPE_ALL (1 << 3) /* otherwise only selected are copied */ diff --git a/source/blender/blenkernel/BKE_softbody.h b/source/blender/blenkernel/BKE_softbody.h index 486fe8ed5a83..5e8ea89c0f47 100644 --- a/source/blender/blenkernel/BKE_softbody.h +++ b/source/blender/blenkernel/BKE_softbody.h @@ -72,4 +72,3 @@ extern void SB_estimate_transform(Object *ob, float lloc[3], float l #endif - diff --git a/source/blender/blenkernel/BKE_texture.h b/source/blender/blenkernel/BKE_texture.h index 4e98852c995d..7ffa22ac49bb 100644 --- a/source/blender/blenkernel/BKE_texture.h +++ b/source/blender/blenkernel/BKE_texture.h @@ -144,4 +144,3 @@ void BKE_texture_fetch_images_for_pool(struct Tex *texture, struct ImagePool *po #endif #endif - diff --git a/source/blender/blenkernel/BKE_writeavi.h b/source/blender/blenkernel/BKE_writeavi.h index ca295c51f5dc..31235047cbdd 100644 --- a/source/blender/blenkernel/BKE_writeavi.h +++ b/source/blender/blenkernel/BKE_writeavi.h @@ -38,7 +38,7 @@ extern "C" { /* generic blender movie support, could move to own module */ -struct RenderData; +struct RenderData; struct ReportList; struct Scene; @@ -63,4 +63,3 @@ void BKE_context_create(bMovieHandle *mh); #endif #endif - diff --git a/source/blender/blenkernel/BKE_writeffmpeg.h b/source/blender/blenkernel/BKE_writeffmpeg.h index a40c31022e33..0950935fbc8d 100644 --- a/source/blender/blenkernel/BKE_writeffmpeg.h +++ b/source/blender/blenkernel/BKE_writeffmpeg.h @@ -92,4 +92,3 @@ void BKE_ffmpeg_context_free(void *context_v); #endif #endif - diff --git a/source/blender/blenkernel/BKE_writeframeserver.h b/source/blender/blenkernel/BKE_writeframeserver.h index 0837e9bce794..c38b1b196c3b 100644 --- a/source/blender/blenkernel/BKE_writeframeserver.h +++ b/source/blender/blenkernel/BKE_writeframeserver.h @@ -36,7 +36,7 @@ extern "C" { #endif -struct RenderData; +struct RenderData; struct ReportList; struct Scene; @@ -56,4 +56,3 @@ void BKE_frameserver_context_free(void *context_v); #endif #endif - diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 28ac76196570..8d2d142b2c24 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -413,7 +413,7 @@ if(WITH_CODEC_FFMPEG) ) add_definitions(-DWITH_FFMPEG) - remove_strict_flags_file( + remove_strict_c_flags_file( intern/writeffmpeg.c ) endif() diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c index 792e9195f121..c6224da2fe01 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf.c +++ b/source/blender/blenkernel/intern/CCGSubSurf.c @@ -277,7 +277,7 @@ CCGSubSurf *ccgSubSurf_new(CCGMeshIFC *ifc, int subdivLevels, CCGAllocatorIFC *a ss->fMap = ccg_ehash_new(0, &ss->allocatorIFC, ss->allocator); ss->meshIFC = *ifc; - + ss->subdivLevels = subdivLevels; ss->numGrids = 0; ss->allowEdgeCreation = 0; @@ -489,8 +489,8 @@ CCGError ccgSubSurf_initFullSync(CCGSubSurf *ss) ss->currentAge++; - ss->oldVMap = ss->vMap; - ss->oldEMap = ss->eMap; + ss->oldVMap = ss->vMap; + ss->oldEMap = ss->eMap; ss->oldFMap = ss->fMap; ss->vMap = ccg_ehash_new(0, &ss->allocatorIFC, ss->allocator); @@ -592,7 +592,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, const void *vertDa void **prevp; CCGVert *v = NULL; short seamflag = (seam) ? Vert_eSeam : 0; - + if (ss->syncState == eSyncState_Partial) { v = ccg_ehash_lookupWithPrev(ss->vMap, vHDL, &prevp); if (!v) { @@ -937,7 +937,7 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGFace **faces, int num for (j = 0; j < v->numFaces; j++) if (!(v->faces[j]->flags & Face_eEffected)) break; - + if (j == v->numFaces) { arrayV[numV++] = v; v->flags |= Vert_eEffected; @@ -952,7 +952,7 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGFace **faces, int num for (j = 0; j < e->numFaces; j++) if (!(e->faces[j]->flags & Face_eEffected)) break; - + if (j == e->numFaces) { e->flags |= Edge_eEffected; arrayE[numE++] = e; @@ -1550,11 +1550,11 @@ int ccgSubSurf_getNumFinalFaces(const CCGSubSurf *ss) void CCG_key(CCGKey *key, const CCGSubSurf *ss, int level) { key->level = level; - + key->elem_size = ss->meshIFC.vertDataSize; key->has_normals = ss->calcVertNormals; key->num_layers = ss->meshIFC.numLayers; - + /* if normals are present, always the last three floats of an * element */ if (key->has_normals) diff --git a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c index f1f82f458aa2..8c1ba0c3782f 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c +++ b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c @@ -84,11 +84,14 @@ static OpenSubdiv_SchemeType conv_dm_get_type( return OSD_SCHEME_CATMARK; } -static bool conv_dm_get_subdiv_uvs( +static OpenSubdiv_FVarLinearInterpolation conv_dm_get_fvar_linear_interpolation( const OpenSubdiv_Converter *converter) { ConvDMStorage *storage = converter->user_data; - return (storage->ss->osd_subdiv_uvs); + if (storage->ss->osd_subdiv_uvs) { + return OSD_FVAR_LINEAR_INTERPOLATION_CORNERS_ONLY; + } + return OSD_FVAR_LINEAR_INTERPOLATION_ALL; } static int conv_dm_get_num_faces(const OpenSubdiv_Converter *converter) @@ -429,9 +432,10 @@ void ccgSubSurf_converter_setup_from_derivedmesh( { ConvDMStorage *user_data; - converter->get_type = conv_dm_get_type; + converter->get_scheme_type = conv_dm_get_type; - converter->get_subdiv_uvs = conv_dm_get_subdiv_uvs; + converter->get_fvar_linear_interpolation = + conv_dm_get_fvar_linear_interpolation; converter->get_num_faces = conv_dm_get_num_faces; converter->get_num_edges = conv_dm_get_num_edges; @@ -526,11 +530,14 @@ static OpenSubdiv_SchemeType conv_ccg_get_bilinear_type( } } -static bool conv_ccg_get_subdiv_uvs( - const OpenSubdiv_Converter *converter) +static OpenSubdiv_FVarLinearInterpolation +conv_ccg_get_fvar_linear_interpolation(const OpenSubdiv_Converter *converter) { CCGSubSurf *ss = converter->user_data; - return (ss->osd_subdiv_uvs); + if (ss->osd_subdiv_uvs) { + return OSD_FVAR_LINEAR_INTERPOLATION_CORNERS_ONLY; + } + return OSD_FVAR_LINEAR_INTERPOLATION_ALL; } static int conv_ccg_get_num_faces(const OpenSubdiv_Converter *converter) @@ -710,9 +717,10 @@ static int conv_ccg_get_face_corner_uv_index(const OpenSubdiv_Converter *UNUSED( void ccgSubSurf_converter_setup_from_ccg(CCGSubSurf *ss, OpenSubdiv_Converter *converter) { - converter->get_type = conv_ccg_get_bilinear_type; + converter->get_scheme_type = conv_ccg_get_bilinear_type; - converter->get_subdiv_uvs = conv_ccg_get_subdiv_uvs; + converter->get_fvar_linear_interpolation = + conv_ccg_get_fvar_linear_interpolation; converter->get_num_faces = conv_ccg_get_num_faces; converter->get_num_edges = conv_ccg_get_num_edges; diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 15469e3ae4b0..9c0fc79a358a 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -137,7 +137,7 @@ static MFace *dm_getTessFaceArray(DerivedMesh *dm) if (!mface) { int numTessFaces = dm->getNumTessFaces(dm); - + if (!numTessFaces) { /* Do not add layer if there's no elements in it, this leads to issues later when * this layer is needed with non-zero size, but currently CD stuff does not check @@ -145,7 +145,7 @@ static MFace *dm_getTessFaceArray(DerivedMesh *dm) * added (sergey) */ return NULL; } - + mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces); CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY); dm->copyTessFaceArray(dm, mface); @@ -347,7 +347,7 @@ void DM_init( dm->numPolyData = numPolys; DM_init_funcs(dm); - + dm->needsFree = 1; dm->auto_bump_scale = -1.0f; dm->dirty = 0; @@ -758,7 +758,7 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) { KeyBlock *kb; int uid; - + if (ob) { kb = BLI_findlink(&me->key->block, ob->shapenr - 1); if (kb) { @@ -784,7 +784,7 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool if (ob) { BKE_mesh_texspace_copy_from_object(&tmp, ob); } - + /* not all DerivedMeshes store their verts/edges/faces in CustomData, so * we set them here in case they are missing */ if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) { @@ -864,18 +864,18 @@ void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb) int a, totvert = dm->getNumVerts(dm); float *fp; MVert *mvert; - + if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) { return; } - + if (kb->data) MEM_freeN(kb->data); kb->data = MEM_malloc_arrayN(me->key->elemsize, me->totvert, "kb->data"); kb->totelem = totvert; - + fp = kb->data; mvert = dm->getVertDataArray(dm, CD_MVERT); - + for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) { copy_v3_v3(fp, mvert->co); } @@ -1135,10 +1135,10 @@ void DM_interp_poly_data( DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3]) { DerivedMesh *dm = CDDM_from_mesh(me); - + if (!dm) return NULL; - + if (vertCos) { CDDM_apply_vert_coords(dm, vertCos); } @@ -1156,7 +1156,7 @@ DerivedMesh *mesh_create_derived_for_modifier( KeyBlock *kb; md->scene = scene; - + if (!(md->mode & eModifierMode_Realtime)) { return NULL; } @@ -1164,11 +1164,11 @@ DerivedMesh *mesh_create_derived_for_modifier( if (mti->isDisabled && mti->isDisabled(md, 0)) { return NULL; } - + if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) { BKE_keyblock_convert_to_mesh(kb, me); } - + if (mti->type == eModifierTypeType_OnlyDeform) { int numVerts; float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts); @@ -1178,7 +1178,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(dm, me, ob); - + MEM_freeN(deformedVerts); } else { @@ -1186,7 +1186,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(tdm, me, ob); - + dm = modwrap_applyModifier(md, ob, tdm, 0); ASSERT_IS_VALID_DM(dm); @@ -1205,13 +1205,13 @@ static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3] /* these may not really be the orco's, but it's only for preview. * could be solver better once, but isn't simple */ - + orco = MEM_malloc_arrayN(em->bm->totvert, sizeof(float) * 3, "BMEditMesh Orco"); BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) { copy_v3_v3(orco[i], eve->co); } - + return orco; } @@ -1401,7 +1401,7 @@ static void calc_weightpaint_vert_color( const int draw_flag) { float input = 0.0f; - + bool show_alert_color = false; if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) { @@ -1633,35 +1633,35 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape { KeyBlock *kb; int i, j, tot; - + if (!me->key) return; - + tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY); for (i = 0; i < tot; i++) { CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)]; float (*cos)[3], (*kbcos)[3]; - + for (kb = me->key->block.first; kb; kb = kb->next) { if (kb->uid == layer->uid) break; } - + if (!kb) { kb = BKE_keyblock_add(me->key, layer->name); kb->uid = layer->uid; } - + if (kb->data) MEM_freeN(kb->data); - + cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i); kb->totelem = dm->numVertData; kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, 3 * sizeof(float), "kbcos DerivedMesh.c"); if (kb->uid == actshape_uid) { MVert *mvert = dm->getVertArray(dm); - + for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) { copy_v3_v3(*kbcos, mvert->co); } @@ -1672,12 +1672,12 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape } } } - + for (kb = me->key->block.first; kb; kb = kb->next) { if (kb->totelem != dm->numVertData) { if (kb->data) MEM_freeN(kb->data); - + kb->totelem = dm->numVertData; kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c"); fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name); @@ -1844,13 +1844,13 @@ static void mesh_calc_modifiers( if (useDeform) { if (inputVertexCos) deformedVerts = inputVertexCos; - + /* Apply all leading deforming modifiers */ for (; md; md = md->next, curr = curr->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!modifier_isEnabled(scene, md, required_mode)) { continue; } @@ -1868,7 +1868,7 @@ static void mesh_calc_modifiers( else { break; } - + /* grab modifiers until index i */ if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) break; @@ -1883,7 +1883,7 @@ static void mesh_calc_modifiers( if (build_shapekey_layers) add_shapekey_layers(dm, me, ob); - + if (deformedVerts) { CDDM_apply_vert_coords(*r_deform, deformedVerts); } @@ -1899,7 +1899,7 @@ static void mesh_calc_modifiers( /* Now apply all remaining modifiers. If useDeform is off then skip - * OnlyDeform ones. + * OnlyDeform ones. */ dm = NULL; orcodm = NULL; @@ -2059,14 +2059,14 @@ static void mesh_calc_modifiers( } } - + /* set the DerivedMesh to only copy needed data */ mask = curr->mask; /* needMapping check here fixes bug [#28112], otherwise it's * possible that it won't be copied */ mask |= append_mask; DM_set_only_copy(dm, mask | (need_mapping ? CD_MASK_ORIGINDEX : 0)); - + /* add cloth rest shape key if needed */ if (mask & CD_MASK_CLOTH_ORCO) add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO); @@ -2191,11 +2191,11 @@ static void mesh_calc_modifiers( } else { finaldm = CDDM_from_mesh(me); - + if (build_shapekey_layers) { add_shapekey_layers(finaldm, me, ob); } - + if (deformedVerts) { CDDM_apply_vert_coords(finaldm, deformedVerts); } @@ -2302,7 +2302,7 @@ bool editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh * modifier_setError(md, "Modifier requires original data, bad stack position"); return false; } - + return true; } @@ -2359,7 +2359,7 @@ static void editbmesh_calc_modifiers( const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!editbmesh_modifier_is_enabled(scene, md, dm)) { continue; } @@ -2794,7 +2794,7 @@ DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask da DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers( scene, ob, NULL, true, 1, false, dataMask, -1, false, false, false, NULL, &final); @@ -2839,7 +2839,7 @@ DerivedMesh *mesh_create_derived_no_deform( CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers( scene, ob, vertCos, false, 0, false, dataMask, -1, false, false, false, NULL, &final); @@ -2852,7 +2852,7 @@ DerivedMesh *mesh_create_derived_no_virtual( CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers( scene, ob, vertCos, false, -1, false, dataMask, -1, false, false, false, NULL, &final); @@ -2865,7 +2865,7 @@ DerivedMesh *mesh_create_derived_physics( CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers( scene, ob, vertCos, false, -1, true, dataMask, -1, false, false, false, NULL, &final); @@ -2991,13 +2991,13 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob) Mesh *me = ob->data; DerivedMesh *dm; DMCoNo *vertexcosnos; - + /* lets prevent crashing... */ if (ob->type != OB_MESH || me->totvert == 0) return NULL; - + dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX); - + if (dm->foreachMappedVert) { vertexcosnos = MEM_calloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map"); dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos); @@ -3010,7 +3010,7 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob) dm->getVertNo(dm, a, v_co_no->no); } } - + dm->release(dm); return vertexcosnos; } @@ -3703,7 +3703,7 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, vdata = &dm->vertData; ldata = dm->getLoopDataLayout(dm); - + /* calc auto bump scale if necessary */ if (dm->auto_bump_scale <= 0.0f) DM_calc_auto_bump_scale(dm); diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index fa36da8030ee..e6848876425e 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include "MEM_guardedalloc.h" @@ -87,11 +87,11 @@ bAction *BKE_action_add(Main *bmain, const char name[]) { bAction *act; - + act = BKE_libblock_alloc(bmain, ID_AC, name, 0); - + return act; -} +} /* .................................. */ @@ -105,15 +105,15 @@ void BKE_action_make_local(Main *bmain, bAction *act, const bool lib_local) /** Free (or release) any data used by this action (does not free the action itself). */ void BKE_action_free(bAction *act) -{ +{ /* No animdata here. */ /* Free F-Curves */ free_fcurves(&act->curves); - + /* Free groups */ BLI_freelistN(&act->groups); - + /* Free pose-references (aka local markers) */ BLI_freelistN(&act->markers); } @@ -178,14 +178,14 @@ bAction *BKE_action_copy(Main *bmain, const bAction *act_src) bActionGroup *get_active_actiongroup(bAction *act) { bActionGroup *agrp = NULL; - + if (act && act->groups.first) { for (agrp = act->groups.first; agrp; agrp = agrp->next) { if (agrp->flag & AGRP_ACTIVE) break; } } - + return agrp; } @@ -193,11 +193,11 @@ bActionGroup *get_active_actiongroup(bAction *act) void set_active_action_group(bAction *act, bActionGroup *agrp, short select) { bActionGroup *grp; - + /* sanity checks */ if (act == NULL) return; - + /* Deactive all others */ for (grp = act->groups.first; grp; grp = grp->next) { if ((grp == agrp) && (select)) @@ -216,7 +216,7 @@ void action_group_colors_sync(bActionGroup *grp, const bActionGroup *ref_grp) /* copy theme colors on-to group's custom color in case user tries to edit color */ bTheme *btheme = U.themes.first; ThemeWireColor *col_set = &btheme->tarm[(grp->customCol - 1)]; - + memcpy(&grp->cs, col_set, sizeof(ThemeWireColor)); } else { @@ -242,69 +242,69 @@ void action_group_colors_sync(bActionGroup *grp, const bActionGroup *ref_grp) bActionGroup *action_groups_add_new(bAction *act, const char name[]) { bActionGroup *agrp; - + /* sanity check: must have action and name */ if (ELEM(NULL, act, name)) return NULL; - + /* allocate a new one */ agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup"); - + /* make it selected, with default name */ agrp->flag = AGRP_SELECTED; BLI_strncpy(agrp->name, name[0] ? name : DATA_("Group"), sizeof(agrp->name)); - + /* add to action, and validate */ BLI_addtail(&act->groups, agrp); BLI_uniquename(&act->groups, agrp, DATA_("Group"), '.', offsetof(bActionGroup, name), sizeof(agrp->name)); - + /* return the new group */ return agrp; } -/* Add given channel into (active) group +/* Add given channel into (active) group * - assumes that channel is not linked to anything anymore * - always adds at the end of the group */ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) -{ +{ /* sanity checks */ if (ELEM(NULL, act, agrp, fcurve)) return; - + /* if no channels anywhere, just add to two lists at the same time */ if (BLI_listbase_is_empty(&act->curves)) { fcurve->next = fcurve->prev = NULL; - + agrp->channels.first = agrp->channels.last = fcurve; act->curves.first = act->curves.last = fcurve; } - - /* if the group already has channels, the F-Curve can simply be added to the list + + /* if the group already has channels, the F-Curve can simply be added to the list * (i.e. as the last channel in the group) */ else if (agrp->channels.first) { - /* if the group's last F-Curve is the action's last F-Curve too, + /* if the group's last F-Curve is the action's last F-Curve too, * then set the F-Curve as the last for the action first so that * the lists will be in sync after linking */ if (agrp->channels.last == act->curves.last) act->curves.last = fcurve; - + /* link in the given F-Curve after the last F-Curve in the group, * which means that it should be able to fit in with the rest of the * list seamlessly */ BLI_insertlinkafter(&agrp->channels, agrp->channels.last, fcurve); } - + /* otherwise, need to find the nearest F-Curve in group before/after current to link with */ else { bActionGroup *grp; - + /* firstly, link this F-Curve to the group */ agrp->channels.first = agrp->channels.last = fcurve; - + /* step through the groups preceding this one, finding the F-Curve there to attach this one after */ for (grp = agrp->prev; grp; grp = grp->prev) { /* if this group has F-Curves, we want weave the given one in right after the last channel there, @@ -318,18 +318,18 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) break; } } - + /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first - * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the + * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the * second in the chain, etc. etc. */ if (grp == NULL) BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve); } - + /* set the F-Curve's new group */ fcurve->grp = agrp; -} +} /* Remove the given channel from all groups */ void action_groups_remove_channel(bAction *act, FCurve *fcu) @@ -337,11 +337,11 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) /* sanity checks */ if (ELEM(NULL, act, fcu)) return; - + /* check if any group used this directly */ if (fcu->grp) { bActionGroup *agrp = fcu->grp; - + if (agrp->channels.first == agrp->channels.last) { if (agrp->channels.first == fcu) { BLI_listbase_clear(&agrp->channels); @@ -359,10 +359,10 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) else agrp->channels.last = NULL; } - + fcu->grp = NULL; } - + /* now just remove from list */ BLI_remlink(&act->curves, fcu); } @@ -373,7 +373,7 @@ bActionGroup *BKE_action_group_find_name(bAction *act, const char name[]) /* sanity checks */ if (ELEM(NULL, act, act->groups.first, name) || (name[0] == 0)) return NULL; - + /* do string comparisons */ return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name)); } @@ -382,11 +382,11 @@ bActionGroup *BKE_action_group_find_name(bAction *act, const char name[]) void action_groups_clear_tempflags(bAction *act) { bActionGroup *agrp; - + /* sanity checks */ if (ELEM(NULL, act, act->groups.first)) return; - + /* flag clearing loop */ for (agrp = act->groups.first; agrp; agrp = agrp->next) agrp->flag &= ~AGRP_TEMP; @@ -402,10 +402,10 @@ bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name) { if (ELEM(NULL, pose, name) || (name[0] == '\0')) return NULL; - + if (pose->chanhash) return BLI_ghash_lookup(pose->chanhash, (const void *)name); - + return BLI_findstring(&((const bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name)); } @@ -420,10 +420,10 @@ bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name) bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) { bPoseChannel *chan; - + if (pose == NULL) return NULL; - + /* See if this channel exists */ chan = BLI_findstring(&pose->chanbase, name, offsetof(bPoseChannel, name)); if (chan) { @@ -432,7 +432,7 @@ bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) /* If not, create it and add it */ chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel"); - + BLI_strncpy(chan->name, name, sizeof(chan->name)); chan->custom_scale = 1.0f; @@ -441,20 +441,20 @@ bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) unit_qt(chan->quat); unit_axis_angle(chan->rotAxis, &chan->rotAngle); chan->size[0] = chan->size[1] = chan->size[2] = 1.0f; - + chan->scaleIn = chan->scaleOut = 1.0f; - + chan->limitmin[0] = chan->limitmin[1] = chan->limitmin[2] = -M_PI; chan->limitmax[0] = chan->limitmax[1] = chan->limitmax[2] = M_PI; chan->stiffness[0] = chan->stiffness[1] = chan->stiffness[2] = 0.0f; chan->ikrotweight = chan->iklinweight = 0.0f; unit_m4(chan->constinv); - + chan->protectflag = OB_LOCK_ROT4D; /* lock by components by default */ - + BLI_addtail(&pose->chanbase, chan); BKE_pose_channels_hash_free(pose); - + return chan; } @@ -494,7 +494,7 @@ bPoseChannel *BKE_pose_channel_active(Object *ob) if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer)) return pchan; } - + return NULL; } @@ -543,11 +543,11 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const *dst = NULL; return; } - + outPose = MEM_callocN(sizeof(bPose), "pose"); - + BLI_duplicatelist(&outPose->chanbase, &src->chanbase); - + /* Rebuild ghash here too, so that name lookups below won't be too bad... * BUT this will have the penalty that the ghash will be built twice * if BKE_pose_rebuild() gets called after this... @@ -556,12 +556,12 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const outPose->chanhash = NULL; BKE_pose_channels_hash_make(outPose); } - + outPose->iksolver = src->iksolver; outPose->ikdata = NULL; outPose->ikparam = MEM_dupallocN(src->ikparam); outPose->avs = src->avs; - + for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) { if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)pchan->custom); @@ -583,7 +583,7 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const pchan->constraints = listb; pchan->mpath = NULL; /* motion paths should not get copied yet... */ } - + if (pchan->prop) { pchan->prop = IDP_CopyProperty_ex(pchan->prop, flag); } @@ -593,7 +593,7 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const if (copy_constraints) { BLI_duplicatelist(&outPose->agroups, &src->agroups); } - + *dst = outPose; } @@ -641,7 +641,7 @@ static bool pose_channel_in_IK_chain(Object *ob, bPoseChannel *pchan, int level) { bConstraint *con; Bone *bone; - + /* No need to check if constraint is active (has influence), * since all constraints with CONSTRAINT_IK_AUTO are active */ for (con = pchan->constraints.first; con; con = con->next) { @@ -670,18 +670,18 @@ bool BKE_pose_channel_in_IK_chain(Object *ob, bPoseChannel *pchan) * Removes the hash for quick lookup of channels, must * be done when adding/removing channels. */ -void BKE_pose_channels_hash_make(bPose *pose) +void BKE_pose_channels_hash_make(bPose *pose) { if (!pose->chanhash) { bPoseChannel *pchan; - + pose->chanhash = BLI_ghash_str_new("make_pose_chan gh"); for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) BLI_ghash_insert(pose->chanhash, pchan->name, pchan); } } -void BKE_pose_channels_hash_free(bPose *pose) +void BKE_pose_channels_hash_free(bPose *pose) { if (pose->chanhash) { BLI_ghash_free(pose->chanhash, NULL, NULL); @@ -737,7 +737,7 @@ void BKE_pose_channels_remove( cti->flush_constraint_targets(con, &targets, 0); } } - + if (pchan->bbone_prev) { if (filter_fn(pchan->bbone_prev->name, user_data)) pchan->bbone_prev = NULL; @@ -746,7 +746,7 @@ void BKE_pose_channels_remove( if (filter_fn(pchan->bbone_next->name, user_data)) pchan->bbone_next = NULL; } - + if (pchan->custom_tx) { if (filter_fn(pchan->custom_tx->name, user_data)) pchan->custom_tx = NULL; @@ -775,7 +775,7 @@ void BKE_pose_channel_free_ex(bPoseChannel *pchan, bool do_id_user) } BKE_constraints_free_ex(&pchan->constraints, do_id_user); - + if (pchan->prop) { IDP_FreeProperty(pchan->prop); MEM_freeN(pchan->prop); @@ -794,11 +794,11 @@ void BKE_pose_channel_free(bPoseChannel *pchan) void BKE_pose_channels_free_ex(bPose *pose, bool do_id_user) { bPoseChannel *pchan; - + if (pose->chanbase.first) { for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) BKE_pose_channel_free_ex(pchan, do_id_user); - + BLI_freelistN(&pose->chanbase); } @@ -852,7 +852,7 @@ void BKE_pose_free(bPose *pose) static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan) { bConstraint *pcon, *con; - + copy_v3_v3(pchan->loc, chan->loc); copy_v3_v3(pchan->size, chan->size); copy_v3_v3(pchan->eul, chan->eul); @@ -863,7 +863,7 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan copy_m4_m4(pchan->chan_mat, (float(*)[4])chan->chan_mat); copy_m4_m4(pchan->pose_mat, (float(*)[4])chan->pose_mat); pchan->flag = chan->flag; - + pchan->roll1 = chan->roll1; pchan->roll2 = chan->roll2; pchan->curveInX = chan->curveInX; @@ -874,7 +874,7 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan pchan->ease2 = chan->ease2; pchan->scaleIn = chan->scaleIn; pchan->scaleOut = chan->scaleOut; - + con = chan->constraints.first; for (pcon = pchan->constraints.first; pcon && con; pcon = pcon->next, con = con->next) { pcon->enforce = con->enforce; @@ -908,7 +908,7 @@ void BKE_pose_channel_copy_data(bPoseChannel *pchan, const bPoseChannel *pchan_f pchan->ikstretch = pchan_from->ikstretch; pchan->ikrotweight = pchan_from->ikrotweight; pchan->iklinweight = pchan_from->iklinweight; - + /* bbone settings (typically not animated) */ pchan->bboneflag = pchan_from->bboneflag; pchan->bbone_next = pchan_from->bbone_next; @@ -946,31 +946,31 @@ void BKE_pose_update_constraint_flags(bPose *pose) { bPoseChannel *pchan, *parchan; bConstraint *con; - + /* clear */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { pchan->constflag = 0; } pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND; - + /* detect */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { if (con->type == CONSTRAINT_TYPE_KINEMATIC) { bKinematicConstraint *data = (bKinematicConstraint *)con->data; - + pchan->constflag |= PCHAN_HAS_IK; - + if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)) pchan->constflag |= PCHAN_HAS_TARGET; - + /* negative rootbone = recalc rootbone index. used in do_versions */ if (data->rootbone < 0) { data->rootbone = 0; - + if (data->flag & CONSTRAINT_IK_TIP) parchan = pchan; else parchan = pchan->parent; - + while (parchan) { data->rootbone++; if ((parchan->bone->flag & BONE_CONNECTED) == 0) @@ -981,10 +981,10 @@ void BKE_pose_update_constraint_flags(bPose *pose) } else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) { bFollowPathConstraint *data = (bFollowPathConstraint *)con->data; - + /* for drawing constraint colors when color set allows this */ pchan->constflag |= PCHAN_HAS_CONST; - + /* if we have a valid target, make sure that this will get updated on frame-change * (needed for when there is no anim-data for this pose) */ @@ -993,7 +993,7 @@ void BKE_pose_update_constraint_flags(bPose *pose) } else if (con->type == CONSTRAINT_TYPE_SPLINEIK) pchan->constflag |= PCHAN_HAS_SPLINEIK; - else + else pchan->constflag |= PCHAN_HAS_CONST; } } @@ -1005,7 +1005,7 @@ void BKE_pose_tag_update_constraint_flags(bPose *pose) pose->flag |= POSE_CONSTRAINTS_NEED_UPDATE_FLAGS; } -/* Clears all BONE_UNKEYED flags for every pose channel in every pose +/* Clears all BONE_UNKEYED flags for every pose channel in every pose * This should only be called on frame changing, when it is acceptable to * do this. Otherwise, these flags should not get cleared as poses may get lost. */ @@ -1014,14 +1014,14 @@ void framechange_poses_clear_unkeyed(Main *bmain) Object *ob; bPose *pose; bPoseChannel *pchan; - + /* This needs to be done for each object that has a pose */ /* TODO: proxies may/may not be correctly handled here... (this needs checking) */ for (ob = bmain->object.first; ob; ob = ob->id.next) { /* we only need to do this on objects with a pose */ if ((pose = ob->pose)) { for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (pchan->bone) + if (pchan->bone) pchan->bone->flag &= ~BONE_UNKEYED; } } @@ -1034,18 +1034,18 @@ void framechange_poses_clear_unkeyed(Main *bmain) bActionGroup *BKE_pose_add_group(bPose *pose, const char *name) { bActionGroup *grp; - + if (!name) { name = DATA_("Group"); } - + grp = MEM_callocN(sizeof(bActionGroup), "PoseGroup"); BLI_strncpy(grp->name, name, sizeof(grp->name)); BLI_addtail(&pose->agroups, grp); BLI_uniquename(&pose->agroups, grp, name, '.', offsetof(bActionGroup, name), sizeof(grp->name)); - + pose->active_group = BLI_listbase_count(&pose->agroups); - + return grp; } @@ -1055,13 +1055,13 @@ void BKE_pose_remove_group(bPose *pose, bActionGroup *grp, const int index) { bPoseChannel *pchan; int idx = index; - + if (idx < 1) { idx = BLI_findindex(&pose->agroups, grp) + 1; } - + BLI_assert(idx > 0); - + /* adjust group references (the trouble of using indices!): * - firstly, make sure nothing references it * - also, make sure that those after this item get corrected @@ -1091,7 +1091,7 @@ void BKE_pose_remove_group(bPose *pose, bActionGroup *grp, const int index) void BKE_pose_remove_group_index(bPose *pose, const int index) { bActionGroup *grp = NULL; - + /* get group to remove */ grp = BLI_findlink(&pose->agroups, index - 1); if (grp) { @@ -1105,7 +1105,7 @@ void BKE_pose_remove_group_index(bPose *pose, const int index) bool action_has_motion(const bAction *act) { FCurve *fcu; - + /* return on the first F-Curve that has some keyframes/samples defined */ if (act) { for (fcu = act->curves.first; fcu; fcu = fcu->next) { @@ -1113,7 +1113,7 @@ bool action_has_motion(const bAction *act) return true; } } - + /* nothing found */ return false; } @@ -1130,7 +1130,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ /* if curve has keyframes, consider them first */ if (fcu->totvert) { float nmin, nmax; - + /* get extents for this curve * - no "selected only", since this is often used in the backend * - no "minimum length" (we will apply this later), otherwise @@ -1138,26 +1138,26 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ * a phantom frame (T50354) */ calc_fcurve_range(fcu, &nmin, &nmax, false, false); - + /* compare to the running tally */ min = min_ff(min, nmin); max = max_ff(max, nmax); - + foundvert = 1; } - + /* if incl_modifiers is enabled, need to consider modifiers too * - only really care about the last modifier */ if ((incl_modifiers) && (fcu->modifiers.last)) { FModifier *fcm = fcu->modifiers.last; - + /* only use the maximum sensible limits of the modifiers if they are more extreme */ switch (fcm->type) { case FMODIFIER_TYPE_LIMITS: /* Limits F-Modifier */ { FMod_Limits *fmd = (FMod_Limits *)fcm->data; - + if (fmd->flag & FCM_LIMIT_XMIN) { min = min_ff(min, fmd->rect.xmin); } @@ -1169,7 +1169,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ case FMODIFIER_TYPE_CYCLES: /* Cycles F-Modifier */ { FMod_Cycles *fmd = (FMod_Cycles *)fcm->data; - + if (fmd->before_mode != FCM_EXTRAPOLATE_NONE) min = MINAFRAMEF; if (fmd->after_mode != FCM_EXTRAPOLATE_NONE) @@ -1177,22 +1177,22 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ break; } /* TODO: function modifier may need some special limits */ - + default: /* all other standard modifiers are on the infinite range... */ min = MINAFRAMEF; max = MAXFRAMEF; break; } - + foundmod = 1; } } } - + if (foundvert || foundmod) { /* ensure that action is at least 1 frame long (for NLA strips to have a valid length) */ if (min == max) max += 1.0f; - + *start = min; *end = max; } @@ -1202,7 +1202,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ } } -/* Return flags indicating which transforms the given object/posechannel has +/* Return flags indicating which transforms the given object/posechannel has * - if 'curves' is provided, a list of links to these curves are also returned */ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, ListBase *curves) @@ -1211,7 +1211,7 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, FCurve *fcu; char *basePath = NULL; short flags = 0; - + /* build PointerRNA from provided data to obtain the paths to use */ if (pchan) RNA_pointer_create((ID *)ob, &RNA_PoseBone, pchan, &ptr); @@ -1219,37 +1219,37 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, RNA_id_pointer_create((ID *)ob, &ptr); else return 0; - + /* get the basic path to the properties of interest */ basePath = RNA_path_from_ID_to_struct(&ptr); if (basePath == NULL) return 0; - - /* search F-Curves for the given properties + + /* search F-Curves for the given properties * - we cannot use the groups, since they may not be grouped in that way... */ for (fcu = act->curves.first; fcu; fcu = fcu->next) { const char *bPtr = NULL, *pPtr = NULL; - + /* if enough flags have been found, we can stop checking unless we're also getting the curves */ if ((flags == ACT_TRANS_ALL) && (curves == NULL)) break; - + /* just in case... */ if (fcu->rna_path == NULL) continue; - + /* step 1: check for matching base path */ bPtr = strstr(fcu->rna_path, basePath); - + if (bPtr) { - /* we must add len(basePath) bytes to the match so that we are at the end of the + /* we must add len(basePath) bytes to the match so that we are at the end of the * base path so that we don't get false positives with these strings in the names */ bPtr += strlen(basePath); - - /* step 2: check for some property with transforms - * - to speed things up, only check for the ones not yet found + + /* step 2: check for some property with transforms + * - to speed things up, only check for the ones not yet found * unless we're getting the curves too * - if we're getting the curves, the BLI_genericNodeN() creates a LinkData * node wrapping the F-Curve, which then gets added to the list @@ -1259,53 +1259,53 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, pPtr = strstr(bPtr, "location"); if (pPtr) { flags |= ACT_TRANS_LOC; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_SCALE) == 0) { pPtr = strstr(bPtr, "scale"); if (pPtr) { flags |= ACT_TRANS_SCALE; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_ROT) == 0) { pPtr = strstr(bPtr, "rotation"); if (pPtr) { flags |= ACT_TRANS_ROT; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_BBONE) == 0) { /* bbone shape properties */ pPtr = strstr(bPtr, "bbone_"); if (pPtr) { flags |= ACT_TRANS_BBONE; - + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_PROP) == 0) { /* custom properties only */ pPtr = strstr(bPtr, "[\""); /* extra '"' comment here to keep my texteditor functionlist working :) */ if (pPtr) { flags |= ACT_TRANS_PROP; - + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; @@ -1313,10 +1313,10 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, } } } - + /* free basePath */ MEM_freeN(basePath); - + /* return flags found */ return flags; } @@ -1346,26 +1346,26 @@ void extract_pose_from_pose(bPose *pose, const bPose *src) void BKE_pose_rest(bPose *pose) { bPoseChannel *pchan; - + if (!pose) return; - + memset(pose->stride_offset, 0, sizeof(pose->stride_offset)); memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset)); - + for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { zero_v3(pchan->loc); zero_v3(pchan->eul); unit_qt(pchan->quat); unit_axis_angle(pchan->rotAxis, &pchan->rotAngle); pchan->size[0] = pchan->size[1] = pchan->size[2] = 1.0f; - + pchan->roll1 = pchan->roll2 = 0.0f; pchan->curveInX = pchan->curveInY = 0.0f; pchan->curveOutX = pchan->curveOutY = 0.0f; pchan->ease1 = pchan->ease2 = 0.0f; pchan->scaleIn = pchan->scaleOut = 1.0f; - + pchan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE | POSE_BBONE_SHAPE); } } @@ -1374,7 +1374,7 @@ void BKE_pose_rest(bPose *pose) bool BKE_pose_copy_result(bPose *to, bPose *from) { bPoseChannel *pchanto, *pchanfrom; - + if (to == NULL || from == NULL) { printf("Pose copy error, pose to:%p from:%p\n", (void *)to, (void *)from); /* debug temp */ return false; @@ -1391,16 +1391,16 @@ bool BKE_pose_copy_result(bPose *to, bPose *from) if (pchanto) { copy_m4_m4(pchanto->pose_mat, pchanfrom->pose_mat); copy_m4_m4(pchanto->chan_mat, pchanfrom->chan_mat); - + /* used for local constraints */ copy_v3_v3(pchanto->loc, pchanfrom->loc); copy_qt_qt(pchanto->quat, pchanfrom->quat); copy_v3_v3(pchanto->eul, pchanfrom->eul); copy_v3_v3(pchanto->size, pchanfrom->size); - + copy_v3_v3(pchanto->pose_head, pchanfrom->pose_head); copy_v3_v3(pchanto->pose_tail, pchanfrom->pose_tail); - + pchanto->roll1 = pchanfrom->roll1; pchanto->roll2 = pchanfrom->roll2; pchanto->curveInX = pchanfrom->curveInX; @@ -1411,7 +1411,7 @@ bool BKE_pose_copy_result(bPose *to, bPose *from) pchanto->ease2 = pchanfrom->ease2; pchanto->scaleIn = pchanfrom->scaleIn; pchanto->scaleOut = pchanfrom->scaleOut; - + pchanto->rotmode = pchanfrom->rotmode; pchanto->flag = pchanfrom->flag; pchanto->protectflag = pchanfrom->protectflag; @@ -1431,27 +1431,27 @@ void BKE_pose_tag_recalc(Main *bmain, bPose *pose) DAG_relations_tag_update(bmain); } -/* For the calculation of the effects of an Action at the given frame on an object +/* For the calculation of the effects of an Action at the given frame on an object * This is currently only used for the Action Constraint */ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe) { bActionGroup *agrp = BKE_action_group_find_name(act, groupname); - + /* clear workob */ BKE_object_workob_clear(workob); - + /* init workob */ copy_m4_m4(workob->obmat, ob->obmat); copy_m4_m4(workob->parentinv, ob->parentinv); copy_m4_m4(workob->constinv, ob->constinv); workob->parent = ob->parent; - + workob->rotmode = ob->rotmode; - + workob->trackflag = ob->trackflag; workob->upflag = ob->upflag; - + workob->partype = ob->partype; workob->par1 = ob->par1; workob->par2 = ob->par2; @@ -1459,7 +1459,7 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c workob->constraints.first = ob->constraints.first; workob->constraints.last = ob->constraints.last; - + workob->pose = pose; /* need to set pose too, since this is used for both types of Action Constraint */ if (pose) { /* This function is most likely to be used with a temporary pose with a single bone in there. @@ -1476,29 +1476,28 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr)); BLI_strncpy(workob->id.name, "OB", sizeof(workob->id.name)); /* we don't use real object name, otherwise RNA screws with the real thing */ - + /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */ if (agrp) { /* specifically evaluate this group only */ PointerRNA id_ptr; - + /* get RNA-pointer for the workob's ID */ RNA_id_pointer_create(&workob->id, &id_ptr); - + /* execute action for this group only */ animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe); } else { AnimData adt = {NULL}; - + /* init animdata, and attach to workob */ workob->adt = &adt; - + adt.recalc = ADT_RECALC_ANIM; adt.action = act; - + /* execute effects of Action on to workob (or it's PoseChannels) */ BKE_animsys_evaluate_animdata(NULL, &workob->id, &adt, cframe, ADT_RECALC_ANIM); } } - diff --git a/source/blender/blenkernel/intern/addon.c b/source/blender/blenkernel/intern/addon.c index 689e0fb5ee62..854bf62c0616 100644 --- a/source/blender/blenkernel/intern/addon.c +++ b/source/blender/blenkernel/intern/addon.c @@ -53,9 +53,14 @@ bAddon *BKE_addon_new(void) return addon; } +bAddon *BKE_addon_find(ListBase *addon_list, const char *module) +{ + return BLI_findstring(addon_list, module, offsetof(bAddon, module)); +} + bAddon *BKE_addon_ensure(ListBase *addon_list, const char *module) { - bAddon *addon = BLI_findstring(addon_list, module, offsetof(bAddon, module)); + bAddon *addon = BKE_addon_find(addon_list, module); if (addon == NULL) { addon = BKE_addon_new(); BLI_strncpy(addon->module, module, sizeof(addon->module)); @@ -64,6 +69,17 @@ bAddon *BKE_addon_ensure(ListBase *addon_list, const char *module) return addon; } +bool BKE_addon_remove_safe(ListBase *addon_list, const char *module) +{ + bAddon *addon = BLI_findstring(addon_list, module, offsetof(bAddon, module)); + if (addon) { + BLI_remlink(addon_list, addon); + BKE_addon_free(addon); + return true; + } + return false; +} + void BKE_addon_free(bAddon *addon) { if (addon->prop) { diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index 84a8a5d6e29c..b3c6fb4f3a9d 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -92,22 +92,22 @@ void animviz_settings_init(bAnimVizSettings *avs) /* ------------------- */ /* Free the given motion path's cache */ -void animviz_free_motionpath_cache(bMotionPath *mpath) +void animviz_free_motionpath_cache(bMotionPath *mpath) { /* sanity check */ - if (mpath == NULL) + if (mpath == NULL) return; - + /* free the path if necessary */ if (mpath->points) MEM_freeN(mpath->points); - + /* reset the relevant parameters */ mpath->points = NULL; mpath->length = 0; } -/* Free the given motion path instance and its data +/* Free the given motion path instance and its data * NOTE: this frees the motion path given! */ void animviz_free_motionpath(bMotionPath *mpath) @@ -115,10 +115,10 @@ void animviz_free_motionpath(bMotionPath *mpath) /* sanity check */ if (mpath == NULL) return; - + /* free the cache first */ animviz_free_motionpath_cache(mpath); - + /* now the instance itself */ MEM_freeN(mpath); } @@ -137,11 +137,11 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec { bAnimVizSettings *avs; bMotionPath *mpath, **dst; - + /* sanity checks */ if (ELEM(NULL, scene, ob)) return NULL; - + /* get destination data */ if (pchan) { /* paths for posechannel - assume that posechannel belongs to the object */ @@ -169,9 +169,9 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec */ if (*dst != NULL) { int expected_length = avs->path_ef - avs->path_sf; - + mpath = *dst; - + /* path is "valid" if length is valid, but must also be of the same length as is being requested */ if ((mpath->start_frame != mpath->end_frame) && (mpath->length > 0)) { /* outer check ensures that we have some curve data for this path */ @@ -190,13 +190,13 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec mpath = MEM_callocN(sizeof(bMotionPath), "bMotionPath"); *dst = mpath; } - + /* set settings from the viz settings */ mpath->start_frame = avs->path_sf; mpath->end_frame = avs->path_ef; - + mpath->length = mpath->end_frame - mpath->start_frame; - + if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS) mpath->flag |= MOTIONPATH_FLAG_BHEAD; else @@ -212,10 +212,10 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec /* allocate a cache */ mpath->points = MEM_callocN(sizeof(bMotionPathVert) * mpath->length, "bMotionPathVerts"); - + /* tag viz settings as currently having some path(s) which use it */ avs->path_bakeflag |= MOTIONPATH_BAKE_HAS_PATHS; - + /* return it */ return mpath; } @@ -225,9 +225,9 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec /* Motion path needing to be baked (mpt) */ typedef struct MPathTarget { struct MPathTarget *next, *prev; - + bMotionPath *mpath; /* motion path in question */ - + Object *ob; /* source object */ bPoseChannel *pchan; /* source posechannel (if applicable) */ } MPathTarget; @@ -241,28 +241,28 @@ typedef struct MPathTarget { void animviz_get_object_motionpaths(Object *ob, ListBase *targets) { MPathTarget *mpt; - + /* object itself first */ if ((ob->avs.recalc & ANIMVIZ_RECALC_PATHS) && (ob->mpath)) { /* new target for object */ mpt = MEM_callocN(sizeof(MPathTarget), "MPathTarget Ob"); BLI_addtail(targets, mpt); - + mpt->mpath = ob->mpath; mpt->ob = ob; } - + /* bones */ if ((ob->pose) && (ob->pose->avs.recalc & ANIMVIZ_RECALC_PATHS)) { bArmature *arm = ob->data; bPoseChannel *pchan; - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { if ((pchan->bone) && (arm->layer & pchan->bone->layer) && (pchan->mpath)) { /* new target for bone */ mpt = MEM_callocN(sizeof(MPathTarget), "MPathTarget PoseBone"); BLI_addtail(targets, mpt); - + mpt->mpath = pchan->mpath; mpt->ob = ob; mpt->pchan = pchan; @@ -285,28 +285,28 @@ static void motionpaths_calc_optimise_depsgraph(Main *bmain, Scene *scene, ListB { Base *base, *baseNext; MPathTarget *mpt; - + /* make sure our temp-tag isn't already in use */ for (base = scene->base.first; base; base = base->next) base->object->flag &= ~BA_TEMP_TAG; - + /* for each target, dump its object to the start of the list if it wasn't moved already */ for (mpt = targets->first; mpt; mpt = mpt->next) { for (base = scene->base.first; base; base = baseNext) { baseNext = base->next; - + if ((base->object == mpt->ob) && !(mpt->ob->flag & BA_TEMP_TAG)) { BLI_remlink(&scene->base, base); BLI_addhead(&scene->base, base); - + mpt->ob->flag |= BA_TEMP_TAG; - + /* we really don't need to continue anymore once this happens, but this line might really 'break' */ break; } } } - + /* "brew me a list that's sorted a bit faster now depsy" */ DAG_scene_relations_rebuild(bmain, scene); } @@ -322,11 +322,11 @@ static void motionpaths_calc_update_scene(Main *bmain, Scene *scene) } else { /* otherwise we can optimize by restricting updates */ Base *base, *last = NULL; - + /* only stuff that moves or needs display still */ DAG_scene_update_flags(bmain, scene, scene->lay, true, false); - - /* find the last object with the tag + + /* find the last object with the tag * - all those afterwards are assumed to not be relevant for our calculations */ /* optimize further by moving out... */ @@ -334,14 +334,14 @@ static void motionpaths_calc_update_scene(Main *bmain, Scene *scene) if (base->object->flag & BA_TEMP_TAG) last = base; } - + /* perform updates for tagged objects */ /* XXX: this will break if rigs depend on scene or other data that * is animated but not attached to/updatable from objects */ for (base = scene->base.first; base; base = base->next) { /* update this object */ BKE_object_handle_update(bmain, bmain->eval_ctx, scene, base->object); - + /* if this is the last one we need to update, let's stop to save some time */ if (base == last) break; @@ -363,21 +363,21 @@ static void motionpaths_calc_update_scene(Main *bmain, Scene *scene) static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) { MPathTarget *mpt; - + /* for each target, check if it can be baked on the current frame */ for (mpt = targets->first; mpt; mpt = mpt->next) { bMotionPath *mpath = mpt->mpath; bMotionPathVert *mpv; - - /* current frame must be within the range the cache works for + + /* current frame must be within the range the cache works for * - is inclusive of the first frame, but not the last otherwise we get buffer overruns */ if ((CFRA < mpath->start_frame) || (CFRA >= mpath->end_frame)) continue; - + /* get the relevant cache vert to write to */ mpv = mpath->points + (CFRA - mpath->start_frame); - + /* pose-channel or object path baking? */ if (mpt->pchan) { /* heads or tails */ @@ -387,7 +387,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) else { copy_v3_v3(mpv->co, mpt->pchan->pose_tail); } - + /* result must be in worldspace */ mul_m4_v3(mpt->ob->obmat, mpv->co); } @@ -398,7 +398,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) } } -/* Perform baking of the given object's and/or its bones' transforms to motion paths +/* Perform baking of the given object's and/or its bones' transforms to motion paths * - scene: current scene * - ob: object whose flagged motionpaths should get calculated * - recalc: whether we need to @@ -409,15 +409,15 @@ void animviz_calc_motionpaths(Main *bmain, Scene *scene, ListBase *targets) MPathTarget *mpt; int sfra, efra; int cfra; - + /* sanity check */ if (ELEM(NULL, targets, targets->first)) return; - + /* set frame values */ cfra = CFRA; sfra = efra = cfra; - + /* TODO: this method could be improved... * 1) max range for standard baking * 2) minimum range for recalc baking (i.e. between keyframes, but how?) */ @@ -427,34 +427,34 @@ void animviz_calc_motionpaths(Main *bmain, Scene *scene, ListBase *targets) efra = MAX2(efra, mpt->mpath->end_frame); } if (efra <= sfra) return; - + /* optimize the depsgraph for faster updates */ /* TODO: whether this is used should depend on some setting for the level of optimizations used */ motionpaths_calc_optimise_depsgraph(bmain, scene, targets); - + /* calculate path over requested range */ for (CFRA = sfra; CFRA <= efra; CFRA++) { /* update relevant data for new frame */ motionpaths_calc_update_scene(bmain, scene); - + /* perform baking for targets */ motionpaths_calc_bake_targets(scene, targets); } - + /* reset original environment */ CFRA = cfra; motionpaths_calc_update_scene(bmain, scene); - + /* clear recalc flags from targets */ for (mpt = targets->first; mpt; mpt = mpt->next) { bAnimVizSettings *avs; - + /* get pointer to animviz settings for each target */ if (mpt->pchan) avs = &mpt->ob->pose->avs; else avs = &mpt->ob->avs; - + /* clear the flag requesting recalculation of targets */ avs->recalc &= ~ANIMVIZ_RECALC_PATHS; } @@ -463,7 +463,7 @@ void animviz_calc_motionpaths(Main *bmain, Scene *scene, ListBase *targets) /* ******************************************************************** */ /* Curve Paths - for curve deforms and/or curve following */ -/* free curve path data +/* free curve path data * NOTE: frees the path itself! * NOTE: this is increasingly inaccurate with non-uniform BevPoint subdivisions [#24633] */ @@ -473,7 +473,7 @@ void free_path(Path *path) MEM_freeN(path); } -/* calculate a curve-deform path for a curve +/* calculate a curve-deform path for a curve * - only called from displist.c -> do_makeDispListCurveTypes */ void calc_curvepath(Object *ob, ListBase *nurbs) @@ -486,17 +486,17 @@ void calc_curvepath(Object *ob, ListBase *nurbs) float *fp, *dist, *maxdist, xyz[3]; float fac, d = 0, fac1, fac2; int a, tot, cycl = 0; - + /* in a path vertices are with equal differences: path->len = number of verts */ /* NOW WITH BEVELCURVE!!! */ - + if (ob == NULL || ob->type != OB_CURVE) { return; } if (ob->curve_cache->path) free_path(ob->curve_cache->path); ob->curve_cache->path = NULL; - + /* weak! can only use first curve */ bl = ob->curve_cache->bev.first; if (bl == NULL || !bl->nr) { @@ -506,18 +506,18 @@ void calc_curvepath(Object *ob, ListBase *nurbs) nu = nurbs->first; ob->curve_cache->path = path = MEM_callocN(sizeof(Path), "calc_curvepath"); - + /* if POLY: last vertice != first vertice */ cycl = (bl->poly != -1); - + tot = cycl ? bl->nr : bl->nr - 1; - + path->len = tot + 1; /* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */ if (path->len < nu->resolu * SEGMENTSU(nu)) { path->len = nu->resolu * SEGMENTSU(nu); } - + dist = (float *)MEM_mallocN(sizeof(float) * (tot + 1), "calcpathdist"); /* all lengths in *dist */ @@ -530,13 +530,13 @@ void calc_curvepath(Object *ob, ListBase *nurbs) sub_v3_v3v3(xyz, bevpfirst->vec, bevp->vec); else sub_v3_v3v3(xyz, (bevp + 1)->vec, bevp->vec); - + *fp = *(fp - 1) + len_v3(xyz); bevp++; } - + path->totdist = *fp; - + /* the path verts in path->data */ /* now also with TILT value */ pp = path->data = (PathPoint *)MEM_callocN(sizeof(PathPoint) * path->len, "pathdata"); @@ -551,11 +551,11 @@ void calc_curvepath(Object *ob, ListBase *nurbs) maxdist = dist + tot; fac = 1.0f / ((float)path->len - 1.0f); fac = fac * path->totdist; - + for (a = 0; a < path->len; a++) { - + d = ((float)a) * fac; - + /* we're looking for location (distance) 'd' in the array */ if (LIKELY(tot > 0)) { while ((fp < maxdist) && (d >= *fp)) { @@ -581,10 +581,10 @@ void calc_curvepath(Object *ob, ListBase *nurbs) pp->weight = fac1 * bevp->weight + fac2 * bevpn->weight; interp_qt_qtqt(pp->quat, bevp->quat, bevpn->quat, fac2); normalize_qt(pp->quat); - + pp++; } - + MEM_freeN(dist); } @@ -628,7 +628,7 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua } path = ob->curve_cache->path; pp = path->data; - + /* test for cyclic */ bl = ob->curve_cache->bev.first; if (!bl) return 0; @@ -639,7 +639,7 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua BLI_assert(cycl || ctime >= 0.0f); ctime *= (path->len - 1); - + s1 = (int)floor(ctime); fac = (float)(s1 + 1) - ctime; diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index 96914c8d6394..05cb10ab7a49 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -104,7 +104,7 @@ bool id_type_can_have_animdata(const short id_type) case ID_GD: case ID_CF: return true; - + /* no AnimData */ default: return false; @@ -120,13 +120,13 @@ bool id_can_have_animdata(const ID *id) return id_type_can_have_animdata(GS(id->name)); } -/* Get AnimData from the given ID-block. In order for this to work, we assume that +/* Get AnimData from the given ID-block. In order for this to work, we assume that * the AnimData pointer is stored immediately after the given ID-block in the struct, * as per IdAdtTemplate. */ AnimData *BKE_animdata_from_id(ID *id) { - /* only some ID-blocks have this info for now, so we cast the + /* only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate, and extract the * AnimData that way */ @@ -138,33 +138,33 @@ AnimData *BKE_animdata_from_id(ID *id) return NULL; } -/* Add AnimData to the given ID-block. In order for this to work, we assume that +/* Add AnimData to the given ID-block. In order for this to work, we assume that * the AnimData pointer is stored immediately after the given ID-block in the struct, * as per IdAdtTemplate. Also note that */ AnimData *BKE_animdata_add_id(ID *id) { - /* Only some ID-blocks have this info for now, so we cast the + /* Only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate, and add the AnimData * to it using the template */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; - + /* check if there's already AnimData, in which case, don't add */ if (iat->adt == NULL) { AnimData *adt; - + /* add animdata */ adt = iat->adt = MEM_callocN(sizeof(AnimData), "AnimData"); - + /* set default settings */ adt->act_influence = 1.0f; } - + return iat->adt; } - else + else return NULL; } @@ -175,14 +175,14 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) { AnimData *adt = BKE_animdata_from_id(id); bool ok = false; - + /* animdata validity check */ if (adt == NULL) { BKE_report(reports, RPT_WARNING, "No AnimData to set action on"); return ok; } - - /* active action is only editable when it is not a tweaking strip + + /* active action is only editable when it is not a tweaking strip * see rna_AnimData_action_editable() in rna_animation.c */ if ((adt->flag & ADT_NLA_EDIT_ON) || (adt->actstrip) || (adt->tmpact)) { @@ -190,11 +190,11 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) BKE_report(reports, RPT_ERROR, "Cannot change action, as it is still being edited in NLA"); return ok; } - + /* manage usercount for current action */ if (adt->action) id_us_min((ID *)adt->action); - + /* assume that AnimData's action can in fact be edited... */ if (act) { /* action must have same type as owner */ @@ -217,7 +217,7 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) adt->action = NULL; ok = true; } - + return ok; } @@ -226,13 +226,13 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) /* Free AnimData used by the nominated ID-block, and clear ID-block's AnimData pointer */ void BKE_animdata_free(ID *id, const bool do_id_user) { - /* Only some ID-blocks have this info for now, so we cast the + /* Only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; AnimData *adt = iat->adt; - + /* check if there's any AnimData to start with */ if (adt) { if (do_id_user) { @@ -243,16 +243,16 @@ void BKE_animdata_free(ID *id, const bool do_id_user) if (adt->tmpact) id_us_min(&adt->tmpact->id); } - + /* free nla data */ BKE_nla_tracks_free(&adt->nla_tracks); - + /* free drivers - stored as a list of F-Curves */ free_fcurves(&adt->drivers); - + /* free overrides */ /* TODO... */ - + /* free animdata now */ MEM_freeN(adt); iat->adt = NULL; @@ -266,12 +266,12 @@ void BKE_animdata_free(ID *id, const bool do_id_user) AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action) { AnimData *dadt; - + /* sanity check before duplicating struct */ if (adt == NULL) return NULL; dadt = MEM_dupallocN(adt); - + /* make a copy of action - at worst, user has to delete copies... */ if (do_action) { BLI_assert(bmain != NULL); @@ -285,13 +285,13 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action) /* duplicate NLA data */ BKE_nla_tracks_copy(bmain, &dadt->nla_tracks, &adt->nla_tracks); - + /* duplicate drivers (F-Curves) */ copy_fcurves(&dadt->drivers, &adt->drivers); - + /* don't copy overrides */ BLI_listbase_clear(&dadt->overrides); - + /* return */ return dadt; } @@ -338,17 +338,17 @@ void BKE_animdata_merge_copy( { AnimData *src = BKE_animdata_from_id(src_id); AnimData *dst = BKE_animdata_from_id(dst_id); - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + // TODO: we must unset all "tweakmode" flags if ((src->flag & ADT_NLA_EDIT_ON) || (dst->flag & ADT_NLA_EDIT_ON)) { printf("ERROR: Merging AnimData blocks while editing NLA is dangerous as it may cause data corruption\n"); return; } - + /* handle actions... */ if (action_mode == ADT_MERGECOPY_SRC_COPY) { /* make a copy of the actions */ @@ -359,35 +359,35 @@ void BKE_animdata_merge_copy( /* make a reference to it */ dst->action = src->action; id_us_plus((ID *)dst->action); - + dst->tmpact = src->tmpact; id_us_plus((ID *)dst->tmpact); } - + /* duplicate NLA data */ if (src->nla_tracks.first) { ListBase tracks = {NULL, NULL}; - + BKE_nla_tracks_copy(bmain, &tracks, &src->nla_tracks); BLI_movelisttolist(&dst->nla_tracks, &tracks); } - + /* duplicate drivers (F-Curves) */ if (src->drivers.first) { ListBase drivers = {NULL, NULL}; - + copy_fcurves(&drivers, &src->drivers); - + /* Fix up all driver targets using the old target id * - This assumes that the src ID is being merged into the dst ID */ if (fix_drivers) { FCurve *fcu; - + for (fcu = drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar = driver->variables.first; dvar; dvar = dvar->next) { DRIVER_TARGETS_USED_LOOPER(dvar) { @@ -399,7 +399,7 @@ void BKE_animdata_merge_copy( } } } - + BLI_movelisttolist(&dst->drivers, &drivers); } } @@ -419,7 +419,7 @@ static bool animpath_matches_basepath(const char path[], const char basepath[]) return (path && basepath) && STRPREFIX(path, basepath); } -/* Move F-Curves in src action to dst action, setting up all the necessary groups +/* Move F-Curves in src action to dst action, setting up all the necessary groups * for this to happen, but only if the F-Curves being moved have the appropriate * "base path". * - This is used when data moves from one datablock to another, causing the @@ -428,7 +428,7 @@ static bool animpath_matches_basepath(const char path[], const char basepath[]) void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const char basepath[]) { FCurve *fcu, *fcn = NULL; - + /* sanity checks */ if (ELEM(NULL, srcAct, dstAct, basepath)) { if (G.debug & G_DEBUG) { @@ -437,56 +437,56 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha } return; } - - /* clear 'temp' flags on all groups in src, as we'll be needing them later + + /* clear 'temp' flags on all groups in src, as we'll be needing them later * to identify groups that we've managed to empty out here */ action_groups_clear_tempflags(srcAct); - + /* iterate over all src F-Curves, moving over the ones that need to be moved */ for (fcu = srcAct->curves.first; fcu; fcu = fcn) { /* store next pointer in case we move stuff */ fcn = fcu->next; - + /* should F-Curve be moved over? * - we only need the start of the path to match basepath */ if (animpath_matches_basepath(fcu->rna_path, basepath)) { bActionGroup *agrp = NULL; - + /* if grouped... */ if (fcu->grp) { /* make sure there will be a matching group on the other side for the migrants */ agrp = BKE_action_group_find_name(dstAct, fcu->grp->name); - + if (agrp == NULL) { /* add a new one with a similar name (usually will be the same though) */ agrp = action_groups_add_new(dstAct, fcu->grp->name); } - + /* old groups should be tagged with 'temp' flags so they can be removed later * if we remove everything from them */ fcu->grp->flag |= AGRP_TEMP; } - + /* perform the migration now */ action_groups_remove_channel(srcAct, fcu); - + if (agrp) action_groups_add_channel(dstAct, agrp, fcu); else BLI_addtail(&dstAct->curves, fcu); } } - + /* cleanup groups (if present) */ if (srcAct->groups.first) { bActionGroup *agrp, *grp = NULL; - + for (agrp = srcAct->groups.first; agrp; agrp = grp) { grp = agrp->next; - + /* only tagged groups need to be considered - clearing these tags or removing them */ if (agrp->flag & AGRP_TEMP) { /* if group is empty and tagged, then we can remove as this operation @@ -510,24 +510,24 @@ void BKE_animdata_separate_by_basepath( { AnimData *srcAdt = NULL, *dstAdt = NULL; LinkData *ld; - + /* sanity checks */ if (ELEM(NULL, srcID, dstID)) { if (G.debug & G_DEBUG) printf("ERROR: no source or destination ID to separate AnimData with\n"); return; } - + /* get animdata from src, and create for destination (if needed) */ srcAdt = BKE_animdata_from_id(srcID); dstAdt = BKE_animdata_add_id(dstID); - + if (ELEM(NULL, srcAdt, dstAdt)) { if (G.debug & G_DEBUG) printf("ERROR: no AnimData for this pair of ID's\n"); return; } - + /* active action */ if (srcAdt->action) { /* set up an action if necessary, and name it in a similar way so that it can be easily found again */ @@ -537,38 +537,38 @@ void BKE_animdata_separate_by_basepath( else if (dstAdt->action == srcAdt->action) { printf("Argh! Source and Destination share animation! ('%s' and '%s' both use '%s') Making new empty action\n", srcID->name, dstID->name, srcAdt->action->id.name); - + /* TODO: review this... */ id_us_min(&dstAdt->action->id); dstAdt->action = BKE_action_add(bmain, dstAdt->action->id.name + 2); } - + /* loop over base paths, trying to fix for each one... */ for (ld = basepaths->first; ld; ld = ld->next) { const char *basepath = (const char *)ld->data; action_move_fcurves_by_basepath(srcAdt->action, dstAdt->action, basepath); } } - + /* drivers */ if (srcAdt->drivers.first) { FCurve *fcu, *fcn = NULL; - + /* check each driver against all the base paths to see if any should go */ for (fcu = srcAdt->drivers.first; fcu; fcu = fcn) { fcn = fcu->next; - + /* try each basepath in turn, but stop on the first one which works */ for (ld = basepaths->first; ld; ld = ld->next) { const char *basepath = (const char *)ld->data; - + if (animpath_matches_basepath(fcu->rna_path, basepath)) { /* just need to change lists */ BLI_remlink(&srcAdt->drivers, fcu); BLI_addtail(&dstAdt->drivers, fcu); - + /* TODO: add depsgraph flushing calls? */ - + /* can stop now, as moved already */ break; } @@ -654,15 +654,15 @@ static bool check_rna_path_is_valid(ID *owner_id, const char *path) { PointerRNA id_ptr, ptr; PropertyRNA *prop = NULL; - + /* make initial RNA pointer to start resolving from */ RNA_id_pointer_create(owner_id, &id_ptr); - + /* try to resolve */ - return RNA_path_resolve_property(&id_ptr, path, &ptr, &prop); + return RNA_path_resolve_property(&id_ptr, path, &ptr, &prop); } -/* Check if some given RNA Path needs fixing - free the given path and set a new one as appropriate +/* Check if some given RNA Path needs fixing - free the given path and set a new one as appropriate * NOTE: we assume that oldName and newName have [" "] padding around them */ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, char *oldpath, bool verify_paths) @@ -671,7 +671,7 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o char *oldNamePtr = strstr(oldpath, oldName); int prefixLen = strlen(prefix); int oldNameLen = strlen(oldName); - + /* only start fixing the path if the prefix and oldName feature in the path, * and prefix occurs immediately before oldName */ @@ -686,20 +686,20 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o if (prefixPtr > oldpath) { BLI_dynstr_nappend(ds, oldpath, prefixPtr - oldpath); } - + /* add the prefix */ BLI_dynstr_append(ds, prefix); - + /* add the new name (complete with brackets) */ BLI_dynstr_append(ds, newName); - + /* add the postfix */ BLI_dynstr_append(ds, postfixPtr); - + /* create new path, and cleanup old data */ newPath = BLI_dynstr_get_cstring(ds); BLI_dynstr_free(ds); - + /* check if the new path will solve our problems */ /* TODO: will need to check whether this step really helps in practice */ if (!verify_paths || check_rna_path_is_valid(owner_id, newPath)) { @@ -713,31 +713,31 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o } } } - + /* the old path doesn't need to be changed */ return oldpath; } /* Check RNA-Paths for a list of F-Curves */ -static void fcurves_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, +static void fcurves_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, const char *oldKey, const char *newKey, ListBase *curves, bool verify_paths) { FCurve *fcu; - + /* we need to check every curve... */ for (fcu = curves->first; fcu; fcu = fcu->next) { if (fcu->rna_path) { const char *old_path = fcu->rna_path; - + /* firstly, handle the F-Curve's own path */ fcu->rna_path = rna_path_rename_fix(owner_id, prefix, oldKey, newKey, fcu->rna_path, verify_paths); - + /* if path changed and the F-Curve is grouped, check if its group also needs renaming * (i.e. F-Curve is first of a bone's F-Curves; hence renaming this should also trigger rename) */ if (fcu->rna_path != old_path) { bActionGroup *agrp = fcu->grp; - + if ((agrp) && STREQ(oldName, agrp->name)) { BLI_strncpy(agrp->name, newName, sizeof(agrp->name)); } @@ -751,27 +751,27 @@ static void drivers_path_rename_fix(ID *owner_id, ID *ref_id, const char *prefix const char *oldKey, const char *newKey, ListBase *curves, bool verify_paths) { FCurve *fcu; - + /* we need to check every curve - drivers are F-Curves too! */ for (fcu = curves->first; fcu; fcu = fcu->next) { /* firstly, handle the F-Curve's own path */ if (fcu->rna_path) fcu->rna_path = rna_path_rename_fix(owner_id, prefix, oldKey, newKey, fcu->rna_path, verify_paths); - + /* driver? */ if (fcu->driver) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + /* driver variables */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* only change the used targets, since the others will need fixing manually anyway */ - DRIVER_TARGETS_USED_LOOPER(dvar) + DRIVER_TARGETS_USED_LOOPER(dvar) { /* rename RNA path */ if (dtar->rna_path && dtar->id) dtar->rna_path = rna_path_rename_fix(dtar->id, prefix, oldKey, newKey, dtar->rna_path, verify_paths); - + /* also fix the bone-name (if applicable) */ if (strstr(prefix, "bones")) { if ( ((dtar->id) && (GS(dtar->id->name) == ID_OB) && (!ref_id || ((Object *)(dtar->id))->data == ref_id)) && @@ -788,18 +788,18 @@ static void drivers_path_rename_fix(ID *owner_id, ID *ref_id, const char *prefix } /* Fix all RNA-Paths for Actions linked to NLA Strips */ -static void nlastrips_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, +static void nlastrips_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, const char *oldKey, const char *newKey, ListBase *strips, bool verify_paths) { NlaStrip *strip; - + /* recursively check strips, fixing only actions... */ for (strip = strips->first; strip; strip = strip->next) { /* fix strip's action */ if (strip->act) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldKey, newKey, &strip->act->curves, verify_paths); /* ignore own F-Curves, since those are local... */ - + /* check sub-strips (if metas) */ nlastrips_path_rename_fix(owner_id, prefix, oldName, newName, oldKey, newKey, &strip->strips, verify_paths); } @@ -820,13 +820,13 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char * { char *oldN, *newN; char *result; - + /* if no action, no need to proceed */ if (ELEM(NULL, owner_id, old_path)) { if (G.debug & G_DEBUG) printf("%s: early abort\n", __func__); return old_path; } - + /* Name sanitation logic - copied from BKE_animdata_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -844,21 +844,21 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char * oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* fix given path */ if (G.debug & G_DEBUG) printf("%s | %s | oldpath = %p ", oldN, newN, old_path); result = rna_path_rename_fix(owner_id, prefix, oldN, newN, old_path, verify_paths); if (G.debug & G_DEBUG) printf("path rename result = %p\n", result); - + /* free the temp names */ MEM_freeN(oldN); MEM_freeN(newN); - + /* return the resulting path - may be the same path again if nothing changed */ return result; } -/* Fix all RNA_Paths in the given Action, relative to the given ID block +/* Fix all RNA_Paths in the given Action, relative to the given ID block * * This is just an external wrapper for the F-Curve fixing function, * with input validity checks on top of the basic method. @@ -870,11 +870,11 @@ void BKE_action_fix_paths_rename(ID *owner_id, bAction *act, const char *prefix, const char *newName, int oldSubscript, int newSubscript, bool verify_paths) { char *oldN, *newN; - + /* if no action, no need to proceed */ if (ELEM(NULL, owner_id, act)) return; - + /* Name sanitation logic - copied from BKE_animdata_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -892,10 +892,10 @@ void BKE_action_fix_paths_rename(ID *owner_id, bAction *act, const char *prefix, oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* fix paths in action */ fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &act->curves, verify_paths); - + /* free the temp names */ MEM_freeN(oldN); MEM_freeN(newN); @@ -910,11 +910,11 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons { NlaTrack *nlt; char *oldN, *newN; - + /* if no AnimData, no need to proceed */ if (ELEM(NULL, owner_id, adt)) return; - + /* Name sanitation logic - shared with BKE_action_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -932,16 +932,16 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* Active action and temp action */ if (adt->action) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &adt->action->curves, verify_paths); if (adt->tmpact) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &adt->tmpact->curves, verify_paths); - + /* Drivers - Drivers are really F-Curves */ drivers_path_rename_fix(owner_id, ref_id, prefix, oldName, newName, oldN, newN, &adt->drivers, verify_paths); - + /* NLA Data - Animation Data for Strips */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) nlastrips_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &nlt->strips, verify_paths); @@ -1031,7 +1031,7 @@ typedef struct AllFCurvesCbWrapper { static void fcurves_apply_cb(ID *id, ListBase *fcurves, ID_FCurve_Edit_Callback func, void *user_data) { FCurve *fcu; - + for (fcu = fcurves->first; fcu; fcu = fcu->next) { func(id, fcu, user_data); } @@ -1041,13 +1041,13 @@ static void fcurves_apply_cb(ID *id, ListBase *fcurves, ID_FCurve_Edit_Callback static void nlastrips_apply_all_curves_cb(ID *id, ListBase *strips, AllFCurvesCbWrapper *wrapper) { NlaStrip *strip; - + for (strip = strips->first; strip; strip = strip->next) { /* fix strip's action */ if (strip->act) { fcurves_apply_cb(id, &strip->act->curves, wrapper->func, wrapper->user_data); } - + /* check sub-strips (if metas) */ nlastrips_apply_all_curves_cb(id, &strip->strips, wrapper); } @@ -1058,18 +1058,18 @@ static void adt_apply_all_fcurves_cb(ID *id, AnimData *adt, void *wrapper_data) { AllFCurvesCbWrapper *wrapper = wrapper_data; NlaTrack *nlt; - + if (adt->action) { fcurves_apply_cb(id, &adt->action->curves, wrapper->func, wrapper->user_data); } - + if (adt->tmpact) { fcurves_apply_cb(id, &adt->tmpact->curves, wrapper->func, wrapper->user_data); } - + /* free drivers - stored as a list of F-Curves */ fcurves_apply_cb(id, &adt->drivers, wrapper->func, wrapper->user_data); - + /* NLA Data - Animation Data for Strips */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { nlastrips_apply_all_curves_cb(id, &nlt->strips, wrapper); @@ -1081,7 +1081,7 @@ void BKE_fcurves_main_cb(Main *bmain, ID_FCurve_Edit_Callback func, void *user_d { /* Wrap F-Curve operation stuff to pass to the general AnimData-level func */ AllFCurvesCbWrapper wrapper = {func, user_data}; - + /* Use the AnimData-based function so that we don't have to reimplement all that stuff */ BKE_animdata_main_cb(bmain, adt_apply_all_fcurves_cb, &wrapper); } @@ -1100,7 +1100,7 @@ void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *use AnimData *adt = BKE_animdata_from_id(id); \ if (adt) func(id, adt, user_data); \ } (void)0 - + /* "embedded" nodetree cases (i.e. scene/material/texture->nodetree) */ #define ANIMDATA_NODETREE_IDS_CB(first, NtId_Type) \ for (id = first; id; id = id->next) { \ @@ -1112,40 +1112,40 @@ void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *use } \ if (adt) func(id, adt, user_data); \ } (void)0 - + /* nodes */ ANIMDATA_IDS_CB(bmain->nodetree.first); - + /* textures */ ANIMDATA_NODETREE_IDS_CB(bmain->tex.first, Tex); - + /* lamps */ ANIMDATA_NODETREE_IDS_CB(bmain->lamp.first, Lamp); - + /* materials */ ANIMDATA_NODETREE_IDS_CB(bmain->mat.first, Material); - + /* cameras */ ANIMDATA_IDS_CB(bmain->camera.first); - + /* shapekeys */ ANIMDATA_IDS_CB(bmain->key.first); - + /* metaballs */ ANIMDATA_IDS_CB(bmain->mball.first); - + /* curves */ ANIMDATA_IDS_CB(bmain->curve.first); - + /* armatures */ ANIMDATA_IDS_CB(bmain->armature.first); - + /* lattices */ ANIMDATA_IDS_CB(bmain->latt.first); - + /* meshes */ ANIMDATA_IDS_CB(bmain->mesh.first); - + /* particles */ ANIMDATA_IDS_CB(bmain->particle.first); @@ -1160,7 +1160,7 @@ void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *use /* masks */ ANIMDATA_IDS_CB(bmain->mask.first); - + /* worlds */ ANIMDATA_NODETREE_IDS_CB(bmain->world.first, World); @@ -1169,7 +1169,7 @@ void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *use /* line styles */ ANIMDATA_IDS_CB(bmain->linestyle.first); - + /* grease pencil */ ANIMDATA_IDS_CB(bmain->gpencil.first); @@ -1186,9 +1186,9 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha { Main *bmain = G.main; /* XXX UGLY! */ ID *id; - - /* macro for less typing - * - whether animdata exists is checked for by the main renaming callback, though taking + + /* macro for less typing + * - whether animdata exists is checked for by the main renaming callback, though taking * this outside of the function may make things slightly faster? */ #define RENAMEFIX_ANIM_IDS(first) \ @@ -1196,7 +1196,7 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha AnimData *adt = BKE_animdata_from_id(id); \ BKE_animdata_fix_paths_rename(id, adt, ref_id, prefix, oldName, newName, 0, 0, 1); \ } (void)0 - + /* another version of this macro for nodetrees */ #define RENAMEFIX_ANIM_NODETREE_IDS(first, NtId_Type) \ for (id = first; id; id = id->next) { \ @@ -1208,40 +1208,40 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha } \ BKE_animdata_fix_paths_rename(id, adt, ref_id, prefix, oldName, newName, 0, 0, 1); \ } (void)0 - + /* nodes */ RENAMEFIX_ANIM_IDS(bmain->nodetree.first); - + /* textures */ RENAMEFIX_ANIM_NODETREE_IDS(bmain->tex.first, Tex); - + /* lamps */ RENAMEFIX_ANIM_NODETREE_IDS(bmain->lamp.first, Lamp); - + /* materials */ RENAMEFIX_ANIM_NODETREE_IDS(bmain->mat.first, Material); - + /* cameras */ RENAMEFIX_ANIM_IDS(bmain->camera.first); - + /* shapekeys */ RENAMEFIX_ANIM_IDS(bmain->key.first); - + /* metaballs */ RENAMEFIX_ANIM_IDS(bmain->mball.first); - + /* curves */ RENAMEFIX_ANIM_IDS(bmain->curve.first); - + /* armatures */ RENAMEFIX_ANIM_IDS(bmain->armature.first); - + /* lattices */ RENAMEFIX_ANIM_IDS(bmain->latt.first); - + /* meshes */ RENAMEFIX_ANIM_IDS(bmain->mesh.first); - + /* particles */ RENAMEFIX_ANIM_IDS(bmain->particle.first); @@ -1256,24 +1256,24 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha /* masks */ RENAMEFIX_ANIM_IDS(bmain->mask.first); - + /* worlds */ RENAMEFIX_ANIM_NODETREE_IDS(bmain->world.first, World); - + /* linestyles */ RENAMEFIX_ANIM_IDS(bmain->linestyle.first); - + /* grease pencil */ RENAMEFIX_ANIM_IDS(bmain->gpencil.first); /* cache files */ RENAMEFIX_ANIM_IDS(bmain->cachefiles.first); - + /* scenes */ RENAMEFIX_ANIM_NODETREE_IDS(bmain->scene.first, Scene); } -/* *********************************** */ +/* *********************************** */ /* KeyingSet API */ /* Finding Tools --------------------------- */ @@ -1283,50 +1283,50 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha KS_Path *BKE_keyingset_find_path(KeyingSet *ks, ID *id, const char group_name[], const char rna_path[], int array_index, int UNUSED(group_mode)) { KS_Path *ksp; - + /* sanity checks */ if (ELEM(NULL, ks, rna_path, id)) return NULL; - - /* loop over paths in the current KeyingSet, finding the first one where all settings match + + /* loop over paths in the current KeyingSet, finding the first one where all settings match * (i.e. the first one where none of the checks fail and equal 0) */ for (ksp = ks->paths.first; ksp; ksp = ksp->next) { short eq_id = 1, eq_path = 1, eq_index = 1, eq_group = 1; - + /* id */ if (id != ksp->id) eq_id = 0; - + /* path */ if ((ksp->rna_path == NULL) || !STREQ(rna_path, ksp->rna_path)) eq_path = 0; - + /* index - need to compare whole-array setting too... */ if (ksp->array_index != array_index) eq_index = 0; - + /* group */ if (group_name) { /* FIXME: these checks need to be coded... for now, it's not too important though */ } - + /* if all aspects are ok, return */ if (eq_id && eq_path && eq_index && eq_group) return ksp; } - + /* none found */ return NULL; } - + /* Defining Tools --------------------------- */ /* Used to create a new 'custom' KeyingSet for the user, that will be automatically added to the stack */ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char name[], short flag, short keyingflag) { KeyingSet *ks; - + /* allocate new KeyingSet */ ks = MEM_callocN(sizeof(KeyingSet), "KeyingSet"); @@ -1336,16 +1336,16 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam ks->flag = flag; ks->keyingflag = keyingflag; ks->keyingoverride = keyingflag; /* NOTE: assume that if one is set one way, the other should be too, so that it'll work */ - + /* add KeyingSet to list */ BLI_addtail(list, ks); - + /* Make sure KeyingSet has a unique idname */ BLI_uniquename(list, ks, DATA_("KeyingSet"), '.', offsetof(KeyingSet, idname), sizeof(ks->idname)); - + /* Make sure KeyingSet has a unique label (this helps with identification) */ BLI_uniquename(list, ks, DATA_("Keying Set"), '.', offsetof(KeyingSet, name), sizeof(ks->name)); - + /* return new KeyingSet for further editing */ return ks; } @@ -1356,55 +1356,55 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam KS_Path *BKE_keyingset_add_path(KeyingSet *ks, ID *id, const char group_name[], const char rna_path[], int array_index, short flag, short groupmode) { KS_Path *ksp; - + /* sanity checks */ if (ELEM(NULL, ks, rna_path)) { printf("ERROR: no Keying Set and/or RNA Path to add path with\n"); return NULL; } - + /* ID is required for all types of KeyingSets */ if (id == NULL) { printf("ERROR: No ID provided for Keying Set Path\n"); return NULL; } - + /* don't add if there is already a matching KS_Path in the KeyingSet */ if (BKE_keyingset_find_path(ks, id, group_name, rna_path, array_index, groupmode)) { if (G.debug & G_DEBUG) printf("ERROR: destination already exists in Keying Set\n"); return NULL; } - + /* allocate a new KeyingSet Path */ ksp = MEM_callocN(sizeof(KS_Path), "KeyingSet Path"); - + /* just store absolute info */ ksp->id = id; if (group_name) BLI_strncpy(ksp->group, group_name, sizeof(ksp->group)); else ksp->group[0] = '\0'; - + /* store additional info for relative paths (just in case user makes the set relative) */ if (id) ksp->idtype = GS(id->name); - + /* just copy path info */ /* TODO: should array index be checked too? */ ksp->rna_path = BLI_strdup(rna_path); ksp->array_index = array_index; - + /* store flags */ ksp->flag = flag; ksp->groupmode = groupmode; - + /* add KeyingSet path to KeyingSet */ BLI_addtail(&ks->paths, ksp); - + /* return this path */ return ksp; -} +} /* Free the given Keying Set path */ void BKE_keyingset_free_path(KeyingSet *ks, KS_Path *ksp) @@ -1426,12 +1426,12 @@ void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) { KeyingSet *ksn; KS_Path *kspn; - + BLI_duplicatelist(newlist, list); for (ksn = newlist->first; ksn; ksn = ksn->next) { BLI_duplicatelist(&ksn->paths, &ksn->paths); - + for (kspn = ksn->paths.first; kspn; kspn = kspn->next) kspn->rna_path = MEM_dupallocN(kspn->rna_path); } @@ -1443,11 +1443,11 @@ void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) void BKE_keyingset_free(KeyingSet *ks) { KS_Path *ksp, *kspn; - + /* sanity check */ if (ks == NULL) return; - + /* free each path as we go to avoid looping twice */ for (ksp = ks->paths.first; ksp; ksp = kspn) { kspn = ksp->next; @@ -1459,12 +1459,12 @@ void BKE_keyingset_free(KeyingSet *ks) void BKE_keyingsets_free(ListBase *list) { KeyingSet *ks, *ksn; - + /* sanity check */ if (list == NULL) return; - - /* loop over KeyingSets freeing them + + /* loop over KeyingSets freeing them * - BKE_keyingset_free() doesn't free the set itself, but it frees its sub-data */ for (ks = list->first; ks; ks = ksn) { @@ -1477,7 +1477,7 @@ void BKE_keyingsets_free(ListBase *list) /* ***************************************** */ /* Evaluation Data-Setting Backend */ -/* Retrieve string to act as RNA-path, adjusted using mapping-table if provided +/* Retrieve string to act as RNA-path, adjusted using mapping-table if provided * It returns whether the string needs to be freed (i.e. if it was a temp remapped one) * // FIXME: maybe it would be faster if we didn't have to alloc/free strings like this all the time, but for now it's safer * @@ -1564,7 +1564,7 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val PropertyRNA *prop = anim_rna->prop; PointerRNA *ptr = &anim_rna->ptr; int array_index = anim_rna->prop_index; - + /* caller must ensure this is animatable */ BLI_assert(RNA_property_animateable(ptr, prop) || ptr->id.data == NULL); @@ -1697,13 +1697,13 @@ bool BKE_animsys_execute_fcurve(PointerRNA *ptr, AnimMapper *remap, FCurve *fcu, return ok; } -/* Evaluate all the F-Curves in the given list +/* Evaluate all the F-Curves in the given list * This performs a set of standard checks. If extra checks are required, separate code should be used */ static void animsys_evaluate_fcurves(PointerRNA *ptr, ListBase *list, AnimMapper *remap, float ctime) { FCurve *fcu; - + /* calculate then execute each curve */ for (fcu = list->first; fcu; fcu = fcu->next) { /* check if this F-Curve doesn't belong to a muted group */ @@ -1727,14 +1727,14 @@ static void animsys_evaluate_fcurves(PointerRNA *ptr, ListBase *list, AnimMapper static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime) { FCurve *fcu; - + /* drivers are stored as F-Curves, but we cannot use the standard code, as we need to check if * the depsgraph requested that this driver be evaluated... */ for (fcu = adt->drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; bool ok = false; - + /* check if this driver's curve should be skipped */ if ((fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) == 0) { /* check if driver itself is tagged for recalculation */ @@ -1749,13 +1749,13 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime const float curval = calculate_fcurve(&anim_rna, fcu, ctime); ok = animsys_write_rna_setting(&anim_rna, curval); } - + /* clear recalc flag */ driver->flag &= ~DRIVER_FLAG_RECALC; - + /* set error-flag if evaluation failed */ if (ok == 0) - driver->flag |= DRIVER_FLAG_INVALID; + driver->flag |= DRIVER_FLAG_INVALID; } } } @@ -1771,13 +1771,13 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime static void action_idcode_patch_check(ID *id, bAction *act) { int idcode = 0; - + /* just in case */ if (ELEM(NULL, id, act)) return; else idcode = GS(id->name); - + /* the actual checks... hopefully not too much of a performance hit in the long run... */ if (act->idroot == 0) { /* use the current root if not set already (i.e. newly created actions and actions from 2.50-2.57 builds) @@ -1801,17 +1801,17 @@ static void action_idcode_patch_check(ID *id, bAction *act) void animsys_evaluate_action_group(PointerRNA *ptr, bAction *act, bActionGroup *agrp, AnimMapper *remap, float ctime) { FCurve *fcu; - + /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ if (ELEM(NULL, act, agrp)) return; if ((remap) && (remap->target != act)) remap = NULL; - + action_idcode_patch_check(ptr->id.data, act); - + /* if group is muted, don't evaluated any of the F-Curve */ if (agrp->flag & AGRP_MUTED) return; - + /* calculate then execute each curve */ for (fcu = agrp->channels.first; (fcu) && (fcu->grp == agrp); fcu = fcu->next) { /* check if this curve should be skipped */ @@ -1831,9 +1831,9 @@ void animsys_evaluate_action(PointerRNA *ptr, bAction *act, AnimMapper *remap, f /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ if (act == NULL) return; if ((remap) && (remap->target != act)) remap = NULL; - + action_idcode_patch_check(ptr->id.data, act); - + /* calculate then execute each curve */ animsys_evaluate_fcurves(ptr, &act->curves, remap, ctime); } @@ -1847,7 +1847,7 @@ static float nlastrip_get_influence(NlaStrip *strip, float cframe) /* sanity checks - normalize the blendin/out values? */ strip->blendin = fabsf(strip->blendin); strip->blendout = fabsf(strip->blendout); - + /* result depends on where frame is in respect to blendin/out values */ if (IS_EQF(strip->blendin, 0.0f) == false && (cframe <= (strip->start + strip->blendin))) { /* there is some blend-in */ @@ -1869,14 +1869,14 @@ static void nlastrip_evaluate_controls(NlaStrip *strip, float ctime) /* now strip's evaluate F-Curves for these settings (if applicable) */ if (strip->fcurves.first) { PointerRNA strip_ptr; - + /* create RNA-pointer needed to set values */ RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr); - + /* execute these settings as per normal */ animsys_evaluate_fcurves(&strip_ptr, &strip->fcurves, NULL, ctime); } - + /* analytically generate values for influence and time (if applicable) * - we do this after the F-Curves have been evaluated to override the effects of those * in case the override has been turned off. @@ -1901,7 +1901,7 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short NlaStrip *strip, *estrip = NULL; NlaEvalStrip *nes; short side = 0; - + /* loop over strips, checking if they fall within the range */ for (strip = strips->first; strip; strip = strip->next) { /* check if current time occurs within this strip */ @@ -1911,53 +1911,53 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short side = NES_TIME_WITHIN; break; } - + /* if time occurred before current strip... */ if (ctime < strip->start) { if (strip == strips->first) { /* before first strip - only try to use it if it extends backwards in time too */ if (strip->extendmode == NLASTRIP_EXTEND_HOLD) estrip = strip; - + /* side is 'before' regardless of whether there's a useful strip */ side = NES_TIME_BEFORE; } else { - /* before next strip - previous strip has ended, but next hasn't begun, + /* before next strip - previous strip has ended, but next hasn't begun, * so blending mode depends on whether strip is being held or not... * - only occurs when no transition strip added, otherwise the transition would have * been picked up above... */ strip = strip->prev; - + if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) estrip = strip; side = NES_TIME_AFTER; } break; } - + /* if time occurred after current strip... */ if (ctime > strip->end) { /* only if this is the last strip should we do anything, and only if that is being held */ if (strip == strips->last) { if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) estrip = strip; - + side = NES_TIME_AFTER; break; } - + /* otherwise, skip... as the 'before' case will catch it more elegantly! */ } } - + /* check if a valid strip was found * - must not be muted (i.e. will have contribution */ - if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) + if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) return NULL; - + /* if ctime was not within the boundaries of the strip, clamp! */ switch (side) { case NES_TIME_BEFORE: /* extend first frame only */ @@ -1967,8 +1967,8 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short ctime = estrip->end; break; } - - /* evaluate strip's evaluation controls + + /* evaluate strip's evaluation controls * - skip if no influence (i.e. same effect as muting the strip) * - negative influence is not supported yet... how would that be defined? */ @@ -1976,12 +1976,12 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short nlastrip_evaluate_controls(estrip, ctime); if (estrip->influence <= 0.0f) return NULL; - + /* check if strip has valid data to evaluate, * and/or perform any additional type-specific actions */ switch (estrip->type) { - case NLASTRIP_TYPE_CLIP: + case NLASTRIP_TYPE_CLIP: /* clip must have some action to evaluate */ if (estrip->act == NULL) return NULL; @@ -1990,51 +1990,51 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short /* there must be strips to transition from and to (i.e. prev and next required) */ if (ELEM(NULL, estrip->prev, estrip->next)) return NULL; - + /* evaluate controls for the relevant extents of the bordering strips... */ nlastrip_evaluate_controls(estrip->prev, estrip->start); nlastrip_evaluate_controls(estrip->next, estrip->end); break; } - + /* add to list of strips we need to evaluate */ nes = MEM_callocN(sizeof(NlaEvalStrip), "NlaEvalStrip"); - + nes->strip = estrip; nes->strip_mode = side; nes->track_index = index; nes->strip_time = estrip->strip_time; - + if (list) BLI_addtail(list, nes); - + return nes; } /* ---------------------- */ -/* find an NlaEvalChannel that matches the given criteria +/* find an NlaEvalChannel that matches the given criteria * - ptr and prop are the RNA data to find a match for */ static NlaEvalChannel *nlaevalchan_find_match(ListBase *channels, PointerRNA *ptr, PropertyRNA *prop, int array_index) { NlaEvalChannel *nec; - + /* sanity check */ if (channels == NULL) return NULL; - + /* loop through existing channels, checking for a channel which affects the same property */ for (nec = channels->first; nec; nec = nec->next) { /* - comparing the PointerRNA's is done by comparing the pointers * to the actual struct the property resides in, since that all the - * other data stored in PointerRNA cannot allow us to definitively - * identify the data + * other data stored in PointerRNA cannot allow us to definitively + * identify the data */ if ((nec->ptr.data == ptr->data) && (nec->prop == prop) && (nec->index == array_index)) return nec; } - + /* not found */ return NULL; } @@ -2045,9 +2045,9 @@ static void nlaevalchan_value_init(NlaEvalChannel *nec) PointerRNA *ptr = &nec->ptr; PropertyRNA *prop = nec->prop; int index = nec->index; - - /* NOTE: while this doesn't work for all RNA properties as default values aren't in fact - * set properly for most of them, at least the common ones (which also happen to get used + + /* NOTE: while this doesn't work for all RNA properties as default values aren't in fact + * set properly for most of them, at least the common ones (which also happen to get used * in NLA strips a lot, e.g. scale) are set correctly. */ switch (RNA_property_type(prop)) { @@ -2086,15 +2086,15 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, ListBase *channels, N PointerRNA new_ptr; char *path = NULL; /* short free_path = 0; */ - + /* sanity checks */ if (channels == NULL) return NULL; - + /* get RNA pointer+property info from F-Curve for more convenient handling */ /* get path, remapped as appropriate to work in its new environment */ /* free_path = */ /* UNUSED */ animsys_remap_path(strip->remap, fcu->rna_path, &path); - + /* a valid property must be available, and it must be animatable */ if (RNA_path_resolve_property(ptr, path, &new_ptr, &prop) == false) { if (G.debug & G_DEBUG) printf("NLA Strip Eval: Cannot resolve path\n"); @@ -2105,27 +2105,27 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, ListBase *channels, N if (G.debug & G_DEBUG) printf("NLA Strip Eval: Property not animatable\n"); return NULL; } - + /* try to find a match */ nec = nlaevalchan_find_match(channels, &new_ptr, prop, fcu->array_index); - + /* allocate a new struct for this if none found */ if (nec == NULL) { nec = MEM_callocN(sizeof(NlaEvalChannel), "NlaEvalChannel"); BLI_addtail(channels, nec); - + /* store property links for writing to the property later */ nec->ptr = new_ptr; nec->prop = prop; nec->index = fcu->array_index; - + /* initialise value using default value of property [#35856] */ nlaevalchan_value_init(nec); *newChan = true; } else *newChan = false; - + /* we can now return */ return nec; } @@ -2136,7 +2136,7 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float NlaStrip *strip = nes->strip; short blendmode = strip->blendmode; float inf = strip->influence; - + /* for replace blend mode, and if this is the first strip, * just replace the value regardless of the influence */ if (newChan && blendmode == NLASTRIP_MODE_REPLACE) { @@ -2147,36 +2147,36 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float /* if this is being performed as part of transition evaluation, incorporate * an additional weighting factor for the influence */ - if (nes->strip_mode == NES_TIME_TRANSITION_END) + if (nes->strip_mode == NES_TIME_TRANSITION_END) inf *= nes->strip_time; - + /* optimisation: no need to try applying if there is no influence */ if (IS_EQF(inf, 0.0f)) return; - + /* perform blending */ switch (blendmode) { case NLASTRIP_MODE_ADD: /* simply add the scaled value on to the stack */ nec->value += (value * inf); break; - + case NLASTRIP_MODE_SUBTRACT: /* simply subtract the scaled value from the stack */ nec->value -= (value * inf); break; - + case NLASTRIP_MODE_MULTIPLY: /* multiply the scaled value with the stack */ - /* Formula Used: - * result = fac * (a * b) + (1 - fac) * a + /* Formula Used: + * result = fac * (a * b) + (1 - fac) * a */ nec->value = inf * (nec->value * value) + (1 - inf) * nec->value; break; - + case NLASTRIP_MODE_REPLACE: default: /* TODO: do we really want to blend by default? it seems more uses might prefer add... */ - /* do linear interpolation - * - the influence of the accumulated data (elsewhere, that is called dstweight) + /* do linear interpolation + * - the influence of the accumulated data (elsewhere, that is called dstweight) * is 1 - influence, since the strip's influence is srcweight */ nec->value = nec->value * (1.0f - inf) + (value * inf); @@ -2188,19 +2188,19 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buffer, NlaEvalStrip *nes) { NlaEvalChannel *nec, *necn, *necd; - + /* optimize - abort if no channels */ if (BLI_listbase_is_empty(tmp_buffer)) return; - + /* accumulate results in tmp_channels buffer to the accumulation buffer */ for (nec = tmp_buffer->first; nec; nec = necn) { /* get pointer to next channel in case we remove the current channel from the temp-buffer */ necn = nec->next; - + /* try to find an existing matching channel for this setting in the accumulation buffer */ necd = nlaevalchan_find_match(channels, &nec->ptr, nec->prop, nec->index); - + /* if there was a matching channel already in the buffer, accumulate to it, * otherwise, add the current channel to the buffer for efficiency */ @@ -2211,7 +2211,7 @@ static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buf BLI_addtail(channels, nec); } } - + /* free temp-channels that haven't been assimilated into the buffer */ BLI_freelistN(tmp_buffer); } @@ -2223,7 +2223,7 @@ static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buf static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, ListBase *list2) { FModifier *fcm1, *fcm2; - + /* if list1 is invalid... */ if (ELEM(NULL, list1, list1->first)) { if (list2 && list2->first) { @@ -2237,15 +2237,15 @@ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, Li result->last = list1->last; } else { - /* list1 should be added first, and list2 second, with the endpoints of these being the endpoints for result + /* list1 should be added first, and list2 second, with the endpoints of these being the endpoints for result * - the original lists must be left unchanged though, as we need that fact for restoring */ result->first = list1->first; result->last = list2->last; - + fcm1 = list1->last; fcm2 = list2->first; - + fcm1->next = fcm2; fcm2->prev = fcm1; } @@ -2255,17 +2255,17 @@ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, Li static void nlaeval_fmodifiers_split_stacks(ListBase *list1, ListBase *list2) { FModifier *fcm1, *fcm2; - + /* if list1/2 is invalid... just skip */ if (ELEM(NULL, list1, list2)) return; if (ELEM(NULL, list1->first, list2->first)) return; - + /* get endpoints */ fcm1 = list1->last; fcm2 = list2->first; - + /* clear their links */ fcm1->next = NULL; fcm2->prev = NULL; @@ -2281,48 +2281,48 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, ListBase *channels, Li NlaStrip *strip = nes->strip; FCurve *fcu; float evaltime; - + /* sanity checks for action */ if (strip == NULL) return; - + if (strip->act == NULL) { printf("NLA-Strip Eval Error: Strip '%s' has no Action\n", strip->name); return; } - + action_idcode_patch_check(ptr->id.data, strip->act); - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); - + /* evaluate strip's modifiers which modify time to evaluate the base curves at */ storage = evaluate_fmodifiers_storage_new(&tmp_modifiers); evaltime = evaluate_time_fmodifiers(storage, &tmp_modifiers, NULL, 0.0f, strip->strip_time); - + /* evaluate all the F-Curves in the action, saving the relevant pointers to data that will need to be used */ for (fcu = strip->act->curves.first; fcu; fcu = fcu->next) { NlaEvalChannel *nec; float value = 0.0f; bool newChan; - + /* check if this curve should be skipped */ if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) continue; if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) continue; - - /* evaluate the F-Curve's value for the time given in the strip - * NOTE: we use the modified time here, since strip's F-Curve Modifiers are applied on top of this + + /* evaluate the F-Curve's value for the time given in the strip + * NOTE: we use the modified time here, since strip's F-Curve Modifiers are applied on top of this */ value = evaluate_fcurve(fcu, evaltime); - - /* apply strip's F-Curve Modifiers on this value + + /* apply strip's F-Curve Modifiers on this value * NOTE: we apply the strip's original evaluation time not the modified one (as per standard F-Curve eval) */ evaluate_value_fmodifiers(storage, &tmp_modifiers, fcu, &value, strip->strip_time); - - + + /* get an NLA evaluation channel to work with, and accumulate the evaluated value with the value(s) * stored in this channel if it has been used already */ @@ -2345,11 +2345,11 @@ static void nlastrip_evaluate_transition(PointerRNA *ptr, ListBase *channels, Li ListBase tmp_modifiers = {NULL, NULL}; NlaEvalStrip tmp_nes; NlaStrip *s1, *s2; - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &nes->strip->modifiers, modifiers); - - /* get the two strips to operate on + + /* get the two strips to operate on * - we use the endpoints of the strips directly flanking our strip * using these as the endpoints of the transition (destination and source) * - these should have already been determined to be valid... @@ -2364,8 +2364,8 @@ static void nlastrip_evaluate_transition(PointerRNA *ptr, ListBase *channels, Li s1 = nes->strip->prev; s2 = nes->strip->next; } - - /* prepare template for 'evaluation strip' + + /* prepare template for 'evaluation strip' * - based on the transition strip's evaluation strip data * - strip_mode is NES_TIME_TRANSITION_* based on which endpoint * - strip_time is the 'normalized' (i.e. in-strip) time for evaluation, @@ -2373,23 +2373,23 @@ static void nlastrip_evaluate_transition(PointerRNA *ptr, ListBase *channels, Li * which allows us to appear to be 'interpolating' between the two extremes */ tmp_nes = *nes; - + /* evaluate these strips into a temp-buffer (tmp_channels) */ /* FIXME: modifier evaluation here needs some work... */ /* first strip */ tmp_nes.strip_mode = NES_TIME_TRANSITION_START; tmp_nes.strip = s1; nlastrip_evaluate(ptr, &tmp_channels, &tmp_modifiers, &tmp_nes); - + /* second strip */ tmp_nes.strip_mode = NES_TIME_TRANSITION_END; tmp_nes.strip = s2; nlastrip_evaluate(ptr, &tmp_channels, &tmp_modifiers, &tmp_nes); - - + + /* accumulate temp-buffer and full-buffer, using the 'real' strip */ nlaevalchan_buffers_accumulate(channels, &tmp_channels, nes); - + /* unlink this strip's modifiers from the parent's modifiers again */ nlaeval_fmodifiers_split_stacks(&nes->strip->modifiers, modifiers); } @@ -2401,32 +2401,32 @@ static void nlastrip_evaluate_meta(PointerRNA *ptr, ListBase *channels, ListBase NlaStrip *strip = nes->strip; NlaEvalStrip *tmp_nes; float evaltime; - + /* meta-strip was calculated normally to have some time to be evaluated at * and here we 'look inside' the meta strip, treating it as a decorated window to - * it's child strips, which get evaluated as if they were some tracks on a strip + * it's child strips, which get evaluated as if they were some tracks on a strip * (but with some extra modifiers to apply). * * NOTE: keep this in sync with animsys_evaluate_nla() */ - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ - nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); - + nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); + /* find the child-strip to evaluate */ evaltime = (nes->strip_time * (strip->end - strip->start)) + strip->start; tmp_nes = nlastrips_ctime_get_strip(NULL, &strip->strips, -1, evaltime); - - /* directly evaluate child strip into accumulation buffer... + + /* directly evaluate child strip into accumulation buffer... * - there's no need to use a temporary buffer (as it causes issues [T40082]) */ if (tmp_nes) { nlastrip_evaluate(ptr, channels, &tmp_modifiers, tmp_nes); - + /* free temp eval-strip */ MEM_freeN(tmp_nes); } - + /* unlink this strip's modifiers from the parent's modifiers again */ nlaeval_fmodifiers_split_stacks(&strip->modifiers, modifiers); } @@ -2435,7 +2435,7 @@ static void nlastrip_evaluate_meta(PointerRNA *ptr, ListBase *channels, ListBase void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, NlaEvalStrip *nes) { NlaStrip *strip = nes->strip; - + /* to prevent potential infinite recursion problems (i.e. transition strip, beside meta strip containing a transition * several levels deep inside it), we tag the current strip as being evaluated, and clear this when we leave */ @@ -2443,7 +2443,7 @@ void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, if (strip->flag & NLASTRIP_FLAG_EDIT_TOUCHED) return; strip->flag |= NLASTRIP_FLAG_EDIT_TOUCHED; - + /* actions to take depend on the type of strip */ switch (strip->type) { case NLASTRIP_TYPE_CLIP: /* action-clip */ @@ -2455,11 +2455,11 @@ void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, case NLASTRIP_TYPE_META: /* meta */ nlastrip_evaluate_meta(ptr, channels, modifiers, nes); break; - + default: /* do nothing */ break; } - + /* clear temp recursion safe-check */ strip->flag &= ~NLASTRIP_FLAG_EDIT_TOUCHED; } @@ -2468,18 +2468,18 @@ void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, void nladata_flush_channels(ListBase *channels) { NlaEvalChannel *nec; - + /* sanity checks */ if (channels == NULL) return; - + /* for each channel with accumulated values, write its value on the property it affects */ for (nec = channels->first; nec; nec = nec->next) { PointerRNA *ptr = &nec->ptr; PropertyRNA *prop = nec->prop; int array_index = nec->index; float value = nec->value; - + /* write values - see animsys_write_rna_setting() to sync the code */ switch (RNA_property_type(prop)) { case PROP_BOOLEAN: @@ -2524,19 +2524,19 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData NlaTrack *nlt; short track_index = 0; bool has_strips = false; - + ListBase estrips = {NULL, NULL}; NlaEvalStrip *nes; - + NlaStrip dummy_strip = {NULL}; /* dummy strip for active action */ - - + + /* 1. get the stack of strips to evaluate at current time (influence calculated here) */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next, track_index++) { /* stop here if tweaking is on and this strip is the tweaking track (it will be the first one that's 'disabled')... */ if ((adt->flag & ADT_NLA_EDIT_ON) && (nlt->flag & NLATRACK_DISABLED)) break; - + /* solo and muting are mutually exclusive... */ if (adt->flag & ADT_NLA_SOLO_TRACK) { /* skip if there is a solo track, but this isn't it */ @@ -2546,24 +2546,24 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData } else { /* no solo tracks - skip track if muted */ - if (nlt->flag & NLATRACK_MUTED) + if (nlt->flag & NLATRACK_MUTED) continue; } - - /* if this track has strips (but maybe they won't be suitable), set has_strips + + /* if this track has strips (but maybe they won't be suitable), set has_strips * - used for mainly for still allowing normal action evaluation... */ if (nlt->strips.first) has_strips = true; - + /* otherwise, get strip to evaluate for this channel */ nes = nlastrips_ctime_get_strip(&estrips, &nlt->strips, track_index, ctime); if (nes) nes->track = nlt; } - + /* add 'active' Action (may be tweaking track) as last strip to evaluate in NLA stack * - only do this if we're not exclusively evaluating the 'solo' NLA-track - * - however, if the 'solo' track houses the current 'tweaking' strip, + * - however, if the 'solo' track houses the current 'tweaking' strip, * then we should allow this to play, otherwise nothing happens */ if ((adt->action) && ((adt->flag & ADT_NLA_SOLO_TRACK) == 0 || (adt->flag & ADT_NLA_EDIT_ON))) { @@ -2571,9 +2571,9 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData if ((has_strips) || (adt->actstrip)) { /* make dummy NLA strip, and add that to the stack */ ListBase dummy_trackslist; - + dummy_trackslist.first = dummy_trackslist.last = &dummy_strip; - + if ((nlt) && !(adt->flag & ADT_NLA_EDIT_NOMAP)) { /* edit active action in-place according to its active strip, so copy the data */ memcpy(&dummy_strip, adt->actstrip, sizeof(NlaStrip)); @@ -2583,20 +2583,20 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData /* set settings of dummy NLA strip from AnimData settings */ dummy_strip.act = adt->action; dummy_strip.remap = adt->remap; - + /* action range is calculated taking F-Modifiers into account (which making new strips doesn't do due to the troublesome nature of that) */ calc_action_range(dummy_strip.act, &dummy_strip.actstart, &dummy_strip.actend, 1); dummy_strip.start = dummy_strip.actstart; dummy_strip.end = (IS_EQF(dummy_strip.actstart, dummy_strip.actend)) ? (dummy_strip.actstart + 1.0f) : (dummy_strip.actend); - + dummy_strip.blendmode = adt->act_blendmode; dummy_strip.extendmode = adt->act_extendmode; dummy_strip.influence = adt->act_influence; - + /* NOTE: must set this, or else the default setting overrides, and this setting doesn't work */ dummy_strip.flag |= NLASTRIP_FLAG_USR_INFLUENCE; } - + /* add this to our list of evaluation strips */ nlastrips_ctime_get_strip(&estrips, &dummy_trackslist, -1, ctime); } @@ -2604,22 +2604,22 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData /* special case - evaluate as if there isn't any NLA data */ /* TODO: this is really just a stop-gap measure... */ if (G.debug & G_DEBUG) printf("NLA Eval: Stopgap for active action on NLA Stack - no strips case\n"); - + animsys_evaluate_action(ptr, adt->action, adt->remap, ctime); BLI_freelistN(&estrips); return; } } - + /* only continue if there are strips to evaluate */ if (BLI_listbase_is_empty(&estrips)) return; - - + + /* 2. for each strip, evaluate then accumulate on top of existing channels, but don't set values yet */ for (nes = estrips.first; nes; nes = nes->next) nlastrip_evaluate(ptr, echannels, NULL, nes); - + /* 3. free temporary evaluation data that's not used elsewhere */ BLI_freelistN(&estrips); @@ -2635,7 +2635,7 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData } } -/* NLA Evaluation function (mostly for use through do_animdata) +/* NLA Evaluation function (mostly for use through do_animdata) * - All channels that will be affected are not cleared anymore. Instead, we just evaluate into * some temp channels, where values can be accumulated in one go. */ @@ -2648,15 +2648,15 @@ static void animsys_calculate_nla(PointerRNA *ptr, AnimData *adt, float ctime) /* evaluate the NLA stack, obtaining a set of values to flush */ animsys_evaluate_nla(&echannels, ptr, adt, ctime); - + /* flush effects of accumulating channels in NLA to the actual data they affect */ nladata_flush_channels(&echannels); - + /* free temp data */ BLI_freelistN(&echannels); } -/* ***************************************** */ +/* ***************************************** */ /* Overrides System - Public API */ /* Clear all overrides */ @@ -2676,7 +2676,7 @@ AnimOverride *BKE_animsys_validate_override(PointerRNA *UNUSED(ptr), char *UNUSE static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) { AnimOverride *aor; - + /* for each override, simply execute... */ for (aor = adt->overrides.first; aor; aor = aor->next) { PathResolvedRNA anim_rna; @@ -2720,7 +2720,7 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) * However, the code for this is relatively harmless, so is left in the code for now. */ -/* Evaluation loop for evaluation animation data +/* Evaluation loop for evaluation animation data * * This assumes that the animation-data provided belongs to the ID block in question, * and that the flags for which parts of the anim-data settings need to be recalculated @@ -2729,14 +2729,14 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) void BKE_animsys_evaluate_animdata(Scene *scene, ID *id, AnimData *adt, float ctime, short recalc) { PointerRNA id_ptr; - + /* sanity checks */ if (ELEM(NULL, id, adt)) return; - + /* get pointer to ID-block for RNA to use */ RNA_id_pointer_create(id, &id_ptr); - + /* recalculate keyframe data: * - NLA before Active Action, as Active Action behaves as 'tweaking track' * that overrides 'rough' work in NLA @@ -2745,7 +2745,7 @@ void BKE_animsys_evaluate_animdata(Scene *scene, ID *id, AnimData *adt, float ct if ((recalc & ADT_RECALC_ANIM) || (adt->recalc & ADT_RECALC_ANIM)) { /* evaluate NLA data */ if ((adt->nla_tracks.first) && !(adt->flag & ADT_NLA_EVAL_OFF)) { - /* evaluate NLA-stack + /* evaluate NLA-stack * - active action is evaluated as part of the NLA stack as the last item */ animsys_calculate_nla(&id_ptr, adt, ctime); @@ -2753,13 +2753,13 @@ void BKE_animsys_evaluate_animdata(Scene *scene, ID *id, AnimData *adt, float ct /* evaluate Active Action only */ else if (adt->action) animsys_evaluate_action(&id_ptr, adt->action, adt->remap, ctime); - + /* reset tag */ adt->recalc &= ~ADT_RECALC_ANIM; } - - /* recalculate drivers - * - Drivers need to be evaluated afterwards, as they can either override + + /* recalculate drivers + * - Drivers need to be evaluated afterwards, as they can either override * or be layered on top of existing animation data. * - Drivers should be in the appropriate order to be evaluated without problems... */ @@ -2769,22 +2769,22 @@ void BKE_animsys_evaluate_animdata(Scene *scene, ID *id, AnimData *adt, float ct { animsys_evaluate_drivers(&id_ptr, adt, ctime); } - - /* always execute 'overrides' + + /* always execute 'overrides' * - Overrides allow editing, by overwriting the value(s) set from animation-data, with the - * value last set by the user (and not keyframed yet). + * value last set by the user (and not keyframed yet). * - Overrides are cleared upon frame change and/or keyframing * - It is best that we execute this every time, so that no errors are likely to occur. */ animsys_evaluate_overrides(&id_ptr, adt); - + /* execute and clear all cached property update functions */ if (scene) { Main *bmain = G.main; // xxx - to get passed in! RNA_property_update_cache_flush(bmain, scene); RNA_property_update_cache_free(); } - + /* clear recalc flag now */ adt->recalc = 0; } @@ -2802,10 +2802,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime) if (G.debug & G_DEBUG) printf("Evaluate all animation - %f\n", ctime); - - /* macros for less typing + + /* macros for less typing * - only evaluate animation data for id if it has users (and not just fake ones) - * - whether animdata exists is checked for by the evaluation function, though taking + * - whether animdata exists is checked for by the evaluation function, though taking * this outside of the function may make things slightly faster? */ #define EVAL_ANIM_IDS(first, aflag) \ @@ -2816,8 +2816,8 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime) } \ } (void)0 - /* another macro for the "embedded" nodetree cases - * - this is like EVAL_ANIM_IDS, but this handles the case "embedded nodetrees" + /* another macro for the "embedded" nodetree cases + * - this is like EVAL_ANIM_IDS, but this handles the case "embedded nodetrees" * (i.e. scene/material/texture->nodetree) which we need a special exception * for, otherwise they'd get skipped * - ntp = "node tree parent" = datablock where node tree stuff resides @@ -2834,10 +2834,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime) BKE_animsys_evaluate_animdata(scene, id, adt, ctime, aflag); \ } \ } (void)0 - - /* optimization: - * when there are no actions, don't go over database and loop over heaps of datablocks, - * which should ultimately be empty, since it is not possible for now to have any animation + + /* optimization: + * when there are no actions, don't go over database and loop over heaps of datablocks, + * which should ultimately be empty, since it is not possible for now to have any animation * without some actions, and drivers wouldn't get affected by any state changes * * however, if there are some curves, we will need to make sure that their 'ctime' property gets @@ -2846,46 +2846,46 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime) if (BLI_listbase_is_empty(&main->action) && BLI_listbase_is_empty(&main->curve)) { if (G.debug & G_DEBUG) printf("\tNo Actions, so no animation needs to be evaluated...\n"); - + return; } - + /* nodes */ EVAL_ANIM_IDS(main->nodetree.first, ADT_RECALC_ANIM); - + /* textures */ EVAL_ANIM_NODETREE_IDS(main->tex.first, Tex, ADT_RECALC_ANIM); - + /* lamps */ EVAL_ANIM_NODETREE_IDS(main->lamp.first, Lamp, ADT_RECALC_ANIM); - + /* materials */ EVAL_ANIM_NODETREE_IDS(main->mat.first, Material, ADT_RECALC_ANIM); - + /* cameras */ EVAL_ANIM_IDS(main->camera.first, ADT_RECALC_ANIM); - + /* shapekeys */ EVAL_ANIM_IDS(main->key.first, ADT_RECALC_ANIM); - + /* metaballs */ EVAL_ANIM_IDS(main->mball.first, ADT_RECALC_ANIM); - + /* curves */ EVAL_ANIM_IDS(main->curve.first, ADT_RECALC_ANIM); - + /* armatures */ EVAL_ANIM_IDS(main->armature.first, ADT_RECALC_ANIM); - + /* lattices */ EVAL_ANIM_IDS(main->latt.first, ADT_RECALC_ANIM); - + /* meshes */ EVAL_ANIM_IDS(main->mesh.first, ADT_RECALC_ANIM); - + /* particles */ EVAL_ANIM_IDS(main->particle.first, ADT_RECALC_ANIM); - + /* speakers */ EVAL_ANIM_IDS(main->speaker.first, ADT_RECALC_ANIM); @@ -2894,31 +2894,31 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime) /* linestyles */ EVAL_ANIM_IDS(main->linestyle.first, ADT_RECALC_ANIM); - + /* grease pencil */ EVAL_ANIM_IDS(main->gpencil.first, ADT_RECALC_ANIM); /* cache files */ EVAL_ANIM_IDS(main->cachefiles.first, ADT_RECALC_ANIM); - + /* objects */ /* ADT_RECALC_ANIM doesn't need to be supplied here, since object AnimData gets * this tagged by Depsgraph on framechange. This optimization means that objects * linked from other (not-visible) scenes will not need their data calculated. */ - EVAL_ANIM_IDS(main->object.first, 0); + EVAL_ANIM_IDS(main->object.first, 0); /* masks */ EVAL_ANIM_IDS(main->mask.first, ADT_RECALC_ANIM); - + /* worlds */ EVAL_ANIM_NODETREE_IDS(main->world.first, World, ADT_RECALC_ANIM); - + /* scenes */ EVAL_ANIM_NODETREE_IDS(main->scene.first, Scene, ADT_RECALC_ANIM); } -/* ***************************************** */ +/* ***************************************** */ /* ************** */ /* Evaluation API */ diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 01a5cc260add..317994d4ed91 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -83,18 +83,18 @@ const char *BKE_appdir_folder_default(void) if (uput_getenv("HOME", documentfolder, MAXPATHLEN)) { if (BLI_is_dir(documentfolder)) return documentfolder; } - + /* add user profile support for WIN 2K / NT. * This is %APPDATA%, which translates to either * %USERPROFILE%\Application Data or since Vista * to %USERPROFILE%\AppData\Roaming */ hResult = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, documentfolder); - + if (hResult == S_OK) { if (BLI_is_dir(documentfolder)) return documentfolder; } - + return NULL; #endif /* WIN32 */ } @@ -120,7 +120,7 @@ static bool test_path( const char *path_base, const char *path_sep, const char *folder_name) { char tmppath[FILE_MAX]; - + if (path_sep) { BLI_join_dirfile(tmppath, sizeof(tmppath), path_base, path_sep); } @@ -161,7 +161,7 @@ static bool test_env_path(char *path, const char *envvar) { const char *env = envvar ? getenv(envvar) : NULL; if (!env) return false; - + if (BLI_is_dir(env)) { BLI_strncpy(path, env, FILE_MAX); #ifdef PATH_DEBUG @@ -193,7 +193,7 @@ static bool get_path_local( const char *folder_name, const char *subfolder_name, const int ver) { char relfolder[FILE_MAX]; - + #ifdef PATH_DEBUG printf("%s...\n", __func__); #endif @@ -276,11 +276,11 @@ static bool get_path_user( if (!user_path[0]) return false; - + #ifdef PATH_DEBUG printf("%s: %s\n", __func__, user_path); #endif - + if (subfolder_name) { return test_path(targetpath, targetpath_len, user_path, folder_name, subfolder_name); } @@ -334,14 +334,14 @@ static bool get_path_system( system_base_path = (const char *)GHOST_getSystemDir(ver, blender_version_decimal(ver)); if (system_base_path) BLI_strncpy(system_path, system_base_path, FILE_MAX); - + if (!system_path[0]) return false; - + #ifdef PATH_DEBUG printf("%s: %s\n", __func__, system_path); #endif - + if (subfolder_name) { /* try $BLENDERPATH/folder_name/subfolder_name */ return test_path(targetpath, targetpath_len, system_path, folder_name, subfolder_name); @@ -371,16 +371,16 @@ const char *BKE_appdir_folder_id_ex( if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break; if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break; return NULL; - + case BLENDER_USER_DATAFILES: if (get_path_user(path, path_len, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break; return NULL; - + case BLENDER_SYSTEM_DATAFILES: if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break; if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break; return NULL; - + case BLENDER_USER_AUTOSAVE: if (get_path_user(path, path_len, "autosave", subfolder, "BLENDER_USER_DATAFILES", ver)) break; return NULL; @@ -388,16 +388,16 @@ const char *BKE_appdir_folder_id_ex( case BLENDER_USER_CONFIG: if (get_path_user(path, path_len, "config", subfolder, "BLENDER_USER_CONFIG", ver)) break; return NULL; - + case BLENDER_USER_SCRIPTS: if (get_path_user(path, path_len, "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver)) break; return NULL; - + case BLENDER_SYSTEM_SCRIPTS: if (get_path_local(path, path_len, "scripts", subfolder, ver)) break; if (get_path_system(path, path_len, "scripts", subfolder, "BLENDER_SYSTEM_SCRIPTS", ver)) break; return NULL; - + case BLENDER_SYSTEM_PYTHON: if (get_path_local(path, path_len, "python", subfolder, ver)) break; if (get_path_system(path, path_len, "python", subfolder, "BLENDER_SYSTEM_PYTHON", ver)) break; @@ -407,7 +407,7 @@ const char *BKE_appdir_folder_id_ex( BLI_assert(0); break; } - + return path; } @@ -460,14 +460,14 @@ const char *BKE_appdir_folder_id_create(const int folder_id, const char *subfold /* only for user folders */ if (!ELEM(folder_id, BLENDER_USER_DATAFILES, BLENDER_USER_CONFIG, BLENDER_USER_SCRIPTS, BLENDER_USER_AUTOSAVE)) return NULL; - + path = BKE_appdir_folder_id(folder_id, subfolder); - + if (!path) { path = BKE_appdir_folder_id_user_notest(folder_id, subfolder); if (path) BLI_dir_create_recursive(path); } - + return path; } @@ -739,8 +739,8 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c if (userdir && BLI_is_dir(userdir)) { BLI_strncpy(fullname, userdir, maxlen); } - - + + #ifdef WIN32 if (fullname[0] == '\0') { const char *tmp = getenv("TEMP"); /* Windows */ @@ -756,7 +756,7 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c BLI_strncpy(fullname, tmp, maxlen); } } - + if (fullname[0] == '\0') { const char *tmp = getenv("TMPDIR"); if (tmp && BLI_is_dir(tmp)) { @@ -764,7 +764,7 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c } } #endif - + if (fullname[0] == '\0') { BLI_strncpy(fullname, "/tmp/", maxlen); } diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index 70a3772f3889..b7a811b75741 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -641,17 +641,17 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB /* add extra rolls */ roll1 += bone->roll1 + (!rest ? pchan->roll1 : 0.0f); roll2 += bone->roll2 + (!rest ? pchan->roll2 : 0.0f); - + if (bone->flag & BONE_ADD_PARENT_END_ROLL) { if (prev) { if (prev->bone) roll1 += prev->bone->roll2; - + if (!rest) roll1 += prev->roll2; } } - + /* extra curve x / y */ /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results @@ -659,14 +659,14 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB */ const float xscale_correction = (do_scale) ? scale[0] : 1.0f; const float yscale_correction = (do_scale) ? scale[2] : 1.0f; - + h1[0] += (bone->curveInX + (!rest ? pchan->curveInX : 0.0f)) * xscale_correction; h1[2] += (bone->curveInY + (!rest ? pchan->curveInY : 0.0f)) * yscale_correction; - + h2[0] += (bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f)) * xscale_correction; h2[2] += (bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f)) * yscale_correction; } - + /* make curve */ if (bone->segments > MAX_BBONE_SUBDIV) bone->segments = MAX_BBONE_SUBDIV; @@ -682,39 +682,39 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) { sub_v3_v3v3(h1, fp + 4, fp); vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */ - + copy_m4_m3(result_array[a].mat, mat3); copy_v3_v3(result_array[a].mat[3], fp); - + if (do_scale) { /* correct for scaling when this matrix is used in scaled space */ mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat); } - + /* BBone scale... */ { const int num_segments = bone->segments; - + const float scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f); const float scaleFactorIn = 1.0f + (scaleIn - 1.0f) * ((float)(num_segments - a) / (float)num_segments); - + const float scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f); const float scaleFactorOut = 1.0f + (scaleOut - 1.0f) * ((float)(a + 1) / (float)num_segments); - + const float scalefac = scaleFactorIn * scaleFactorOut; float bscalemat[4][4], bscale[3]; - + bscale[0] = scalefac; bscale[1] = 1.0f; bscale[2] = scalefac; - + size_to_mat4(bscalemat, bscale); - + /* Note: don't multiply by inverse scale mat here, as it causes problems with scaling shearing and breaking segment chains */ /*mul_m4_series(result_array[a].mat, ibscalemat, result_array[a].mat, bscalemat);*/ mul_m4_series(result_array[a].mat, result_array[a].mat, bscalemat); } - + } } @@ -773,10 +773,10 @@ static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], D float (*mat)[4] = b_bone[0].mat; float segment, y; int a; - + /* need to transform co back to bonespace, only need y */ y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1]; - + /* now calculate which of the b_bones are deforming this */ segment = bone->length / ((float)bone->segments); a = (int)(y / segment); @@ -1818,7 +1818,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { pchanp = BKE_pose_channel_find_name(frompose, pchan->name); - + if (UNLIKELY(pchanp == NULL)) { /* happens for proxies that become invalid because of a missing link * for regular cases it shouldn't happen at all */ @@ -1826,7 +1826,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected else if (pchan->bone->layer & layer_protected) { ListBase proxylocal_constraints = {NULL, NULL}; bPoseChannel pchanw; - + /* copy posechannel to temp, but restore important pointers */ pchanw = *pchanp; pchanw.bone = pchan->bone; @@ -1842,13 +1842,13 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected /* this is freed so copy a copy, else undo crashes */ if (pchanw.prop) { pchanw.prop = IDP_CopyProperty(pchanw.prop); - + /* use the values from the existing props */ if (pchan->prop) { IDP_SyncGroupValues(pchanw.prop, pchan->prop); } } - + /* constraints - proxy constraints are flushed... local ones are added after * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints * 2. copy proxy-pchan's constraints on-to new @@ -1860,29 +1860,29 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints); BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false); BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints); - + /* constraints - set target ob pointer to own object */ for (con = pchanw.constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar == from) ct->tar = ob; } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 0); } } - + /* free stuff from current channel */ BKE_pose_channel_free(pchan); - + /* copy data in temp back over to the cleaned-out (but still allocated) original channel */ *pchan = pchanw; if (pchan->custom) { diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c index ee63e618b185..cb4237f51b45 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -116,7 +116,7 @@ static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPos /* only happens on reload file, but violates depsgraph still... fix! */ if (ELEM(NULL, ikData->tar->curve_cache, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) { BKE_displist_make_curveTypes(scene, ikData->tar, 0); - + /* path building may fail in EditMode after removing verts [#33268]*/ if (ELEM(NULL, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) { /* BLI_assert(cu->path != NULL); */ @@ -422,21 +422,21 @@ static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *o { /* improved volume preservation based on the Stretch To constraint */ float final_scale; - + /* as the basis for volume preservation, we use the inverse scale factor... */ if (fabsf(scaleFac) != 0.0f) { /* NOTE: The method here is taken wholesale from the Stretch To constraint */ float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge); - + if (bulge > 1.0f) { if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MAX) { float bulge_max = max_ff(ikData->bulge_max, 1.0f); float hard = min_ff(bulge, bulge_max); - + float range = bulge_max - 1.0f; float scale = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (float)M_PI_2; - + bulge = interpf(soft, hard, ikData->bulge_smooth); } } @@ -444,15 +444,15 @@ static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *o if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MIN) { float bulge_min = CLAMPIS(ikData->bulge_min, 0.0f, 1.0f); float hard = max_ff(bulge, bulge_min); - + float range = 1.0f - bulge_min; float scale = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (float)M_PI_2; - + bulge = interpf(soft, hard, ikData->bulge_smooth); } } - + /* compute scale factor for xz axes from this value */ final_scale = sqrtf(bulge); } @@ -460,7 +460,7 @@ static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *o /* no scaling, so scale factor is simple */ final_scale = 1.0f; } - + /* apply the scaling (assuming normalised scale) */ mul_v3_fl(poseMat[0], final_scale); mul_v3_fl(poseMat[2], final_scale); diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index 58638ca060a5..2f5cb9e9deb9 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -89,20 +89,20 @@ void BKE_blender_free(void) } BKE_spacetypes_free(); /* after free main, it uses space callbacks */ - + IMB_exit(); BKE_cachefiles_exit(); BKE_images_exit(); DAG_exit(); BKE_brush_system_exit(); - RE_texture_rng_exit(); + RE_texture_rng_exit(); BLI_callback_global_finalize(); BKE_sequencer_cache_destruct(); IMB_moviecache_destruct(); - + free_nodesystem(); } @@ -133,7 +133,7 @@ void BKE_upbge_version_string(char *version_str, size_t maxncpy, short version, void BKE_blender_globals_init(void) { memset(&G, 0, sizeof(Global)); - + U.savetime = 1; G_MAIN = BKE_main_new(); @@ -335,7 +335,7 @@ int BKE_blender_test_break(void) if (blender_test_break_cb) blender_test_break_cb(); } - + return (G.is_break == true); } diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c index 8018629ef2a3..c99894bfbafd 100644 --- a/source/blender/blenkernel/intern/bmfont.c +++ b/source/blender/blenkernel/intern/bmfont.c @@ -71,7 +71,7 @@ void calcAlpha(ImBuf *ibuf) { int i; char *rect; - + if (ibuf) { rect = (char *) ibuf->rect; for (i = ibuf->x * ibuf->y; i > 0; i--) { @@ -86,21 +86,21 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) int glyphcount, bytes, i, index, linelength, ysize; unsigned char *buffer; bmFont * bmfont; - + linelength = ibuf->x * step; - + glyphcount = (rect[6 * step] << 8) | rect[7 * step]; bytes = ((glyphcount - 1) * sizeof(bmGlyph)) + sizeof(bmFont); - + ysize = (bytes + (ibuf->x - 1)) / ibuf->x; - + if (ysize < ibuf->y) { /* we're first going to copy all data into a linear buffer. * step can be 4 or 1 bytes, and the data is not sequential because * the bitmap was flipped vertically. */ - + buffer = MEM_mallocN(bytes, "readBitmapFontVersion0:buffer"); - + index = 0; for (i = 0; i < bytes; i++) { buffer[i] = rect[index]; @@ -111,12 +111,12 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) index -= linelength; } } - + /* we're now going to endian convert the data */ - + bmfont = MEM_mallocN(bytes, "readBitmapFontVersion0:bmfont"); index = 0; - + /* first read the header */ bmfont->magic[0] = buffer[index++]; bmfont->magic[1] = buffer[index++]; @@ -126,7 +126,7 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) bmfont->glyphcount = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->xsize = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->ysize = (buffer[index] << 8) | buffer[index + 1]; index += 2; - + for (i = 0; i < bmfont->glyphcount; i++) { bmfont->glyphs[i].unicode = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->glyphs[i].locx = (buffer[index] << 8) | buffer[index + 1]; index += 2; @@ -141,9 +141,9 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) printfGlyph(&bmfont->glyphs[i]); } } - + MEM_freeN(buffer); - + if (G.debug & G_DEBUG) { printf("Oldy = %d Newy = %d\n", ibuf->y, ibuf->y - ysize); printf("glyphcount = %d\n", glyphcount); @@ -173,7 +173,7 @@ void detectBitmapFont(ImBuf *ibuf) unsigned char *rect; unsigned short version; int i; - + if (ibuf != NULL && ibuf->rect != NULL) { /* bitmap must have an x size that is a power of two */ if (is_power_of_two(ibuf->x)) { @@ -215,7 +215,7 @@ void detectBitmapFont(ImBuf *ibuf) int locateGlyph(bmFont *bmfont, unsigned short unicode) { int min, max, current = 0; - + if (bmfont) { min = 0; max = bmfont->glyphcount; @@ -242,7 +242,7 @@ int locateGlyph(bmFont *bmfont, unsigned short unicode) } } } - + return(current); } @@ -256,19 +256,19 @@ void matrixGlyph( { int index; bmFont *bmfont; - + *centerx = *centery = 0.0; *sizex = *sizey = 1.0; *transx = *transy = 0.0; *movex = *movey = 0.0; *advance = 1.0; - + if (ibuf) { bmfont = ibuf->userdata; if (bmfont && (ibuf->userflags & IB_BITMAPFONT)) { index = locateGlyph(bmfont, unicode); if (index) { - + *sizex = (bmfont->glyphs[index].sizex) / (float) (bmfont->glyphs[0].sizex); *sizey = (bmfont->glyphs[index].sizey) / (float) (bmfont->glyphs[0].sizey); @@ -279,10 +279,10 @@ void matrixGlyph( *centery = (ibuf->y - bmfont->glyphs[0].locy) / (float) ibuf->y; /* 2.0 units is the default size of an object */ - + *movey = 1.0f - *sizey + 2.0f * (bmfont->glyphs[index].ofsy - bmfont->glyphs[0].ofsy) / (float) bmfont->glyphs[0].sizey; *movex = *sizex - 1.0f + 2.0f * (bmfont->glyphs[index].ofsx - bmfont->glyphs[0].ofsx) / (float) bmfont->glyphs[0].sizex; - + *advance = 2.0f * bmfont->glyphs[index].advance / (float) bmfont->glyphs[0].advance; // printfGlyph(&bmfont->glyphs[index]); diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c index 024c0aeb23fb..18b2a5b2fccc 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -276,7 +276,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * sub_v3_v3v3(loc, co1, co2); sub_v3_v3v3(vec, vel1, vel2); - + inp = dot_v3v3(vec, vec); /* velocities not parallel */ @@ -286,7 +286,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * if (t > 0.0f && t < t_min) { madd_v3_v3fl(co1, vel1, t); madd_v3_v3fl(co2, vel2, t); - + sub_v3_v3v3(vec, co2, co1); len = normalize_v3(vec); @@ -326,7 +326,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * sub_v3_v3v3(loc, co1, co2); sub_v3_v3v3(vec, vel1, vel2); - + inp = dot_v3v3(vec, vec); /* velocities not parallel */ @@ -336,7 +336,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * if (t > 0.0f && t < t_min) { madd_v3_v3fl(co1, vel1, t); madd_v3_v3fl(co2, vel2, t); - + sub_v3_v3v3(vec, co2, co1); len = normalize_v3(vec); @@ -394,7 +394,7 @@ static int rule_separate(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues neighbors = BLI_kdtree_range_search( epsys->tree, pa->prev_state.co, &ptn, 2.0f * val->personal_space * pa->size); - + if (neighbors > 0 && ptn[0].dist < len) { sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co); mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist); @@ -496,13 +496,13 @@ static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *va sub_v3_v3v3(vec, flbr->loc, flbr->oloc); mul_v3_fl(vec, 1.0f/bbd->timestep); } - + /* fac is seconds behind leader */ madd_v3_v3fl(loc, vec, -flbr->distance); sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co); bbd->wanted_speed = len_v3(bbd->wanted_co); - + ret = 1; } else if (p % n) { @@ -559,13 +559,13 @@ static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *va copy_v3_v3(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel); copy_v3_v3(loc, bbd->sim->psys->particles[p - p%n].prev_state.co); } - + /* fac is seconds behind leader */ madd_v3_v3fl(loc, vec, -flbr->distance); sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co); bbd->wanted_speed = len_v3(bbd->wanted_co); - + ret = 1; } @@ -611,7 +611,7 @@ static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *va bbd->wanted_co[1] = 2.0f*(0.5f - BLI_rng_get_float(bbd->rng)); bbd->wanted_co[2] = 2.0f*(0.5f - BLI_rng_get_float(bbd->rng)); } - + /* leveling */ if (asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) { project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity); @@ -621,7 +621,7 @@ static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *va } bbd->wanted_speed = asbr->speed * val->max_speed; - + return 1; } static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa) @@ -661,7 +661,7 @@ static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, Parti neighbors = BLI_kdtree_range_search( epsys->tree, pa->prev_state.co, &ptn, fbr->distance); - + health = 0.0f; for (n=0; ndata.mode == eBoidMode_Climbing) { SurfaceModifierData *surmd = NULL; float x[3], v[3]; - + surmd = (SurfaceModifierData *)modifiers_findByType(bpa->ground, eModifierType_Surface ); /* take surface velocity into account */ @@ -868,10 +868,10 @@ static int boid_rule_applies(ParticleData *pa, BoidSettings *UNUSED(boids), Boid if (rule==NULL) return 0; - + if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND) return 1; - + if (bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR) return 1; @@ -1049,7 +1049,7 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) if (bpa->data.mode == eBoidMode_OnLand) { /* fuzziness makes boids capable of misjudgement */ float mul = 1.0f + state->rule_fuzziness; - + if (boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) { float cvel[3], dir[3]; @@ -1165,7 +1165,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* auto-leveling & landing if close to ground */ bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor); - + /* level = how many particle sizes above ground */ level = (pa->prev_state.co[2] - ground_co[2])/(2.0f * pa->size) - 0.5f; @@ -1226,7 +1226,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* constrain speed with maximum acceleration */ old_speed = len_v3(pa->prev_state.vel); - + if (bbd->wanted_speed < old_speed) new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc); else @@ -1273,7 +1273,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) mul_v3_fl(force, length); } - + add_v3_v3(acc, force); /* store smoothed acceleration for nice banking etc. */ @@ -1288,7 +1288,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) copy_v3_v3(dvec, acc); mul_v3_fl(dvec, dtime*dtime*0.5f); - + copy_v3_v3(bvec, pa->prev_state.vel); mul_v3_fl(bvec, dtime); add_v3_v3(dvec, bvec); @@ -1467,7 +1467,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) } negate_v3(mat[2]); cross_v3_v3v3(mat[1], mat[2], mat[0]); - + /* apply rotation */ mat3_to_quat_is_ok(q, mat); copy_qt_qt(pa->state.rot, q); @@ -1617,4 +1617,3 @@ BoidState *boid_get_current_state(BoidSettings *boids) return state; } - diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 7f50e521e638..42cd79683212 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -271,7 +271,7 @@ void BKE_brush_debug_print_state(Brush *br) /* create a fake brush and set it to the defaults */ Brush def = {{NULL}}; brush_defaults(&def); - + #define BR_TEST(field, t) \ if (br->field != def.field) \ printf("br->" #field " = %" #t ";\n", br->field) @@ -281,7 +281,7 @@ void BKE_brush_debug_print_state(Brush *br) printf("br->flag |= " #_f ";\n"); \ else if (!(br->flag & _f) && (def.flag & _f)) \ printf("br->flag &= ~" #_f ";\n") - + #define BR_TEST_FLAG_OVERLAY(_f) \ if ((br->overlay_flags & _f) && !(def.overlay_flags & _f)) \ printf("br->overlay_flags |= " #_f ";\n"); \ @@ -355,7 +355,7 @@ void BKE_brush_debug_print_state(Brush *br) BR_TEST(sub_col[2], f); printf("\n"); - + #undef BR_TEST #undef BR_TEST_FLAG } @@ -757,7 +757,7 @@ int BKE_brush_size_get(const Scene *scene, const Brush *brush) { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size; - + return size; } diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c index 339421683de5..b495585a3f4e 100644 --- a/source/blender/blenkernel/intern/bullet.c +++ b/source/blender/blenkernel/intern/bullet.c @@ -44,25 +44,25 @@ BulletSoftBody *bsbNew(void) { BulletSoftBody *bsb; - + bsb = MEM_callocN(sizeof(BulletSoftBody), "bulletsoftbody"); - + bsb->flag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT; bsb->linStiff = 0.5f; bsb->angStiff = 1.0f; bsb->volume = 1.0f; - + bsb->viterations = 0; bsb->piterations = 2; bsb->diterations = 0; bsb->citerations = 4; - + bsb->kSRHR_CL = 0.1f; bsb->kSKHR_CL = 1.f; bsb->kSSHR_CL = 0.5f; bsb->kSR_SPLT_CL = 0.5f; - + bsb->kSK_SPLT_CL = 0.5f; bsb->kSS_SPLT_CL = 0.5f; bsb->kVCF = 1; @@ -80,7 +80,7 @@ BulletSoftBody *bsbNew(void) bsb->kSHR = 1.0f; bsb->kAHR = 0.7f; - + bsb->collisionflags = 0; //bsb->collisionflags = OB_BSB_COL_CL_RS + OB_BSB_COL_CL_SS; bsb->numclusteriterations = 64; @@ -96,5 +96,3 @@ void bsbFree(BulletSoftBody *bsb) /* no internal data yet */ MEM_freeN(bsb); } - - diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index 3c0f38939fea..e48c6ff38d23 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -76,7 +76,7 @@ float bvhtree_sphereray_tri_intersection( const BVHTreeRay *ray, float radius, const float m_dist, const float v0[3], const float v1[3], const float v2[3]) { - + float idist; float p1[3]; float hit_point[3]; @@ -107,7 +107,7 @@ static void mesh_faces_nearest_point(void *userdata, int index, const float co[3 t2 = vert[face->v3].co; t3 = face->v4 ? vert[face->v4].co : NULL; - + do { float nearest_tmp[3], dist_sq; @@ -191,7 +191,7 @@ static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *r t2 = vert[face->v3].co; t3 = face->v4 ? vert[face->v4].co : NULL; - + do { float dist; if (ray->radius == 0.0f) @@ -284,7 +284,7 @@ static void mesh_edges_nearest_point(void *userdata, int index, const float co[3 closest_to_line_segment_v3(nearest_tmp, co, t0, t1); dist_sq = len_squared_v3v3(nearest_tmp, co); - + if (dist_sq < nearest->dist_sq) { nearest->index = index; nearest->dist_sq = dist_sq; @@ -1152,7 +1152,7 @@ BVHTree *bvhtree_from_mesh_get( MEM_freeN(mloop); } if (looptri_allocated) { - MEM_freeN((void*)looptri); + MEM_freeN((void *)looptri); } memset(data, 0, sizeof(*data)); diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 058394fc1b1f..5f7759c7b55e 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -198,7 +198,7 @@ bool BKE_cachefile_filepath_get( char ext[32]; BLI_path_frame_strip(r_filepath, true, ext); BLI_path_frame(r_filepath, frame, frame_len); - BLI_ensure_extension(r_filepath, FILE_MAX, ext); + BLI_path_extension_ensure(r_filepath, FILE_MAX, ext); /* TODO(kevin): store sequence range? */ return BLI_exists(r_filepath); diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index b81880a57419..22be41dfb2ae 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -145,7 +145,7 @@ void BKE_camera_object_mode(RenderData *rd, Object *cam_ob) /* get the camera's dof value, takes the dof object into account */ float BKE_camera_object_dof_distance(Object *ob) { - Camera *cam = (Camera *)ob->data; + Camera *cam = (Camera *)ob->data; if (ob->type != OB_CAMERA) return 0.0f; if (cam->dof_ob) { diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 1a34b71643fe..1c5b1ca242cf 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -289,7 +289,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color); pbvh_show_mask_set(cddm->pbvh, ob->sculpt->show_mask); } - + /* always build pbvh from original mesh, and only use it for drawing if * this derivedmesh is just original mesh. it's the multires subsurf dm @@ -310,7 +310,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) me->mvert, me->totloop, me->totpoly, looptri); - + BKE_pbvh_build_mesh( cddm->pbvh, me->mpoly, me->mloop, @@ -417,7 +417,7 @@ static void cdDM_drawEdges(DerivedMesh *dm, bool drawLooseEdges, bool drawAllEdg return; } - + GPU_edge_setup(dm); gdo = dm->drawObject; if (gdo->edges && gdo->points) { @@ -469,7 +469,7 @@ static void cdDM_drawFacesSolid( return; } } - + GPU_vertex_setup(dm); GPU_normal_setup(dm); GPU_triangle_setup(dm); @@ -630,7 +630,7 @@ static void cdDM_drawFacesTex_common( } GPU_buffers_unbind(); - + } static void cdDM_drawFacesTex( @@ -966,8 +966,8 @@ static void cdDM_drawMappedFacesGLSL( if (orig == ORIGINDEX_NONE) { /* since the material is set by setMaterial(), faces with no - * origin can be assumed to be generated by a modifier */ - + * origin can be assumed to be generated by a modifier */ + /* continue */ } else if (setDrawOptions(userData, orig) == DM_DRAW_OPTION_SKIP) @@ -990,7 +990,7 @@ static void cdDM_drawMappedFacesGLSL( ln2 = lnors[ltri[1]]; ln3 = lnors[ltri[2]]; } - + cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[0], ltri[0], 0, ln1, smoothnormal); cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[1], ltri[1], 1, ln2, smoothnormal); cddm_draw_attrib_vertex(&attribs, mvert, a, vtri[2], ltri[2], 2, ln3, smoothnormal); @@ -1883,7 +1883,7 @@ static void cdDM_foreachMappedFaceCenter( else { orig = i; } - + ml = &cddm->mloop[mp->loopstart]; BKE_mesh_calc_poly_center(mp, ml, mvert, cent); @@ -2182,9 +2182,9 @@ static void loops_to_customdata_corners( for (i = 0; i < numTex; i++) { texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i); texpoly = CustomData_bmesh_get_n(&bm->pdata, f->head.data, CD_MTEXPOLY, i); - + ME_MTEXFACE_CPY(texface, texpoly); - + for (j = 0; j < 3; j++) { l = l3[j]; mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i); @@ -2194,7 +2194,7 @@ static void loops_to_customdata_corners( for (i = 0; i < numCol; i++) { mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i); - + for (j = 0; j < 3; j++) { l = l3[j]; mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i); @@ -2241,18 +2241,18 @@ static DerivedMesh *cddm_from_bmesh_ex( int *index, add_orig; CustomDataMask mask; unsigned int i, j; - + const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT); const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT); const int cd_edge_crease_offset = CustomData_get_offset(&bm->edata, CD_CREASE); - + dm->deformedOnly = 1; - + /* don't add origindex layer if one already exists */ add_orig = !CustomData_has_layer(&bm->pdata, CD_ORIGINDEX); mask = use_mdisps ? CD_MASK_DERIVEDMESH | CD_MASK_MDISPS : CD_MASK_DERIVEDMESH; - + /* don't process shapekeys, we only feed them through the modifier stack as needed, * e.g. for applying modifiers or the like*/ mask &= ~CD_MASK_SHAPEKEY; @@ -2343,7 +2343,7 @@ static DerivedMesh *cddm_from_bmesh_ex( test_index_face(mf, &dm->faceData, i, 3); } } - + index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX); j = 0; BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, i) { @@ -3044,7 +3044,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int newv[i] = 0; } } - + /* now link target vertices to destination indices */ for (i = 0; i < totvert; i++) { if (vtargetmap[i] != -1) { @@ -3081,7 +3081,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int newe[i] = -1; } } - + if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_EQUAL) { /* In this mode, we need to determine, whenever a poly' vertices are all mapped */ /* if the targets already make up a poly, in which case the new poly is dropped */ @@ -3122,7 +3122,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int mv = cddm->mvert; for (i = 0; i < totpoly; i++, mp++) { MPoly *mp_new; - + ml = cddm->mloop + mp->loopstart; /* check faces with all vertices merged */ @@ -3326,7 +3326,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int mp_new->totloop = c; BLI_assert(mp_new->totloop >= 3); mp_new->loopstart = STACK_SIZE(mloop) - c; - + STACK_PUSH(oldp, i); } /* end of the loop that tests polys */ @@ -3337,11 +3337,11 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int BLI_gset_free(poly_gset, NULL); MEM_freeN(poly_keys); } - + /*create new cddm*/ cddm2 = (CDDerivedMesh *)CDDM_from_template( (DerivedMesh *)cddm, STACK_SIZE(mvert), STACK_SIZE(medge), 0, STACK_SIZE(mloop), STACK_SIZE(mpoly)); - + /*update edge indices and copy customdata*/ med = medge; for (i = 0; i < cddm2->dm.numEdgeData; i++, med++) { @@ -3355,7 +3355,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int CustomData_copy_data(&dm->edgeData, &cddm2->dm.edgeData, olde[i], i, 1); } - + /*update loop indices and copy customdata*/ ml = mloop; for (i = 0; i < cddm2->dm.numLoopData; i++, ml++) { @@ -3365,19 +3365,19 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1); } - + /*copy vertex customdata*/ mv = mvert; for (i = 0; i < cddm2->dm.numVertData; i++, mv++) { CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1); } - + /*copy poly customdata*/ mp = mpoly; for (i = 0; i < cddm2->dm.numPolyData; i++, mp++) { CustomData_copy_data(&dm->polyData, &cddm2->dm.polyData, oldp[i], i, 1); } - + /*copy over data. CustomData_add_layer can do this, need to look it up.*/ memcpy(cddm2->mvert, mvert, sizeof(MVert) * STACK_SIZE(mvert)); memcpy(cddm2->medge, medge, sizeof(MEdge) * STACK_SIZE(medge)); @@ -3405,7 +3405,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int /*free old derivedmesh*/ dm->needsFree = 1; dm->release(dm); - + return (DerivedMesh *)cddm2; } #endif @@ -3425,7 +3425,7 @@ void CDDM_calc_edges_tessface(DerivedMesh *dm) for (i = 0; i < numFaces; i++, mf++) { BLI_edgeset_add(eh, mf->v1, mf->v2); BLI_edgeset_add(eh, mf->v2, mf->v3); - + if (mf->v4) { BLI_edgeset_add(eh, mf->v3, mf->v4); BLI_edgeset_add(eh, mf->v4, mf->v1); @@ -3671,7 +3671,7 @@ void CDDM_tessfaces_to_faces(DerivedMesh *dm) void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - + if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, mvert, dm->numVertData); diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index 9ae295e2e3ba..26f998b3cb46 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -75,7 +75,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ); * 2. fill object with standard values or with the GUI settings if given */ void cloth_init(ClothModifierData *clmd ) -{ +{ /* Initialize our new data structure to reasonable values. */ clmd->sim_parms->gravity[0] = 0.0; clmd->sim_parms->gravity[1] = 0.0; @@ -86,7 +86,7 @@ void cloth_init(ClothModifierData *clmd ) clmd->sim_parms->bending = 0.5; clmd->sim_parms->max_bend = 0.5; clmd->sim_parms->bending_damping = 0.5; - clmd->sim_parms->Cdis = 5.0; + clmd->sim_parms->Cdis = 5.0; clmd->sim_parms->Cvi = 1.0; clmd->sim_parms->mass = 0.3f; clmd->sim_parms->stepsPerFrame = 5; @@ -102,7 +102,7 @@ void cloth_init(ClothModifierData *clmd ) clmd->sim_parms->time_scale = 1.0f; /* multiplies cloth speed */ clmd->sim_parms->reset = 0; clmd->sim_parms->vel_damping = 1.0f; /* 1.0 = no damping, 0.0 = fully dampened */ - + clmd->coll_parms->self_friction = 5.0; clmd->coll_parms->friction = 5.0; clmd->coll_parms->loop_count = 2; @@ -150,27 +150,27 @@ static BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float eps if (!cloth) return NULL; - + verts = cloth->verts; - + /* in the moment, return zero if no faces there */ if (!cloth->mvert_num) return NULL; - + /* create quadtree with k=26 */ bvhtree = BLI_bvhtree_new(cloth->mvert_num, epsilon, 4, 6); - + /* fill tree */ for (i = 0; i < cloth->mvert_num; i++, verts++) { const float *co; co = verts->xold; - + BLI_bvhtree_insert(bvhtree, i, co, 1); } - + /* balance tree */ BLI_bvhtree_balance(bvhtree); - + return bvhtree; } @@ -189,10 +189,10 @@ static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon if (!cloth) return NULL; - + verts = cloth->verts; vt = cloth->tri; - + /* in the moment, return zero if no faces there */ if (!cloth->tri_num) return NULL; @@ -213,23 +213,23 @@ static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon /* balance tree */ BLI_bvhtree_balance(bvhtree); - + return bvhtree; } void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving) -{ +{ unsigned int i = 0; Cloth *cloth = clmd->clothObject; BVHTree *bvhtree = cloth->bvhtree; ClothVertex *verts = cloth->verts; const MVertTri *vt; - + if (!bvhtree) return; - + vt = cloth->tri; - + /* update vertex position in bvh tree */ if (verts && vt) { for (i = 0; i < cloth->tri_num; i++, vt++) { @@ -252,25 +252,25 @@ void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving) else { ret = BLI_bvhtree_update_node(bvhtree, i, co[0], NULL, 3); } - + /* check if tree is already full */ if (ret == false) { break; } } - + BLI_bvhtree_update_tree(bvhtree); } } void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) -{ +{ unsigned int i = 0; Cloth *cloth = clmd->clothObject; BVHTree *bvhtree = cloth->bvhselftree; ClothVertex *verts = cloth->verts; const MVertTri *vt; - + if (!bvhtree) return; @@ -299,7 +299,7 @@ void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) break; } } - + BLI_bvhtree_update_tree(bvhtree); } } @@ -307,13 +307,13 @@ void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr) { PTCacheID pid; - + BKE_ptcache_id_from_cloth(&pid, ob, clmd); // don't do anything as long as we're in editmode! if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT) return; - + BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr); } @@ -330,13 +330,13 @@ static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *resul modifier_setError(&(clmd->modifier), "Can't initialize cloth"); return 0; } - + if (clmd->clothObject == NULL) { BKE_ptcache_invalidate(cache); modifier_setError(&(clmd->modifier), "Null cloth object"); return 0; } - + BKE_cloth_solver_set_positions(clmd); clmd->clothObject->last_frame= MINFRAME-1; @@ -382,7 +382,7 @@ static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *resul cloth_update_spring_lengths ( clmd, result ); cloth_update_springs( clmd ); - + // TIMEIT_START(cloth_step) /* call the solver. */ @@ -393,7 +393,7 @@ static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *resul pdEndEffectors(&effectors); // printf ( "%f\n", ( float ) tval() ); - + return ret; } @@ -424,7 +424,7 @@ void clothModifier_do(ClothModifierData *clmd, Scene *scene, Object *ob, Derived cache->last_exact= 0; cache->flag &= ~PTCACHE_REDO_NEEDED; } - + // unused in the moment, calculated separately in implicit.c clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame; @@ -505,13 +505,13 @@ void clothModifier_do(ClothModifierData *clmd, Scene *scene, Object *ob, Derived void cloth_free_modifier(ClothModifierData *clmd ) { Cloth *cloth = NULL; - + if ( !clmd ) return; cloth = clmd->clothObject; - + if ( cloth ) { BPH_cloth_solver_free(clmd); @@ -527,12 +527,12 @@ void cloth_free_modifier(ClothModifierData *clmd ) LinkNode *search = cloth->springs; while (search) { ClothSpring *spring = search->link; - + MEM_freeN ( spring ); search = search->next; } BLI_linklist_free(cloth->springs, NULL); - + cloth->springs = NULL; } @@ -542,7 +542,7 @@ void cloth_free_modifier(ClothModifierData *clmd ) // free BVH collision tree if ( cloth->bvhtree ) BLI_bvhtree_free ( cloth->bvhtree ); - + if ( cloth->bvhselftree ) BLI_bvhtree_free ( cloth->bvhselftree ); @@ -552,8 +552,8 @@ void cloth_free_modifier(ClothModifierData *clmd ) if (cloth->edgeset) BLI_edgeset_free(cloth->edgeset); - - + + /* if (clmd->clothObject->facemarks) MEM_freeN(clmd->clothObject->facemarks); @@ -569,12 +569,12 @@ void cloth_free_modifier_extern(ClothModifierData *clmd ) Cloth *cloth = NULL; if (G.debug_value > 0) printf("cloth_free_modifier_extern\n"); - + if ( !clmd ) return; cloth = clmd->clothObject; - + if ( cloth ) { if (G.debug_value > 0) printf("cloth_free_modifier_extern in\n"); @@ -608,7 +608,7 @@ void cloth_free_modifier_extern(ClothModifierData *clmd ) // free BVH collision tree if ( cloth->bvhtree ) BLI_bvhtree_free ( cloth->bvhtree ); - + if ( cloth->bvhselftree ) BLI_bvhtree_free ( cloth->bvhselftree ); @@ -658,11 +658,11 @@ static void cloth_to_object (Object *ob, ClothModifierData *clmd, float (*verte int cloth_uses_vgroup(ClothModifierData *clmd) { - return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || + return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SEW) || - (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && - ((clmd->sim_parms->vgroup_mass>0) || + (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && + ((clmd->sim_parms->vgroup_mass>0) || (clmd->sim_parms->vgroup_struct>0)|| (clmd->sim_parms->vgroup_bend>0) || (clmd->sim_parms->vgroup_shrink>0) || @@ -691,7 +691,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ) mvert_num = dm->getNumVerts(dm); verts = clothObj->verts; - + if (cloth_uses_vgroup(clmd)) { for (i = 0; i < mvert_num; i++, verts++) { @@ -715,21 +715,21 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ) verts->goal = dvert->dw [j].weight; /* goalfac= 1.0f; */ /* UNUSED */ - + // Kicking goal factor to simplify things...who uses that anyway? // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal ); - + verts->goal = pow4f(verts->goal); if ( verts->goal >= SOFTGOALSNAP ) verts->flags |= CLOTH_VERT_FLAG_PINNED; } - + if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) { if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1)) { verts->struct_stiff = dvert->dw [j].weight; verts->shear_stiff = dvert->dw [j].weight; } - + if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1)) { verts->bend_stiff = dvert->dw [j].weight; } @@ -784,7 +784,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d Cloth *cloth = NULL; float maxdist = 0; - // If we have a clothObject, free it. + // If we have a clothObject, free it. if ( clmd->clothObject != NULL ) { cloth_free_modifier ( clmd ); if (G.debug_value > 0) @@ -835,9 +835,9 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d else copy_v3_v3(verts->xrest, verts->x); } - + /* no GUI interface yet */ - verts->mass = clmd->sim_parms->mass; + verts->mass = clmd->sim_parms->mass; verts->impulse_count = 0; if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) @@ -857,7 +857,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d verts->impulse_count = 0; copy_v3_v3 ( verts->impulse, tnull ); } - + // apply / set vertex groups // has to be happen before springs are build! cloth_apply_vgroup (clmd, dm); @@ -868,19 +868,19 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d printf("cloth_free_modifier cloth_build_springs\n"); return 0; } - + // init our solver BPH_cloth_solver_init(ob, clmd); - + if (!first) BKE_cloth_solver_set_positions(clmd); clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, MAX2(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel) ); - + for (i = 0; i < dm->getNumVerts(dm); i++) { maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0f)); } - + clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist ); return 1; @@ -956,17 +956,17 @@ static void cloth_free_errorsprings(Cloth *cloth, LinkNodePair *edgelist) LinkNode *search = cloth->springs; while (search) { ClothSpring *spring = search->link; - + MEM_freeN ( spring ); search = search->next; } BLI_linklist_free(cloth->springs, NULL); - + cloth->springs = NULL; } cloth_free_edgelist(edgelist, cloth->mvert_num); - + if (cloth->edgeset) { BLI_edgeset_free(cloth->edgeset); cloth->edgeset = NULL; @@ -979,10 +979,10 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) LinkNode *search = NULL; float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair chains */ - + if (!clmd->hairdata) return; - + /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same @@ -990,17 +990,17 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) * This messy situation can be resolved when solver data is * generated directly from a dedicated hair system. */ - + prev_mn = -1; for (search = cloth->springs; search; search = search->next) { ClothSpring *spring = search->link; ClothHairData *hair_ij, *hair_kl; bool is_root = spring->kl != prev_mn; - + if (spring->type != CLOTH_SPRING_TYPE_BENDING_ANG) { continue; } - + hair_ij = &clmd->hairdata[spring->ij]; hair_kl = &clmd->hairdata[spring->kl]; if (is_root) { @@ -1011,39 +1011,39 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) */ copy_v3_v3(dir_new, hair_frame[2]); } - + copy_v3_v3(dir_old, dir_new); sub_v3_v3v3(dir_new, cloth->verts[spring->mn].x, cloth->verts[spring->kl].x); normalize_v3(dir_new); - + #if 0 if (clmd->debug_data && (spring->ij == 0 || spring->ij == 1)) { float a[3], b[3]; - + copy_v3_v3(a, cloth->verts[spring->kl].x); // BKE_sim_debug_data_add_dot(clmd->debug_data, cloth_vert ? cloth_vert->x : key->co, 1, 1, 0, "frames", 8246, p, k); - + mul_v3_v3fl(b, hair_frame[0], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 1, 0, 0, "frames", 8247, spring->kl, spring->mn); - + mul_v3_v3fl(b, hair_frame[1], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 0, 1, 0, "frames", 8248, spring->kl, spring->mn); - + mul_v3_v3fl(b, hair_frame[2], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 0, 0, 1, "frames", 8249, spring->kl, spring->mn); } #endif - + /* get local targets for kl/mn vertices by putting rest targets into the current frame, * then multiply with the rest length to get the actual goals */ - + mul_v3_m3v3(spring->target, hair_frame, hair_kl->rest_target); mul_v3_fl(spring->target, spring->restlen); - + /* move frame to next hair segment */ cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new); - + prev_mn = spring->mn; } } @@ -1054,10 +1054,10 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) LinkNode *search = NULL; float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair roots */ - + if (!clmd->hairdata) return; - + /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same @@ -1065,17 +1065,17 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) * This messy situation can be resolved when solver data is * generated directly from a dedicated hair system. */ - + prev_mn = -1; for (search = cloth->springs; search; search = search->next) { ClothSpring *spring = search->link; ClothHairData *hair_ij, *hair_kl; bool is_root = spring->kl != prev_mn; - + if (spring->type != CLOTH_SPRING_TYPE_BENDING_ANG) { continue; } - + hair_ij = &clmd->hairdata[spring->ij]; hair_kl = &clmd->hairdata[spring->kl]; if (is_root) { @@ -1086,18 +1086,18 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) */ copy_v3_v3(dir_new, hair_frame[2]); } - + copy_v3_v3(dir_old, dir_new); sub_v3_v3v3(dir_new, cloth->verts[spring->mn].xrest, cloth->verts[spring->kl].xrest); normalize_v3(dir_new); - + /* dir expressed in the hair frame defines the rest target direction */ copy_v3_v3(hair_kl->rest_target, dir_new); mul_transposed_m3_v3(hair_frame, hair_kl->rest_target); - + /* move frame to next hair segment */ cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new); - + prev_mn = spring->mn; } } @@ -1146,10 +1146,10 @@ static void cloth_update_springs( ClothModifierData *clmd ) spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE; } } - + search = search->next; } - + cloth_hair_update_bending_targets(clmd); } @@ -1241,10 +1241,10 @@ BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f) void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3]) { float rot[3][3]; - + /* rotation between segments */ rotation_between_vecs_to_mat3(rot, dir_old, dir_new); - + /* rotate the frame */ mul_m3_m3m3(mat, rot, mat); } @@ -1266,7 +1266,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) LinkNodePair *edgelist; EdgeSet *edgeset = NULL; LinkNode *search = NULL, *search2 = NULL; - + // error handling if ( numedges==0 ) return 0; @@ -1280,7 +1280,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) cloth->edgeset = NULL; edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" ); - + if (!edgelist) return 0; @@ -1312,7 +1312,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) spring->flags = 0; struct_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } else { @@ -1323,7 +1323,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) if (struct_springs_real > 0) clmd->sim_parms->avg_spring_len /= struct_springs_real; - + for (i = 0; i < mvert_num; i++) { if (cloth->verts[i].spring_count > 0) cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count); @@ -1413,15 +1413,15 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) while (search && search2) { tspring = search->link; tspring2 = search2->link; - + if (tspring->ij == tspring2->kl) { spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" ); - + if (!spring) { cloth_free_errorsprings(cloth, edgelist); return 0; } - + spring->ij = tspring2->ij; spring->kl = tspring->ij; spring->mn = tspring->kl; @@ -1429,10 +1429,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) spring->type = CLOTH_SPRING_TYPE_BENDING_ANG; spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f; bend_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } - + search = search->next; search2 = search2->next; } @@ -1450,33 +1450,33 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) while (search && search2) { tspring = search->link; tspring2 = search2->link; - + if (tspring->ij == tspring2->kl) { spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" ); - + if (!spring) { cloth_free_errorsprings(cloth, edgelist); return 0; } - + spring->ij = tspring2->ij; spring->kl = tspring->kl; spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest); spring->type = CLOTH_SPRING_TYPE_BENDING; spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f; bend_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } - + search = search->next; search2 = search2->next; } } - + cloth_hair_update_bending_rest_targets(clmd); } - + /* note: the edges may already exist so run reinsert */ /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */ @@ -1490,10 +1490,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 1].v, mloop[mpoly[i].loopstart + 3].v); } } - - + + cloth->numsprings = struct_springs + shear_springs + bend_springs; - + cloth_free_edgelist(edgelist, mvert_num); #if 0 @@ -1507,4 +1507,3 @@ static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm ) /*************************************************************************************** * SPRING NETWORK BUILDING IMPLEMENTATION END ***************************************************************************************/ - diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c index 65742df754ef..b38d6b8bcebe 100644 --- a/source/blender/blenkernel/intern/collision.c +++ b/source/blender/blenkernel/intern/collision.c @@ -444,7 +444,7 @@ static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2, float v1[3], v2[3], relativeVelocity[3]; // calc relative velocity - + // compute barycentric coordinates for both collision points collision_compute_barycentric ( collpair->pa, verts1[collpair->ap1].txold, @@ -487,14 +487,14 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned /* only get objects with collision modifier */ if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision)) cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type); - + if (cmd) { /* extend array */ if (*numobj >= *maxobj) { *maxobj *= 2; *objs= MEM_reallocN(*objs, sizeof(Object *)*(*maxobj)); } - + (*objs)[*numobj] = ob; (*numobj)++; } @@ -511,7 +511,7 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned } // return all collision objects in scene -// collision object will exclude self +// collision object will exclude self Object **get_collisionobjects_ext(Scene *scene, Object *self, Group *group, int layer, unsigned int *numcollobj, unsigned int modifier_type, bool dupli) { Base *base; @@ -519,7 +519,7 @@ Object **get_collisionobjects_ext(Scene *scene, Object *self, Group *group, int GroupObject *go; unsigned int numobj= 0, maxobj= 100; int level = dupli ? 0 : 1; - + objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray"); /* gather all collision objects */ @@ -560,7 +560,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, if (ob->pd && ob->pd->deflect) cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); - + if (cmd && cmd->bvhtree) { if (*objs == NULL) *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array"); @@ -588,7 +588,7 @@ ListBase *get_collider_cache(Scene *scene, Object *self, Group *group) { GroupObject *go; ListBase *objs= NULL; - + /* add object in same layer in scene */ if (group) { for (go= group->gobject.first; go; go= go->next) @@ -623,7 +623,7 @@ static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, Collis CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt) { int i; - + *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 4, "collision array" ); // * 4 since cloth_collision_static can return more than 1 collision *collisions_index = *collisions; @@ -640,10 +640,10 @@ static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, Collision ClothVertex *verts = NULL; int ret = 0; int result = 0; - + mvert_num = clmd->clothObject->mvert_num; verts = cloth->verts; - + // process all collisions (calculate impulses, TODO: also repulses if distance too short) result = 1; for ( j = 0; j < 2; j++ ) { /* 5 is just a value that ensures convergence */ @@ -689,7 +689,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL) return 0; - + verts = cloth->verts; /* numfaces = cloth->numfaces; */ /* UNUSED */ mvert_num = cloth->mvert_num; @@ -701,9 +701,9 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa // update cloth bvh bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function) bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function) - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); - + if (!collobjs) return 0; @@ -721,31 +721,31 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa do { CollPair **collisions, **collisions_index; - + ret2 = 0; collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData *)modifiers_findByType(collob, eModifierType_Collision); BVHTreeOverlap *overlap = NULL; unsigned int result = 0; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); - + // go to next object if no overlap is there if ( result && overlap ) { /* check if collisions really happen (costly near check) */ - cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], + cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap, dt/(float)clmd->coll_parms->loop_count); - + // resolve nearby collisions ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i], collisions_index[i]); ret2 += ret; @@ -755,11 +755,11 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa MEM_freeN ( overlap ); } rounds++; - + for (i = 0; i < numcollobj; i++) { if ( collisions[i] ) MEM_freeN ( collisions[i] ); } - + MEM_freeN(collisions); MEM_freeN(collisions_index); @@ -779,8 +779,8 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa VECADD ( verts[i].tx, verts[i].txold, verts[i].tv ); } //////////////////////////////////////////////////////////// - - + + //////////////////////////////////////////////////////////// // Test on *simple* selfcollisions //////////////////////////////////////////////////////////// @@ -789,15 +789,15 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa /* TODO: add coll quality rounds again */ BVHTreeOverlap *overlap = NULL; unsigned int result = 0; - + // collisions = 1; verts = cloth->verts; // needed for openMP - + /* numfaces = cloth->numfaces; */ /* UNUSED */ mvert_num = cloth->mvert_num; - + verts = cloth->verts; - + if ( cloth->bvhselftree ) { // search for overlapping collision pairs overlap = BLI_bvhtree_overlap(cloth->bvhselftree, cloth->bvhselftree, &result, NULL, NULL); @@ -807,12 +807,12 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa float temp[3]; float length = 0; float mindistance; - + i = overlap[k].indexA; j = overlap[k].indexB; - + mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len ); - + if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) { if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) ) @@ -826,20 +826,20 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa { continue; } - + sub_v3_v3v3(temp, verts[i].tx, verts[j].tx); - + if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue; - + if (BLI_edgeset_haskey(cloth->edgeset, i, j)) { continue; } - + length = normalize_v3(temp ); - + if ( length < mindistance ) { float correction = mindistance - length; - + if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) { mul_v3_fl(temp, -correction); VECADD ( verts[j].tx, verts[j].tx, temp ); @@ -851,7 +851,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa else { mul_v3_fl(temp, correction * -0.5f); VECADD ( verts[j].tx, verts[j].tx, temp ); - + sub_v3_v3v3(verts[i].tx, verts[i].tx, temp); } ret = 1; @@ -861,10 +861,10 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa // check for approximated time collisions } } - + if ( overlap ) MEM_freeN ( overlap ); - + } } //////////////////////////////////////////////////////////// @@ -883,7 +883,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa } } while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) ); - + if (collobjs) MEM_freeN(collobjs); @@ -900,14 +900,14 @@ BLI_INLINE void max_v3_v3v3(float r[3], const float a[3], const float b[3]) void collision_get_collider_velocity(float vel_old[3], float vel_new[3], CollisionModifierData *collmd, CollPair *collpair) { float u1, u2, u3; - + /* compute barycentric coordinates */ collision_compute_barycentric(collpair->pb, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, &u1, &u2, &u3); - + collision_interpolateOnTriangle(vel_new, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3); /* XXX assume constant velocity of the collider for now */ copy_v3_v3(vel_old, vel_new); @@ -920,7 +920,7 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll float restitution = (1.0f - clmd->coll_parms->damping) * (1.0f - pd->pdef_sbdamp); float inv_dt = 1.0f / dt; Cloth *cloth1 = clmd->clothObject; - + // float w1, w2; float u1, u2, u3; float v1[3], v2_old[3], v2_new[3], v_rel_old[3], v_rel_new[3]; @@ -974,20 +974,20 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll float v_nor_old, v_nor_new; float v_tan_old[3], v_tan_new[3]; float bounce, repulse; - + /* Collision response based on * "Simulating Complex Hair with Robust Collision Handling" (Choe, Choi, Ko, ACM SIGGRAPH 2005) * http://graphics.snu.ac.kr/publications/2005-choe-HairSim/Choe_2005_SCA.pdf */ - + v_nor_old = mag_v_rel; v_nor_new = dot_v3v3(v_rel_new, collpair->normal); - + madd_v3_v3v3fl(v_tan_old, v_rel_old, collpair->normal, -v_nor_old); madd_v3_v3v3fl(v_tan_new, v_rel_new, collpair->normal, -v_nor_new); - + repulse = -margin_distance * inv_dt + dot_v3v3(v1, collpair->normal); - + if (margin_distance < -epsilon2) { bounce = -v_nor_new + v_nor_old * restitution; mul_v3_v3fl(impulse, collpair->normal, max_ff(repulse, bounce)); @@ -997,10 +997,10 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll mul_v3_v3fl(impulse, collpair->normal, repulse); } cloth1->verts[collpair->ap1].impulse_count++; - + result = true; } - + if (result) { int i = 0; @@ -1018,21 +1018,21 @@ BLI_INLINE bool cloth_point_face_collision_params(const float p1[3], const float { float edge1[3], edge2[3], p2face[3], p1p2[3], v0p2[3]; float nor_v0p2, nor_p1p2; - + sub_v3_v3v3(edge1, v1, v0); sub_v3_v3v3(edge2, v2, v0); cross_v3_v3v3(r_nor, edge1, edge2); normalize_v3(r_nor); - + nor_v0p2 = dot_v3v3(v0p2, r_nor); madd_v3_v3v3fl(p2face, p2, r_nor, -nor_v0p2); interp_weights_tri_v3(r_w, v0, v1, v2, p2face); - + sub_v3_v3v3(p1p2, p2, p1); sub_v3_v3v3(v0p2, p2, v0); nor_p1p2 = dot_v3v3(p1p2, r_nor); *r_lambda = (nor_p1p2 != 0.0f ? nor_v0p2 / nor_p1p2 : 0.0f); - + return r_w[1] >= 0.0f && r_w[2] >= 0.0f && r_w[1] + r_w[2] <= 1.0f; #if 0 /* XXX this method uses the intersection point, but is broken and doesn't work well in general */ @@ -1089,7 +1089,7 @@ static CollPair *cloth_point_collpair( if (!cloth_point_face_collision_params(p1, p2, co1, co2, co3, facenor, &lambda, w)) return collpair; - + sub_v3_v3v3(v1p1, p1, co1); // distance1 = dot_v3v3(v1p1, facenor); sub_v3_v3v3(v1p2, p2, co1); @@ -1097,7 +1097,7 @@ static CollPair *cloth_point_collpair( // if (distance2 > epsilon || (distance1 < 0.0f && distance2 < 0.0f)) if (distance2 > epsilon) return collpair; - + collpair->face1 = index_cloth; /* XXX actually not a face, but equivalent index for point */ collpair->face2 = index_coll; collpair->ap1 = index_cloth; @@ -1105,20 +1105,20 @@ static CollPair *cloth_point_collpair( collpair->bp1 = bp1; collpair->bp2 = bp2; collpair->bp3 = bp3; - + /* note: using the second point here, which is * the current updated position that needs to be corrected */ copy_v3_v3(collpair->pa, p2); collpair->distance = distance2; mul_v3_v3fl(collpair->vector, facenor, -distance2); - + interp_v3_v3v3v3(collpair->pb, co1, co2, co3, w); - + copy_v3_v3(collpair->normal, facenor); collpair->time = lambda; collpair->flag = 0; - + collpair++; return collpair; } @@ -1153,7 +1153,7 @@ static void cloth_points_objcollisions_nearcheck( int numresult, BVHTreeOverlap *overlap, float epsilon, double dt) { int i; - + /* can return 2 collisions in total */ *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 2, "collision array" ); *collisions_index = *collisions; @@ -1172,11 +1172,11 @@ static int cloth_points_objcollisions_resolve( int i = 0, mvert_num = clmd->clothObject->mvert_num; ClothVertex *verts = cloth->verts; int ret = 0; - + // process all collisions if ( collmd->bvhtree ) { bool result = cloth_points_collision_response_static(clmd, collmd, pd, collisions, collisions_index, dt); - + // apply impulses in parallel if (result) { for (i = 0; i < mvert_num; i++) { @@ -1186,13 +1186,13 @@ static int cloth_points_objcollisions_resolve( VECADD ( verts[i].tv, verts[i].tv, verts[i].impulse); zero_v3(verts[i].impulse); verts[i].impulse_count = 0; - + ret++; } } } } - + return ret; } @@ -1208,32 +1208,32 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f int ret = 0, ret2 = 0; Object **collobjs = NULL; unsigned int numcollobj = 0; - + verts = cloth->verts; mvert_num = cloth->mvert_num; - + //////////////////////////////////////////////////////////// // static collisions //////////////////////////////////////////////////////////// - + // create temporary cloth points bvh cloth_bvh = BLI_bvhtree_new(mvert_num, max_ff(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel), 4, 6); /* fill tree */ for (i = 0; i < mvert_num; i++) { float co[2][3]; - + copy_v3_v3(co[0], verts[i].x); copy_v3_v3(co[1], verts[i].tx); - + BLI_bvhtree_insert(cloth_bvh, i, co[0], 2); } /* balance tree */ BLI_bvhtree_balance(cloth_bvh); - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); if (!collobjs) return 0; - + /* move object to position (step) in time */ for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; @@ -1247,12 +1247,12 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f do { CollPair **collisions, **collisions_index; - + ret2 = 0; - + collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; @@ -1260,35 +1260,35 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f BVHTreeOverlap *overlap = NULL; unsigned int result = 0; float epsilon; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); epsilon = BLI_bvhtree_get_epsilon(collmd->bvhtree); - + // go to next object if no overlap is there if (result && overlap) { /* check if collisions really happen (costly near check) */ cloth_points_objcollisions_nearcheck(clmd, collmd, &collisions[i], &collisions_index[i], result, overlap, epsilon, round_dt); - + // resolve nearby collisions ret += cloth_points_objcollisions_resolve(clmd, collmd, collob->pd, collisions[i], collisions_index[i], round_dt); ret2 += ret; } - + if (overlap) MEM_freeN ( overlap ); } rounds++; - + for (i = 0; i < numcollobj; i++) { if (collisions[i]) MEM_freeN(collisions[i]); } - + MEM_freeN(collisions); MEM_freeN(collisions_index); @@ -1310,7 +1310,7 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f //////////////////////////////////////////////////////////// } while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) ); - + if (collobjs) MEM_freeN(collobjs); @@ -1326,53 +1326,53 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, BVHTree *cloth_bvh; unsigned int i = 0, mvert_num = 0; ClothVertex *verts = NULL; - + ColliderContacts *collider_contacts; - + Object **collobjs = NULL; unsigned int numcollobj = 0; - + verts = cloth->verts; mvert_num = cloth->mvert_num; - + //////////////////////////////////////////////////////////// // static collisions //////////////////////////////////////////////////////////// - + // create temporary cloth points bvh cloth_bvh = BLI_bvhtree_new(mvert_num, max_ff(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel), 4, 6); /* fill tree */ for (i = 0; i < mvert_num; i++) { float co[6]; - + copy_v3_v3(&co[0*3], verts[i].x); copy_v3_v3(&co[1*3], verts[i].tx); - + BLI_bvhtree_insert(cloth_bvh, i, co, 2); } /* balance tree */ BLI_bvhtree_balance(cloth_bvh); - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); if (!collobjs) { *r_collider_contacts = NULL; *r_totcolliders = 0; return; } - + /* move object to position (step) in time */ for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData *)modifiers_findByType(collob, eModifierType_Collision); if (!collmd->bvhtree) continue; - + /* move object to position (step) in time */ collision_move_object ( collmd, step + dt, step ); } - + collider_contacts = MEM_callocN(sizeof(ColliderContacts) * numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { ColliderContacts *ct = collider_contacts + i; @@ -1381,46 +1381,46 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, BVHTreeOverlap *overlap; unsigned int result = 0; float epsilon; - + ct->ob = collob; ct->collmd = collmd; ct->collisions = NULL; ct->totcollisions = 0; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); epsilon = BLI_bvhtree_get_epsilon(collmd->bvhtree); - + // go to next object if no overlap is there if (result && overlap) { CollPair *collisions_index; - + /* check if collisions really happen (costly near check) */ cloth_points_objcollisions_nearcheck(clmd, collmd, &ct->collisions, &collisions_index, result, overlap, epsilon, dt); ct->totcollisions = (int)(collisions_index - ct->collisions); - + // resolve nearby collisions // ret += cloth_points_objcollisions_resolve(clmd, collmd, collob->pd, collisions[i], collisions_index[i], dt); } - + if (overlap) MEM_freeN(overlap); } - + if (collobjs) MEM_freeN(collobjs); BLI_bvhtree_free(cloth_bvh); - + //////////////////////////////////////////////////////////// // update positions // this is needed for bvh_calc_DOP_hull_moving() [kdop.c] //////////////////////////////////////////////////////////// - + // verts come from clmd for (i = 0; i < mvert_num; i++) { if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) { @@ -1428,11 +1428,11 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, continue; } } - + VECADD(verts[i].tx, verts[i].txold, verts[i].tv); } //////////////////////////////////////////////////////////// - + *r_collider_contacts = collider_contacts; *r_totcolliders = numcollobj; } diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 6c97380b9ca9..ff4795afe878 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -62,21 +62,21 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m { int a; float clipminx, clipminy, clipmaxx, clipmaxy; - + cumap->flag = CUMA_DO_CLIP; if (tot == 4) cumap->cur = 3; /* rhms, hack for 'col' curve? */ - + clipminx = min_ff(minx, maxx); clipminy = min_ff(miny, maxy); clipmaxx = max_ff(minx, maxx); clipmaxy = max_ff(miny, maxy); - + BLI_rctf_init(&cumap->curr, clipminx, clipmaxx, clipminy, clipmaxy); cumap->clipr = cumap->curr; - + cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f; cumap->bwmul[0] = cumap->bwmul[1] = cumap->bwmul[2] = 1.0f; - + for (a = 0; a < tot; a++) { cumap->cm[a].flag = CUMA_EXTEND_EXTRAPOLATE; cumap->cm[a].totpoint = 2; @@ -187,7 +187,7 @@ bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) { CurveMapPoint *cmp; int a, b, removed = 0; - + /* must have 2 points minimum */ if (cuma->totpoint <= 2) return false; @@ -204,7 +204,7 @@ bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) removed++; } } - + MEM_freeN(cuma->curve); cuma->curve = cmp; cuma->totpoint -= removed; @@ -216,7 +216,7 @@ void curvemap_remove(CurveMap *cuma, const short flag) { CurveMapPoint *cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points"); int a, b, removed = 0; - + /* well, lets keep the two outer points! */ cmp[0] = cuma->curve[0]; for (a = 1, b = 1; a < cuma->totpoint - 1; a++) { @@ -229,7 +229,7 @@ void curvemap_remove(CurveMap *cuma, const short flag) } } cmp[b] = cuma->curve[a]; - + MEM_freeN(cuma->curve); cuma->curve = cmp; cuma->totpoint -= removed; @@ -359,11 +359,11 @@ void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope) if (slope == CURVEMAP_SLOPE_POSITIVE) { int i, last = cuma->totpoint - 1; CurveMapPoint *newpoints = MEM_dupallocN(cuma->curve); - + for (i = 0; i < cuma->totpoint; i++) { newpoints[i].y = cuma->curve[last - i].y; } - + MEM_freeN(cuma->curve); cuma->curve = newpoints; } @@ -397,7 +397,7 @@ void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope) void curvemap_handle_set(CurveMap *cuma, int type) { int a; - + for (a = 0; a < cuma->totpoint; a++) { if (cuma->curve[a].flag & CUMA_SELECT) { cuma->curve[a].flag &= ~(CUMA_HANDLE_VECTOR | CUMA_HANDLE_AUTO_ANIM); @@ -435,9 +435,9 @@ static void calchandle_curvemap( if (bezt->h1 == 0 && bezt->h2 == 0) { return; } - + p2 = bezt->vec[1]; - + if (prev == NULL) { p3 = next->vec[1]; pt[0] = 2.0f * p2[0] - p3[0]; @@ -447,7 +447,7 @@ static void calchandle_curvemap( else { p1 = prev->vec[1]; } - + if (next == NULL) { p1 = prev->vec[1]; pt[0] = 2.0f * p2[0] - p1[0]; @@ -474,7 +474,7 @@ static void calchandle_curvemap( len = len_v2(tvec) * 2.5614f; if (len != 0.0f) { - + if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM)) { len_a /= len; madd_v2_v2v2fl(p2_h1, p2, tvec, -len_a); @@ -541,7 +541,7 @@ static void calchandle_curvemap( #undef p2_h2 } -/* in X, out Y. +/* in X, out Y. * X is presumed to be outside first or last */ static float curvemap_calc_extend(const CurveMap *cuma, float x, const float first[2], const float last[2]) { @@ -579,16 +579,16 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) BezTriple *bezt; float *fp, *allpoints, *lastpoint, curf, range; int a, totpoint; - + if (cuma->curve == NULL) return; - + /* default rect also is table range */ cuma->mintable = clipr->xmin; cuma->maxtable = clipr->xmax; - + /* hrmf... we now rely on blender ipo beziers, these are more advanced */ bezt = MEM_callocN(cuma->totpoint * sizeof(BezTriple), "beztarr"); - + for (a = 0; a < cuma->totpoint; a++) { cuma->mintable = min_ff(cuma->mintable, cmp[a].x); cuma->maxtable = max_ff(cuma->maxtable, cmp[a].x); @@ -604,27 +604,27 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) bezt[a].h1 = bezt[a].h2 = HD_AUTO; } } - + const BezTriple *bezt_prev = NULL; for (a = 0; a < cuma->totpoint; a++) { const BezTriple *bezt_next = (a != cuma->totpoint - 1) ? &bezt[a + 1] : NULL; calchandle_curvemap(&bezt[a], bezt_prev, bezt_next); bezt_prev = &bezt[a]; } - - /* first and last handle need correction, instead of pointing to center of next/prev, + + /* first and last handle need correction, instead of pointing to center of next/prev, * we let it point to the closest handle */ if (cuma->totpoint > 2) { float hlen, nlen, vec[3]; - + if (bezt[0].h2 == HD_AUTO) { - + hlen = len_v3v3(bezt[0].vec[1], bezt[0].vec[2]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[1].vec[0]); if (vec[0] < bezt[0].vec[1][0]) vec[0] = bezt[0].vec[1][0]; - + sub_v3_v3(vec, bezt[0].vec[1]); nlen = len_v3(vec); if (nlen > FLT_EPSILON) { @@ -635,13 +635,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) } a = cuma->totpoint - 1; if (bezt[a].h2 == HD_AUTO) { - + hlen = len_v3v3(bezt[a].vec[1], bezt[a].vec[0]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[a - 1].vec[2]); if (vec[0] > bezt[a].vec[1][0]) vec[0] = bezt[a].vec[1][0]; - + sub_v3_v3(vec, bezt[a].vec[1]); nlen = len_v3(vec); if (nlen > FLT_EPSILON) { @@ -656,13 +656,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) MEM_freeN(cuma->table); totpoint = (cuma->totpoint - 1) * CM_RESOL; fp = allpoints = MEM_callocN(totpoint * 2 * sizeof(float), "table"); - + for (a = 0; a < cuma->totpoint - 1; a++, fp += 2 * CM_RESOL) { correct_bezpart(bezt[a].vec[1], bezt[a].vec[2], bezt[a + 1].vec[0], bezt[a + 1].vec[1]); BKE_curve_forward_diff_bezier(bezt[a].vec[1][0], bezt[a].vec[2][0], bezt[a + 1].vec[0][0], bezt[a + 1].vec[1][0], fp, CM_RESOL - 1, 2 * sizeof(float)); BKE_curve_forward_diff_bezier(bezt[a].vec[1][1], bezt[a].vec[2][1], bezt[a + 1].vec[0][1], bezt[a + 1].vec[1][1], fp + 1, CM_RESOL - 1, 2 * sizeof(float)); } - + /* store first and last handle for extrapolation, unit length */ cuma->ext_in[0] = bezt[0].vec[0][0] - bezt[0].vec[1][0]; cuma->ext_in[1] = bezt[0].vec[0][1] - bezt[0].vec[1][1]; @@ -676,13 +676,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) range = sqrtf(cuma->ext_out[0] * cuma->ext_out[0] + cuma->ext_out[1] * cuma->ext_out[1]); cuma->ext_out[0] /= range; cuma->ext_out[1] /= range; - + /* cleanup */ MEM_freeN(bezt); range = CM_TABLEDIV * (cuma->maxtable - cuma->mintable); cuma->range = 1.0f / range; - + /* now make a table with CM_TABLE equal x distances */ fp = allpoints; lastpoint = allpoints + 2 * (totpoint - 1); @@ -691,7 +691,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) for (a = 0; a <= CM_TABLE; a++) { curf = cuma->mintable + range * (float)a; cmp[a].x = curf; - + /* get the first x coordinate larger than curf */ while (curf >= fp[0] && fp != lastpoint) { fp += 2; @@ -708,7 +708,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) cmp[a].y = fac1 * fp[-1] + (1.0f - fac1) * fp[1]; } } - + MEM_freeN(allpoints); cuma->table = cmp; } @@ -718,7 +718,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) void curvemapping_premultiply(CurveMapping *cumap, int restore) { int a; - + if (restore) { if (cumap->flag & CUMA_PREMULLED) { for (a = 0; a < 3; a++) { @@ -731,7 +731,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) zero_v2(cumap->cm[a].premul_ext_in); zero_v2(cumap->cm[a].premul_ext_out); } - + cumap->flag &= ~CUMA_PREMULLED; } } @@ -745,10 +745,10 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) cumap->cm[a].table = MEM_mallocN((CM_TABLE + 1) * sizeof(CurveMapPoint), "premul table"); memcpy(cumap->cm[a].table, cumap->cm[a].premultable, (CM_TABLE + 1) * sizeof(CurveMapPoint)); } - + if (cumap->cm[3].table == NULL) curvemap_make_table(cumap->cm + 3, &cumap->clipr); - + /* premul */ for (a = 0; a < 3; a++) { int b; @@ -761,7 +761,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) mul_v2_v2(cumap->cm[a].ext_in, cumap->cm[3].ext_in); mul_v2_v2(cumap->cm[a].ext_out, cumap->cm[3].ext_out); } - + cumap->flag |= CUMA_PREMULLED; } } @@ -770,7 +770,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) static int sort_curvepoints(const void *a1, const void *a2) { const struct CurveMapPoint *x1 = a1, *x2 = a2; - + if (x1->x > x2->x) return 1; else if (x1->x < x2->x) return -1; return 0; @@ -821,10 +821,10 @@ void curvemapping_changed(CurveMapping *cumap, const bool rem_doubles) cumap->curr.ymax = cumap->clipr.ymax; } } - - + + qsort(cmp, cuma->totpoint, sizeof(CurveMapPoint), sort_curvepoints); - + /* remove doubles, threshold set on 1% of default range */ if (rem_doubles && cuma->totpoint > 2) { for (a = 0; a < cuma->totpoint - 1; a++) { @@ -873,14 +873,14 @@ float curvemap_evaluateF(const CurveMap *cuma, float value) /* index in table */ fi = (value - cuma->mintable) * cuma->range; i = (int)fi; - + /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */ if (fi < 0.0f || fi > CM_TABLE) return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x); else { if (i < 0) return cuma->table[0].y; if (i >= CM_TABLE) return cuma->table[CM_TABLE].y; - + fi = fi - (float)i; return (1.0f - fi) * cuma->table[i].y + (fi) * cuma->table[i + 1].y; } @@ -963,18 +963,18 @@ void curvemapping_evaluate_premulRGB(const CurveMapping *cumap, unsigned char ve int curvemapping_RGBA_does_something(const CurveMapping *cumap) { int a; - + if (cumap->black[0] != 0.0f) return 1; if (cumap->black[1] != 0.0f) return 1; if (cumap->black[2] != 0.0f) return 1; if (cumap->white[0] != 1.0f) return 1; if (cumap->white[1] != 1.0f) return 1; if (cumap->white[2] != 1.0f) return 1; - + for (a = 0; a < CM_TOT; a++) { if (cumap->cm[a].curve) { if (cumap->cm[a].totpoint != 2) return 1; - + if (cumap->cm[a].curve[0].x != 0.0f) return 1; if (cumap->cm[a].curve[0].y != 0.0f) return 1; if (cumap->cm[a].curve[1].x != 1.0f) return 1; @@ -987,9 +987,9 @@ int curvemapping_RGBA_does_something(const CurveMapping *cumap) void curvemapping_initialize(CurveMapping *cumap) { int a; - + if (cumap == NULL) return; - + for (a = 0; a < CM_TOT; a++) { if (cumap->cm[a].table == NULL) curvemap_make_table(cumap->cm + a, &cumap->clipr); @@ -999,7 +999,7 @@ void curvemapping_initialize(CurveMapping *cumap) void curvemapping_table_RGBA(const CurveMapping *cumap, float **array, int *size) { int a; - + *size = CM_TABLE + 1; *array = MEM_callocN(sizeof(float) * (*size) * 4, "CurveMapping"); @@ -1165,7 +1165,7 @@ typedef struct ScopesUpdateDataChunk { float min[3], max[3]; } ScopesUpdateDataChunk; -static void scopes_update_cb(void *__restrict userdata, +static void scopes_update_cb(void *__restrict userdata, const int y, const ParallelRangeTLS *__restrict tls) { @@ -1347,7 +1347,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * /* convert to number of lines with logarithmic scale */ scopes->sample_lines = (scopes->accuracy * 0.01f) * (scopes->accuracy * 0.01f) * ibuf->y; CLAMP_MIN(scopes->sample_lines, 1); - + if (scopes->sample_full) scopes->sample_lines = ibuf->y; @@ -1356,9 +1356,9 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * scopes->minmax[a][0] = 25500.0f; scopes->minmax[a][1] = -25500.0f; } - + scopes->waveform_tot = ibuf->x * scopes->sample_lines; - + if (scopes->waveform_1) MEM_freeN(scopes->waveform_1); if (scopes->waveform_2) @@ -1367,12 +1367,12 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * MEM_freeN(scopes->waveform_3); if (scopes->vecscope) MEM_freeN(scopes->vecscope); - + scopes->waveform_1 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 1"); scopes->waveform_2 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 2"); scopes->waveform_3 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 3"); scopes->vecscope = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "vectorscope point channel"); - + if (ibuf->rect_float) { cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings); } @@ -1411,7 +1411,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * bin_a[a] = sqrt(bin_a[a]); } #endif - + /* convert hist data to float (proportional to max count) */ nl = na = nr = nb = ng = 0; for (a = 0; a < 256; a++) { @@ -1426,7 +1426,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * divr = nr ? 1.0 / (double)nr : 1.0; divg = ng ? 1.0 / (double)ng : 1.0; divb = nb ? 1.0 / (double)nb : 1.0; - + for (a = 0; a < 256; a++) { scopes->hist.data_luma[a] = bin_lum[a] * divl; scopes->hist.data_r[a] = bin_r[a] * divr; @@ -1439,7 +1439,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * IMB_colormanagement_processor_free(cm_processor); if (cache_handle) IMB_display_buffer_release(cache_handle); - + scopes->ok = 1; } diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index 25a77821dd27..7d8616589933 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -30,7 +30,7 @@ */ -#include +#include #include #include #include @@ -124,13 +124,13 @@ void BKE_constraint_unique_name(bConstraint *con, ListBase *list) bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subdata, short datatype) { bConstraintOb *cob; - + /* create regardless of whether we have any data! */ cob = MEM_callocN(sizeof(bConstraintOb), "bConstraintOb"); - + /* for system time, part of deglobalization, code nicer later with local time (ton) */ cob->scene = scene; - + /* based on type of available data */ switch (datatype) { case CONSTRAINT_OBTYPE_OBJECT: @@ -139,7 +139,7 @@ bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subda if (ob) { cob->ob = ob; cob->type = datatype; - + if (cob->ob->rotmode > 0) { /* Should be some kind of Euler order, so use it */ /* NOTE: Versions <= 2.76 assumed that "default" order @@ -157,7 +157,7 @@ bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subda } else unit_m4(cob->matrix); - + copy_m4_m4(cob->startmat, cob->matrix); break; } @@ -168,7 +168,7 @@ bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subda cob->ob = ob; cob->pchan = (bPoseChannel *)subdata; cob->type = datatype; - + if (cob->pchan->rotmode > 0) { /* should be some type of Euler order */ cob->rotOrder = cob->pchan->rotmode; @@ -177,13 +177,13 @@ bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subda /* Quats, so eulers should just use default order */ cob->rotOrder = EULER_ORDER_DEFAULT; } - + /* matrix in world-space */ mul_m4_m4m4(cob->matrix, ob->obmat, cob->pchan->pose_mat); } else unit_m4(cob->matrix); - + copy_m4_m4(cob->startmat, cob->matrix); break; } @@ -200,11 +200,11 @@ bConstraintOb *BKE_constraints_make_evalob(Scene *scene, Object *ob, void *subda void BKE_constraints_clear_evalob(bConstraintOb *cob) { float delta[4][4], imat[4][4]; - + /* prevent crashes */ - if (cob == NULL) + if (cob == NULL) return; - + /* calculate delta of constraints evaluation */ invert_m4_m4(imat, cob->startmat); /* XXX This would seem to be in wrong order. However, it does not work in 'right' order - would be nice to @@ -212,7 +212,7 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) * In any case, we **do not get a delta** here (e.g. startmat & matrix having same location, still gives * a 'delta' with non-null translation component :/ ).*/ mul_m4_m4m4(delta, cob->matrix, imat); - + /* copy matrices back to source */ switch (cob->type) { case CONSTRAINT_OBTYPE_OBJECT: @@ -221,7 +221,7 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) if (cob->ob) { /* copy new ob-matrix back to owner */ copy_m4_m4(cob->ob->obmat, cob->matrix); - + /* copy inverse of delta back to owner */ invert_m4_m4(cob->ob->constinv, delta); } @@ -233,21 +233,21 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) if (cob->ob && cob->pchan) { /* copy new pose-matrix back to owner */ mul_m4_m4m4(cob->pchan->pose_mat, cob->ob->imat, cob->matrix); - + /* copy inverse of delta back to owner */ invert_m4_m4(cob->pchan->constinv, delta); } break; } } - + /* free tempolary struct */ MEM_freeN(cob); } /* -------------- Space-Conversion API -------------- */ -/* This function is responsible for the correct transformations/conversions +/* This function is responsible for the correct transformations/conversions * of a matrix from one space to another for constraint evaluation. * For now, this is only implemented for Objects and PoseChannels. */ @@ -256,12 +256,12 @@ void BKE_constraint_mat_convertspace( { float diff_mat[4][4]; float imat[4][4]; - + /* prevent crashes in these unlikely events */ if (ob == NULL || mat == NULL) return; /* optimize trick - check if need to do anything */ if (from == to) return; - + /* are we dealing with pose-channels or objects */ if (pchan) { /* pose channels */ @@ -271,7 +271,7 @@ void BKE_constraint_mat_convertspace( /* world to pose */ invert_m4_m4(imat, ob->obmat); mul_m4_m4m4(mat, imat, mat); - + /* use pose-space as stepping stone for other spaces... */ if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) { /* call self with slightly different values */ @@ -307,7 +307,7 @@ void BKE_constraint_mat_convertspace( /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */ BKE_armature_mat_bone_to_pose(pchan, mat, mat); } - + /* use pose-space as stepping stone for other spaces */ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) { /* call self with slightly different values */ @@ -322,7 +322,7 @@ void BKE_constraint_mat_convertspace( copy_m4_m4(diff_mat, pchan->bone->arm_mat); mul_m4_m4m4(mat, mat, diff_mat); } - + /* use pose-space as stepping stone for other spaces */ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) { /* call self with slightly different values */ @@ -343,7 +343,7 @@ void BKE_constraint_mat_convertspace( mul_m4_m4m4(mat, imat, mat); } else { - /* Local space in this case will have to be defined as local to the owner's + /* Local space in this case will have to be defined as local to the owner's * transform-property-rotated axes. So subtract this rotation component. */ /* XXX This is actually an ugly hack, local space of a parent-less object *is* the same as @@ -358,7 +358,7 @@ void BKE_constraint_mat_convertspace( normalize_m4(diff_mat); } zero_v3(diff_mat[3]); - + invert_m4_m4_safe(imat, diff_mat); mul_m4_m4m4(mat, imat, mat); } @@ -371,7 +371,7 @@ void BKE_constraint_mat_convertspace( mul_m4_m4m4(mat, diff_mat, mat); } else { - /* Local space in this case will have to be defined as local to the owner's + /* Local space in this case will have to be defined as local to the owner's * transform-property-rotated axes. So add back this rotation component. */ /* XXX See comment above for world->local case... */ @@ -380,7 +380,7 @@ void BKE_constraint_mat_convertspace( normalize_m4(diff_mat); } zero_v3(diff_mat[3]); - + mul_m4_m4m4(mat, diff_mat, mat); } } @@ -399,10 +399,10 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ float imat[3][3], tmat[3][3]; const int defgroup = defgroup_name_index(ob, substring); short freeDM = 0; - + /* initialize target matrix using target matrix */ copy_m4_m4(mat, ob->obmat); - + /* get index of vertex group */ if (defgroup == -1) return; @@ -414,18 +414,18 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ } else { /* when not in EditMode, use the 'final' derived mesh, depsgraph - * ensures we build with CD_MDEFORMVERT layer + * ensures we build with CD_MDEFORMVERT layer */ dm = (DerivedMesh *)ob->derivedFinal; } - + /* only continue if there's a valid DerivedMesh */ if (dm) { MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT); int numVerts = dm->getNumVerts(dm); int i; float co[3], nor[3]; - + /* check that dvert is a valid pointers (just in case) */ if (dvert) { MDeformVert *dv = dvert; @@ -449,22 +449,22 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ mul_v3_fl(vec, 1.0f / weightsum); mul_v3_fl(normal, 1.0f / weightsum); } - - - /* derive the rotation from the average normal: - * - code taken from transform_manipulator.c, + + + /* derive the rotation from the average normal: + * - code taken from transform_manipulator.c, * calc_manipulator_stats, V3D_MANIP_NORMAL case */ /* we need the transpose of the inverse for a normal... */ copy_m3_m4(imat, ob->obmat); - + invert_m3_m3(tmat, imat); transpose_m3(tmat); mul_m3_v3(tmat, normal); - + normalize_v3(normal); copy_v3_v3(plane, tmat[1]); - + cross_v3_v3v3(mat[0], normal, plane); if (len_squared_v3(mat[0]) < SQUARE(1e-3f)) { copy_v3_v3(plane, tmat[0]); @@ -476,12 +476,12 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ normalize_m4(mat); - + /* apply the average coordinate as the new location */ mul_v3_m4v3(mat[3], ob->obmat, vec); } } - + /* free temporary DerivedMesh created (in EditMode case) */ if (dm && freeDM) dm->release(dm); @@ -491,25 +491,25 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ static void contarget_get_lattice_mat(Object *ob, const char *substring, float mat[4][4]) { Lattice *lt = (Lattice *)ob->data; - + DispList *dl = ob->curve_cache ? BKE_displist_find(&ob->curve_cache->disp, DL_VERTS) : NULL; const float *co = dl ? dl->verts : NULL; BPoint *bp = lt->def; - + MDeformVert *dv = lt->dvert; int tot_verts = lt->pntsu * lt->pntsv * lt->pntsw; float vec[3] = {0.0f, 0.0f, 0.0f}, tvec[3]; int grouped = 0; int i, n; const int defgroup = defgroup_name_index(ob, substring); - + /* initialize target matrix using target matrix */ copy_m4_m4(mat, ob->obmat); /* get index of vertex group */ if (defgroup == -1) return; if (dv == NULL) return; - + /* 1. Loop through control-points checking if in nominated vertex-group. * 2. If it is, add it to vec to find the average point. */ @@ -524,17 +524,17 @@ static void contarget_get_lattice_mat(Object *ob, const char *substring, float m grouped++; } } - + /* advance pointer to coordinate data */ if (co) co += 3; else bp++; } - + /* find average location, then multiply by ob->obmat to find world-space location */ if (grouped) mul_v3_fl(vec, 1.0f / grouped); mul_v3_m4v3(tvec, ob->obmat, vec); - + /* copy new location to matrix */ copy_v3_v3(mat[3], tvec); } @@ -550,7 +550,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m } /* Case VERTEXGROUP */ /* Current method just takes the average location of all the points in the - * VertexGroup, and uses that as the location value of the targets. Where + * VertexGroup, and uses that as the location value of the targets. Where * possible, the orientation will also be calculated, by calculating an * 'average' vertex normal, and deriving the rotation from that. * @@ -568,7 +568,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m /* Case BONE */ else { bPoseChannel *pchan; - + pchan = BKE_pose_channel_find_name(ob->pose, substring); if (pchan) { /* Multiply the PoseSpace accumulation/final matrix for this @@ -584,22 +584,22 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m Mat4 bbone[MAX_BBONE_SUBDIV]; float tempmat[4][4]; float loc[3], fac; - + /* get bbone segments */ b_bone_spline_setup(pchan, 0, bbone); - + /* figure out which segment(s) the headtail value falls in */ fac = (float)pchan->bone->segments * headtail; - + if (fac >= pchan->bone->segments - 1) { /* special case: end segment doesn't get created properly... */ float pt[3], sfac; int index; - + /* bbone points are in bonespace, so need to move to posespace first */ index = pchan->bone->segments - 1; mul_v3_m4v3(pt, pchan->pose_mat, bbone[index].mat[3]); - + /* interpolate between last segment point and the endpoint */ sfac = fac - (float)(pchan->bone->segments - 1); /* fac is just the "leftover" between penultimate and last points */ interp_v3_v3v3(loc, pt, pchan->pose_tail, sfac); @@ -608,45 +608,45 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m /* get indices for finding interpolating between points along the bbone */ float pt_a[3], pt_b[3], pt[3]; int index_a, index_b; - + index_a = floorf(fac); CLAMP(index_a, 0, MAX_BBONE_SUBDIV - 1); - + index_b = ceilf(fac); CLAMP(index_b, 0, MAX_BBONE_SUBDIV - 1); - + /* interpolate between these points */ copy_v3_v3(pt_a, bbone[index_a].mat[3]); copy_v3_v3(pt_b, bbone[index_b].mat[3]); - + interp_v3_v3v3(pt, pt_a, pt_b, fac - floorf(fac)); - + /* move the point from bone local space to pose space... */ mul_v3_m4v3(loc, pchan->pose_mat, pt); } - + /* use interpolated distance for subtarget */ copy_m4_m4(tempmat, pchan->pose_mat); copy_v3_v3(tempmat[3], loc); - + mul_m4_m4m4(mat, ob->obmat, tempmat); } else { float tempmat[4][4], loc[3]; - + /* interpolate along length of bone */ interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail); - + /* use interpolated distance for subtarget */ copy_m4_m4(tempmat, pchan->pose_mat); copy_v3_v3(tempmat[3], loc); - + mul_m4_m4m4(mat, ob->obmat, tempmat); } } else copy_m4_m4(mat, ob->obmat); - + /* convert matrix space as required */ BKE_constraint_mat_convertspace(ob, pchan, mat, from, to, false); } @@ -657,7 +657,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m * times. In addition to this, each constraint should have a type-info struct, where * its functions are attached for use. */ - + /* Template for type-info data: * - make a copy of this when creating new constraints, and just change the functions * pointed to as necessary @@ -686,7 +686,7 @@ static bConstraintTypeInfo CTI_CONSTRNAME = { }; #endif -/* This function should be used for the get_target_matrix member of all +/* This function should be used for the get_target_matrix member of all * constraints that are not picky about what happens to their target matrix. */ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime)) @@ -697,7 +697,7 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo unit_m4(ct->matrix); } -/* This following macro should be used for all standard single-target *_get_tars functions +/* This following macro should be used for all standard single-target *_get_tars functions * to save typing and reduce maintenance woes. * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) @@ -730,8 +730,8 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo \ BLI_addtail(list, ct); \ } (void)0 - -/* This following macro should be used for all standard single-target *_get_tars functions + +/* This following macro should be used for all standard single-target *_get_tars functions * to save typing and reduce maintenance woes. It does not do the subtarget related operations * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) @@ -770,7 +770,7 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo ct = ctn; \ } \ } (void)0 - + /* This following macro should be used for all standard single-target *_flush_tars functions * to save typing and reduce maintenance woes. It does not do the subtarget related operations. * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed) @@ -796,7 +796,7 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo static void childof_new_data(void *cdata) { bChildOfConstraint *data = (bChildOfConstraint *)cdata; - + data->flag = (CHILDOF_LOCX | CHILDOF_LOCY | CHILDOF_LOCZ | CHILDOF_ROTX | CHILDOF_ROTY | CHILDOF_ROTZ | CHILDOF_SIZEX | CHILDOF_SIZEY | CHILDOF_SIZEZ); @@ -806,7 +806,7 @@ static void childof_new_data(void *cdata) static void childof_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bChildOfConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -816,13 +816,13 @@ static int childof_get_tars(bConstraint *con, ListBase *list) if (con && list) { bChildOfConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -831,7 +831,7 @@ static void childof_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bChildOfConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -845,16 +845,16 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float parmat[4][4]; - + /* simple matrix parenting */ if (data->flag == CHILDOF_ALL) { - - /* multiply target (parent matrix) by offset (parent inverse) to get + + /* multiply target (parent matrix) by offset (parent inverse) to get * the effect of the parent that will be exerted on the owner */ mul_m4_m4m4(parmat, ct->matrix, data->invmat); - - /* now multiply the parent matrix by the owner matrix to get the + + /* now multiply the parent matrix by the owner matrix to get the * the effect of this constraint (i.e. owner is 'parented' to parent) */ mul_m4_m4m4(cob->matrix, parmat, cob->matrix); @@ -863,19 +863,19 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar float invmat[4][4], tempmat[4][4]; float loc[3], eul[3], size[3]; float loco[3], eulo[3], sizo[3]; - + /* get offset (parent-inverse) matrix */ copy_m4_m4(invmat, data->invmat); - + /* extract components of both matrices */ copy_v3_v3(loc, ct->matrix[3]); mat4_to_eulO(eul, ct->rotOrder, ct->matrix); mat4_to_size(size, ct->matrix); - + copy_v3_v3(loco, invmat[3]); mat4_to_eulO(eulo, cob->rotOrder, invmat); mat4_to_size(sizo, invmat); - + /* disable channels not enabled */ if (!(data->flag & CHILDOF_LOCX)) loc[0] = loco[0] = 0.0f; if (!(data->flag & CHILDOF_LOCY)) loc[1] = loco[1] = 0.0f; @@ -886,22 +886,22 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar if (!(data->flag & CHILDOF_SIZEX)) size[0] = sizo[0] = 1.0f; if (!(data->flag & CHILDOF_SIZEY)) size[1] = sizo[1] = 1.0f; if (!(data->flag & CHILDOF_SIZEZ)) size[2] = sizo[2] = 1.0f; - + /* make new target mat and offset mat */ loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder); loc_eulO_size_to_mat4(invmat, loco, eulo, sizo, cob->rotOrder); - - /* multiply target (parent matrix) by offset (parent inverse) to get + + /* multiply target (parent matrix) by offset (parent inverse) to get * the effect of the parent that will be exerted on the owner */ mul_m4_m4m4(parmat, ct->matrix, invmat); - - /* now multiply the parent matrix by the owner matrix to get the + + /* now multiply the parent matrix by the owner matrix to get the * the effect of this constraint (i.e. owner is 'parented' to parent) */ copy_m4_m4(tempmat, cob->matrix); mul_m4_m4m4(cob->matrix, parmat, tempmat); - + /* without this, changes to scale and rotation can change location * of a parentless bone or a disconnected bone. Even though its set * to zero above. */ @@ -933,15 +933,15 @@ static bConstraintTypeInfo CTI_CHILDOF = { static void trackto_new_data(void *cdata) { bTrackToConstraint *data = (bTrackToConstraint *)cdata; - + data->reserved1 = TRACK_Y; data->reserved2 = UP_Z; -} +} static void trackto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTrackToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -951,13 +951,13 @@ static int trackto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTrackToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -966,7 +966,7 @@ static void trackto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTrackToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -976,14 +976,14 @@ static void trackto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static int basis_cross(int n, int m) { switch (n - m) { - case 1: + case 1: case -2: return 1; - - case -1: + + case -1: case 2: return -1; - + default: return 0; } @@ -1039,14 +1039,14 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s if (axis != upflag) { right_index = 3 - axis - upflag; neg = (float)basis_cross(axis, upflag); - + /* account for up direction, track direction */ m[right_index][0] = neg * right[0]; m[right_index][1] = neg * right[1]; m[right_index][2] = neg * right[2]; - + copy_v3_v3(m[upflag], proj); - + copy_v3_v3(m[axis], n); } /* identity matrix - don't do anything if the two axes are the same */ @@ -1060,14 +1060,14 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bTrackToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float size[3], vec[3]; float totmat[3][3]; - + /* Get size property, since ob->size is only the object's own relative size, not its global one */ mat4_to_size(size, cob->matrix); - + /* Clear the object's rotation */ cob->matrix[0][0] = size[0]; cob->matrix[0][1] = 0; @@ -1078,12 +1078,12 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar cob->matrix[2][0] = 0; cob->matrix[2][1] = 0; cob->matrix[2][2] = size[2]; - + /* targetmat[2] instead of ownermat[2] is passed to vectomat * for backwards compatibility it seems... (Aligorith) */ sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]); - vectomat(vec, ct->matrix[2], + vectomat(vec, ct->matrix[2], (short)data->reserved1, (short)data->reserved2, data->flags, totmat); @@ -1111,7 +1111,7 @@ static bConstraintTypeInfo CTI_TRACKTO = { static void kinematic_new_data(void *cdata) { bKinematicConstraint *data = (bKinematicConstraint *)cdata; - + data->weight = 1.0f; data->orientweight = 1.0f; data->iterations = 500; @@ -1122,10 +1122,10 @@ static void kinematic_new_data(void *cdata) static void kinematic_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bKinematicConstraint *data = con->data; - + /* chain target */ func(con, (ID **)&data->tar, false, userdata); - + /* poletarget */ func(con, (ID **)&data->poletar, false, userdata); } @@ -1135,14 +1135,14 @@ static int kinematic_get_tars(bConstraint *con, ListBase *list) if (con && list) { bKinematicConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints is used twice here */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list); - + return 2; } - + return 0; } @@ -1151,7 +1151,7 @@ static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bKinematicConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, no_copy); @@ -1161,13 +1161,13 @@ static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void kinematic_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bKinematicConstraint *data = con->data; - - if (VALID_CONS_TARGET(ct)) + + if (VALID_CONS_TARGET(ct)) constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); else if (ct) { if (data->flag & CONSTRAINT_IK_AUTO) { Object *ob = cob->ob; - + if (ob == NULL) { unit_m4(ct->matrix); } @@ -1204,7 +1204,7 @@ static bConstraintTypeInfo CTI_KINEMATIC = { static void followpath_new_data(void *cdata) { bFollowPathConstraint *data = (bFollowPathConstraint *)cdata; - + data->trackflag = TRACK_Y; data->upflag = UP_Z; data->offset = 0; @@ -1214,7 +1214,7 @@ static void followpath_new_data(void *cdata) static void followpath_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bFollowPathConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1224,13 +1224,13 @@ static int followpath_get_tars(bConstraint *con, ListBase *list) if (con && list) { bFollowPathConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -1239,7 +1239,7 @@ static void followpath_flush_tars(bConstraint *con, ListBase *list, bool no_copy if (con && list) { bFollowPathConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -1248,7 +1248,7 @@ static void followpath_flush_tars(bConstraint *con, ListBase *list, bool no_copy static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bFollowPathConstraint *data = con->data; - + if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) { Curve *cu = ct->tar->data; float vec[4], dir[3], radius; @@ -1257,7 +1257,7 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra unit_m4(ct->matrix); /* note: when creating constraints that follow path, the curve gets the CU_PATH set now, - * currently for paths to work it needs to go through the bevlist/displist system (ton) + * currently for paths to work it needs to go through the bevlist/displist system (ton) */ #ifdef CYCLIC_DEPENDENCY_WORKAROUND @@ -1272,9 +1272,9 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra /* animated position along curve depending on time */ Nurb *nu = cu->nurb.first; curvetime = cu->ctime - data->offset; - + /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + * but this will only work if it actually is animated... * * we divide the curvetime calculated in the previous step by the length of the path, to get a time * factor, which then gets clamped to lie within 0.0 - 1.0 range @@ -1297,7 +1297,7 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra /* fixed position along curve */ curvetime = data->offset_fac; } - + if (where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) { /* quat_pt is quat or NULL*/ float totmat[4][4]; unit_m4(totmat); @@ -1306,7 +1306,7 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra #if 0 float x1, q[4]; vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag); - + normalize_v3(dir); q[0] = cosf(0.5 * vec[3]); x1 = sinf(0.5 * vec[3]); @@ -1327,9 +1327,9 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra mul_m4_m4m4(rmat, tmat, totmat); copy_m4_m4(totmat, rmat); } - + copy_v3_v3(totmat[3], vec); - + mul_m4_m4m4(ct->matrix, ct->tar->obmat, totmat); } } @@ -1341,27 +1341,27 @@ static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float obmat[4][4]; float size[3]; bFollowPathConstraint *data = con->data; - + /* get Object transform (loc/rot/size) to determine transformation from path */ /* TODO: this used to be local at one point, but is probably more useful as-is */ copy_m4_m4(obmat, cob->matrix); - + /* get scaling of object before applying constraint */ mat4_to_size(size, cob->matrix); - + /* apply targetmat - containing location on path, and rotation */ mul_m4_m4m4(cob->matrix, ct->matrix, obmat); - + /* un-apply scaling caused by path */ if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */ float obsize[3]; - + mat4_to_size(obsize, cob->matrix); if (obsize[0]) mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); @@ -1394,7 +1394,7 @@ static bConstraintTypeInfo CTI_FOLLOWPATH = { static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets)) { bLocLimitConstraint *data = con->data; - + if (data->flag & LIMIT_XMIN) { if (cob->matrix[3][0] < data->xmin) cob->matrix[3][0] = data->xmin; @@ -1412,7 +1412,7 @@ static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN cob->matrix[3][1] = data->ymax; } if (data->flag & LIMIT_ZMIN) { - if (cob->matrix[3][2] < data->zmin) + if (cob->matrix[3][2] < data->zmin) cob->matrix[3][2] = data->zmin; } if (data->flag & LIMIT_ZMAX) { @@ -1444,37 +1444,37 @@ static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN float loc[3]; float eul[3]; float size[3]; - + copy_v3_v3(loc, cob->matrix[3]); mat4_to_size(size, cob->matrix); mat4_to_eulO(eul, cob->rotOrder, cob->matrix); /* constraint data uses radians internally */ - + /* limiting of euler values... */ if (data->flag & LIMIT_XROT) { - if (eul[0] < data->xmin) + if (eul[0] < data->xmin) eul[0] = data->xmin; - + if (eul[0] > data->xmax) eul[0] = data->xmax; } if (data->flag & LIMIT_YROT) { if (eul[1] < data->ymin) eul[1] = data->ymin; - + if (eul[1] > data->ymax) eul[1] = data->ymax; } if (data->flag & LIMIT_ZROT) { if (eul[2] < data->zmin) eul[2] = data->zmin; - + if (eul[2] > data->zmax) eul[2] = data->zmax; } - + loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); } @@ -1500,40 +1500,40 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U { bSizeLimitConstraint *data = con->data; float obsize[3], size[3]; - + mat4_to_size(size, cob->matrix); mat4_to_size(obsize, cob->matrix); - + if (data->flag & LIMIT_XMIN) { - if (size[0] < data->xmin) + if (size[0] < data->xmin) size[0] = data->xmin; } if (data->flag & LIMIT_XMAX) { - if (size[0] > data->xmax) + if (size[0] > data->xmax) size[0] = data->xmax; } if (data->flag & LIMIT_YMIN) { - if (size[1] < data->ymin) + if (size[1] < data->ymin) size[1] = data->ymin; } if (data->flag & LIMIT_YMAX) { - if (size[1] > data->ymax) + if (size[1] > data->ymax) size[1] = data->ymax; } if (data->flag & LIMIT_ZMIN) { - if (size[2] < data->zmin) + if (size[2] < data->zmin) size[2] = data->zmin; } if (data->flag & LIMIT_ZMAX) { - if (size[2] > data->zmax) + if (size[2] > data->zmax) size[2] = data->zmax; } - - if (obsize[0]) + + if (obsize[0]) mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); - if (obsize[1]) + if (obsize[1]) mul_v3_fl(cob->matrix[1], size[1] / obsize[1]); - if (obsize[2]) + if (obsize[2]) mul_v3_fl(cob->matrix[2], size[2] / obsize[2]); } @@ -1557,14 +1557,14 @@ static bConstraintTypeInfo CTI_SIZELIMIT = { static void loclike_new_data(void *cdata) { bLocateLikeConstraint *data = (bLocateLikeConstraint *)cdata; - + data->flag = LOCLIKE_X | LOCLIKE_Y | LOCLIKE_Z; } static void loclike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bLocateLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1574,13 +1574,13 @@ static int loclike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1589,7 +1589,7 @@ static void loclike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1599,28 +1599,28 @@ static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float offset[3] = {0.0f, 0.0f, 0.0f}; - + if (data->flag & LOCLIKE_OFFSET) copy_v3_v3(offset, cob->matrix[3]); - + if (data->flag & LOCLIKE_X) { cob->matrix[3][0] = ct->matrix[3][0]; - + if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1; cob->matrix[3][0] += offset[0]; } if (data->flag & LOCLIKE_Y) { cob->matrix[3][1] = ct->matrix[3][1]; - + if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1; cob->matrix[3][1] += offset[1]; } if (data->flag & LOCLIKE_Z) { cob->matrix[3][2] = ct->matrix[3][2]; - + if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1; cob->matrix[3][2] += offset[2]; } @@ -1647,14 +1647,14 @@ static bConstraintTypeInfo CTI_LOCLIKE = { static void rotlike_new_data(void *cdata) { bRotateLikeConstraint *data = (bRotateLikeConstraint *)cdata; - + data->flag = ROTLIKE_X | ROTLIKE_Y | ROTLIKE_Z; } static void rotlike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bRotateLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1664,13 +1664,13 @@ static int rotlike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1679,7 +1679,7 @@ static void rotlike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1689,50 +1689,50 @@ static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float loc[3]; float eul[3], obeul[3]; float size[3]; - + copy_v3_v3(loc, cob->matrix[3]); mat4_to_size(size, cob->matrix); - + /* to allow compatible rotations, must get both rotations in the order of the owner... */ mat4_to_eulO(obeul, cob->rotOrder, cob->matrix); /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */ mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix); - + if ((data->flag & ROTLIKE_X) == 0) eul[0] = obeul[0]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]); - + if (data->flag & ROTLIKE_X_INVERT) eul[0] *= -1; } - + if ((data->flag & ROTLIKE_Y) == 0) eul[1] = obeul[1]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]); - + if (data->flag & ROTLIKE_Y_INVERT) eul[1] *= -1; } - + if ((data->flag & ROTLIKE_Z) == 0) eul[2] = obeul[2]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]); - + if (data->flag & ROTLIKE_Z_INVERT) eul[2] *= -1; } - + /* good to make eulers compatible again, since we don't know how much they were changed above */ compatible_eul(eul, obeul); loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); @@ -1759,14 +1759,14 @@ static bConstraintTypeInfo CTI_ROTLIKE = { static void sizelike_new_data(void *cdata) { bSizeLikeConstraint *data = (bSizeLikeConstraint *)cdata; - + data->flag = SIZELIKE_X | SIZELIKE_Y | SIZELIKE_Z; } static void sizelike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bSizeLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1776,13 +1776,13 @@ static int sizelike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1791,7 +1791,7 @@ static void sizelike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1801,13 +1801,13 @@ static void sizelike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float obsize[3], size[3]; - + mat4_to_size(size, ct->matrix); mat4_to_size(obsize, cob->matrix); - + if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) { if (data->flag & SIZELIKE_OFFSET) { size[0] += (obsize[0] - 1.0f); @@ -1855,7 +1855,7 @@ static bConstraintTypeInfo CTI_SIZELIKE = { static void translike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTransLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1865,13 +1865,13 @@ static int translike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTransLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1880,7 +1880,7 @@ static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTransLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1889,7 +1889,7 @@ static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void translike_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { /* just copy the entire transform matrix of the target */ copy_m4_m4(cob->matrix, ct->matrix); @@ -1930,12 +1930,12 @@ static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * float obsize[3]; mat4_to_size(obsize, cob->matrix); - + /* calculate normalizing scale factor for non-essential values */ total_scale = obsize[0] * obsize[1] * obsize[2]; if (total_scale != 0) fac = sqrtf(volume / total_scale); - + /* apply scaling factor to the channels not being kept */ switch (data->flag) { case SAMEVOL_X: @@ -1973,20 +1973,20 @@ static bConstraintTypeInfo CTI_SAMEVOL = { static void pycon_free(bConstraint *con) { bPythonConstraint *data = con->data; - + /* id-properties */ IDP_FreeProperty(data->prop); MEM_freeN(data->prop); - + /* multiple targets */ BLI_freelistN(&data->targets); -} +} static void pycon_copy(bConstraint *con, bConstraint *srccon) { bPythonConstraint *pycon = (bPythonConstraint *)con->data; bPythonConstraint *opycon = (bPythonConstraint *)srccon->data; - + pycon->prop = IDP_CopyProperty(opycon->prop); BLI_duplicatelist(&pycon->targets, &opycon->targets); } @@ -1994,7 +1994,7 @@ static void pycon_copy(bConstraint *con, bConstraint *srccon) static void pycon_new_data(void *cdata) { bPythonConstraint *data = (bPythonConstraint *)cdata; - + /* everything should be set correctly by calloc, except for the prop->type constant.*/ data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps"); data->prop->type = IDP_GROUP; @@ -2004,13 +2004,13 @@ static int pycon_get_tars(bConstraint *con, ListBase *list) { if (con && list) { bPythonConstraint *data = con->data; - + list->first = data->targets.first; list->last = data->targets.last; - + return data->tarnum; } - + return 0; } @@ -2018,11 +2018,11 @@ static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userd { bPythonConstraint *data = con->data; bConstraintTarget *ct; - + /* targets */ for (ct = data->targets.first; ct; ct = ct->next) func(con, (ID **)&ct->tar, false, userdata); - + /* script */ func(con, (ID **)&data->text, true, userdata); } @@ -2048,7 +2048,7 @@ static void pycon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTa * this matrix if it needs to do so */ constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); - + /* only execute target calculation if allowed */ #ifdef WITH_PYTHON if (G.f & G_SCRIPT_AUTOEXEC) @@ -2066,19 +2066,19 @@ static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targe return; #else bPythonConstraint *data = con->data; - + /* only evaluate in python if we're allowed to do so */ if ((G.f & G_SCRIPT_AUTOEXEC) == 0) return; - + /* currently removed, until I this can be re-implemented for multiple targets */ #if 0 - /* Firstly, run the 'driver' function which has direct access to the objects involved + /* Firstly, run the 'driver' function which has direct access to the objects involved * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems, * but it also allows certain 'clever' rigging hacks to work. */ BPY_pyconstraint_driver(data, cob, targets); #endif - + /* Now, run the actual 'constraint' function, which should only access the matrices */ BPY_pyconstraint_exec(data, cob, targets); #endif /* WITH_PYTHON */ @@ -2104,7 +2104,7 @@ static bConstraintTypeInfo CTI_PYTHON = { static void actcon_new_data(void *cdata) { bActionConstraint *data = (bActionConstraint *)cdata; - + /* set type to 20 (Loc X), as 0 is Rot X for backwards compatibility */ data->type = 20; } @@ -2112,10 +2112,10 @@ static void actcon_new_data(void *cdata) static void actcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bActionConstraint *data = con->data; - + /* target */ func(con, (ID **)&data->tar, false, userdata); - + /* action */ func(con, (ID **)&data->act, true, userdata); } @@ -2125,13 +2125,13 @@ static int actcon_get_tars(bConstraint *con, ListBase *list) if (con && list) { bActionConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2140,7 +2140,7 @@ static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bActionConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2149,18 +2149,18 @@ static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void actcon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bActionConstraint *data = con->data; - + if (VALID_CONS_TARGET(ct)) { float tempmat[4][4], vec[3]; float s, t; short axis; - + /* initialize return matrix */ unit_m4(ct->matrix); - + /* get the transform matrix of the target */ constraint_target_to_mat4(ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); - + /* determine where in transform range target is */ /* data->type is mapped as follows for backwards compatibility: * 00,01,02 - rotation (it used to be like this) @@ -2183,21 +2183,21 @@ static void actcon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintT copy_v3_v3(vec, tempmat[3]); axis = data->type - 20; } - + BLI_assert((unsigned int)axis < 3); /* Target defines the animation */ s = (vec[axis] - data->min) / (data->max - data->min); CLAMP(s, 0, 1); t = (s * (data->end - data->start)) + data->start; - + if (G.debug & G_DEBUG) printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL); - + /* Get the appropriate information from the action */ if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) { Object workob; - + /* evaluate using workob */ /* FIXME: we don't have any consistent standards on limiting effects on object... */ what_does_obaction(cob->ob, &workob, NULL, data->act, NULL, t); @@ -2208,21 +2208,21 @@ static void actcon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintT bPose pose = {{0}}; bPoseChannel *pchan, *tchan; - /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set + /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set * - we need to manually copy over a few settings, including rotation order, otherwise this fails */ pchan = cob->pchan; - + tchan = BKE_pose_channel_verify(&pose, pchan->name); tchan->rotmode = pchan->rotmode; - + /* evaluate action using workob (it will only set the PoseChannel in question) */ what_does_obaction(cob->ob, &workob, &pose, data->act, pchan->name, t); - + /* convert animation to matrices for use here */ BKE_pchan_calc_mat(tchan); copy_m4_m4(ct->matrix, tchan->chan_mat); - + /* Clean up */ BKE_pose_free_data(&pose); } @@ -2236,10 +2236,10 @@ static void actcon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintT static void actcon_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float temp[4][4]; - + /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix * function has already taken care of everything else. */ @@ -2268,15 +2268,15 @@ static bConstraintTypeInfo CTI_ACTION = { static void locktrack_new_data(void *cdata) { bLockTrackConstraint *data = (bLockTrackConstraint *)cdata; - + data->trackflag = TRACK_Y; data->lockflag = LOCK_Z; -} +} static void locktrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bLockTrackConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2286,13 +2286,13 @@ static int locktrack_get_tars(bConstraint *con, ListBase *list) if (con && list) { bLockTrackConstraint *data = con->data; bConstraintTarget *ct; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2301,7 +2301,7 @@ static void locktrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bLockTrackConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2311,14 +2311,14 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bLockTrackConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float vec[3], vec2[3]; float totmat[3][3]; float tmpmat[3][3]; float invmat[3][3]; float mdet; - + /* Vector object -> target */ sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]); switch (data->lockflag) { @@ -2331,10 +2331,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[0]); sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2345,10 +2345,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[0]); sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2360,10 +2360,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); negate_v3(totmat[1]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2375,10 +2375,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); negate_v3(totmat[2]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2400,7 +2400,7 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[1]); sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); @@ -2414,10 +2414,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[1]); sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2429,10 +2429,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); negate_v3(totmat[0]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2444,10 +2444,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); negate_v3(totmat[2]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2469,10 +2469,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[2]); sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2483,10 +2483,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[2]); sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2498,10 +2498,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); negate_v3(totmat[0]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2513,10 +2513,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); negate_v3(totmat[1]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2543,14 +2543,14 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t totmat[0][0] = tmpmat[0][0]; totmat[0][1] = tmpmat[0][1]; totmat[0][2] = tmpmat[0][2]; totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2]; totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2]; - + mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2], totmat[1][0], totmat[1][1], totmat[1][2], totmat[2][0], totmat[2][1], totmat[2][2]); if (mdet == 0) { unit_m3(totmat); } - + /* apply out transformaton to the object */ mul_m4_m3m4(cob->matrix, totmat, cob->matrix); } @@ -2576,14 +2576,14 @@ static bConstraintTypeInfo CTI_LOCKTRACK = { static void distlimit_new_data(void *cdata) { bDistLimitConstraint *data = (bDistLimitConstraint *)cdata; - + data->dist = 0.0f; } static void distlimit_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bDistLimitConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2593,13 +2593,13 @@ static int distlimit_get_tars(bConstraint *con, ListBase *list) if (con && list) { bDistLimitConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2608,7 +2608,7 @@ static void distlimit_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bDistLimitConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2618,19 +2618,19 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bDistLimitConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float dvec[3], dist, sfac = 1.0f; short clamp_surf = 0; - + /* calculate our current distance from the target */ dist = len_v3v3(cob->matrix[3], ct->matrix[3]); - + /* set distance (flag is only set when user demands it) */ if (data->dist == 0) data->dist = dist; - + /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */ if (data->mode == LIMITDIST_OUTSIDE) { /* if inside, then move to surface */ @@ -2657,7 +2657,7 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (dist >= (data->dist - data->soft)) { sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist); if (dist != 0.0f) sfac /= dist; - + clamp_surf = 1; } } @@ -2668,12 +2668,12 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (dist != 0.0f) sfac = data->dist / dist; } } - + /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */ if (clamp_surf) { /* simply interpolate along line formed by target -> owner */ interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac); - + /* copy new vector onto owner */ copy_v3_v3(cob->matrix[3], dvec); } @@ -2700,10 +2700,10 @@ static bConstraintTypeInfo CTI_DISTLIMIT = { static void stretchto_new_data(void *cdata) { bStretchToConstraint *data = (bStretchToConstraint *)cdata; - + data->volmode = 0; data->plane = 0; - data->orglength = 0.0; + data->orglength = 0.0; data->bulge = 1.0; data->bulge_max = 1.0f; data->bulge_min = 1.0f; @@ -2712,7 +2712,7 @@ static void stretchto_new_data(void *cdata) static void stretchto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bStretchToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2722,13 +2722,13 @@ static int stretchto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bStretchToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2737,7 +2737,7 @@ static void stretchto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bStretchToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2747,51 +2747,51 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bStretchToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float size[3], scale[3], vec[3], xx[3], zz[3], orth[3]; float totmat[3][3]; float dist, bulge; - + /* store scaling before destroying obmat */ mat4_to_size(size, cob->matrix); - + /* store X orientation before destroying obmat */ normalize_v3_v3(xx, cob->matrix[0]); - + /* store Z orientation before destroying obmat */ normalize_v3_v3(zz, cob->matrix[2]); - + /* XXX That makes the constraint buggy with asymmetrically scaled objects, see #29940. */ /* sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);*/ /* vec[0] /= size[0];*/ /* vec[1] /= size[1];*/ /* vec[2] /= size[2];*/ - + /* dist = normalize_v3(vec);*/ dist = len_v3v3(cob->matrix[3], ct->matrix[3]); /* Only Y constrained object axis scale should be used, to keep same length when scaling it. */ dist /= size[1]; - + /* data->orglength==0 occurs on first run, and after 'R' button is clicked */ if (data->orglength == 0) data->orglength = dist; scale[1] = dist / data->orglength; - + bulge = powf(data->orglength / dist, data->bulge); - + if (bulge > 1.0f) { if (data->flag & STRETCHTOCON_USE_BULGE_MAX) { float bulge_max = max_ff(data->bulge_max, 1.0f); float hard = min_ff(bulge, bulge_max); - + float range = bulge_max - 1.0f; float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f + range * atanf((bulge - 1.0f) * scale_fac) / (float)M_PI_2; - + bulge = interpf(soft, hard, data->bulge_smooth); } } @@ -2799,15 +2799,15 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (data->flag & STRETCHTOCON_USE_BULGE_MIN) { float bulge_min = CLAMPIS(data->bulge_min, 0.0f, 1.0f); float hard = max_ff(bulge, bulge_min); - + float range = 1.0f - bulge_min; float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f - range * atanf((1.0f - bulge) * scale_fac) / (float)M_PI_2; - + bulge = interpf(soft, hard, data->bulge_smooth); } } - + switch (data->volmode) { /* volume preserving scaling */ case VOLUME_XZ: @@ -2830,7 +2830,7 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t default: /* should not happen, but in case*/ return; } /* switch (data->volmode) */ - + /* Clear the object's rotation and scale */ cob->matrix[0][0] = size[0] * scale[0]; cob->matrix[0][1] = 0; @@ -2841,10 +2841,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t cob->matrix[2][0] = 0; cob->matrix[2][1] = 0; cob->matrix[2][2] = size[2] * scale[2]; - + sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]); normalize_v3(vec); - + /* new Y aligns object target connection*/ negate_v3_v3(totmat[1], vec); switch (data->plane) { @@ -2853,10 +2853,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old X! plane */ cross_v3_v3v3(orth, vec, xx); normalize_v3(orth); - + /* new Z*/ copy_v3_v3(totmat[2], orth); - + /* we decided to keep X plane*/ cross_v3_v3v3(xx, orth, vec); normalize_v3_v3(totmat[0], xx); @@ -2866,16 +2866,16 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old Z! plane */ cross_v3_v3v3(orth, vec, zz); normalize_v3(orth); - + /* new X */ negate_v3_v3(totmat[0], orth); - + /* we decided to keep Z */ cross_v3_v3v3(zz, orth, vec); normalize_v3_v3(totmat[2], zz); break; } /* switch (data->plane) */ - + mul_m4_m3m4(cob->matrix, totmat, cob->matrix); } } @@ -2900,7 +2900,7 @@ static bConstraintTypeInfo CTI_STRETCHTO = { static void minmax_new_data(void *cdata) { bMinMaxConstraint *data = (bMinMaxConstraint *)cdata; - + data->minmaxflag = TRACK_Z; data->offset = 0.0f; zero_v3(data->cache); @@ -2910,7 +2910,7 @@ static void minmax_new_data(void *cdata) static void minmax_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bMinMaxConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2920,13 +2920,13 @@ static int minmax_get_tars(bConstraint *con, ListBase *list) if (con && list) { bMinMaxConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2935,7 +2935,7 @@ static void minmax_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bMinMaxConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2945,16 +2945,16 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ { bMinMaxConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float obmat[4][4], imat[4][4], tarmat[4][4], tmat[4][4]; float val1, val2; int index; - + copy_m4_m4(obmat, cob->matrix); copy_m4_m4(tarmat, ct->matrix); - + if (data->flag & MINMAX_USEROT) { /* take rotation of target into account by doing the transaction in target's localspace */ invert_m4_m4(imat, tarmat); @@ -2962,7 +2962,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ copy_m4_m4(obmat, tmat); unit_m4(tarmat); } - + switch (data->minmaxflag) { case TRACK_Z: val1 = tarmat[3][2]; @@ -2997,7 +2997,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ default: return; } - + if (val1 > val2) { obmat[3][index] = tarmat[3][index] + data->offset; if (data->flag & MINMAX_STICKY) { @@ -3044,7 +3044,7 @@ static bConstraintTypeInfo CTI_MINMAX = { static void rbj_new_data(void *cdata) { bRigidBodyJointConstraint *data = (bRigidBodyJointConstraint *)cdata; - + /* removed code which set target of this constraint */ data->type = 1; } @@ -3052,7 +3052,7 @@ static void rbj_new_data(void *cdata) static void rbj_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bRigidBodyJointConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); func(con, (ID **)&data->child, false, userdata); @@ -3063,13 +3063,13 @@ static int rbj_get_tars(bConstraint *con, ListBase *list) if (con && list) { bRigidBodyJointConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -3078,7 +3078,7 @@ static void rbj_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bRigidBodyJointConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -3104,7 +3104,7 @@ static bConstraintTypeInfo CTI_RIGIDBODYJOINT = { static void clampto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bClampToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3114,13 +3114,13 @@ static int clampto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bClampToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -3129,7 +3129,7 @@ static void clampto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bClampToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -3156,33 +3156,33 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bClampToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target and it is a curve */ if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) { float obmat[4][4], ownLoc[3]; float curveMin[3], curveMax[3]; float targetMatrix[4][4]; - + copy_m4_m4(obmat, cob->matrix); copy_v3_v3(ownLoc, obmat[3]); - + unit_m4(targetMatrix); INIT_MINMAX(curveMin, curveMax); /* XXX - don't think this is good calling this here - campbell */ BKE_object_minmax(ct->tar, curveMin, curveMax, true); - + /* get targetmatrix */ if (data->tar->curve_cache && data->tar->curve_cache->path && data->tar->curve_cache->path->data) { float vec[4], dir[3], totmat[4][4]; float curvetime; short clamp_axis; - + /* find best position on curve */ /* 1. determine which axis to sample on? */ if (data->flag == CLAMPTO_AUTO) { float size[3]; sub_v3_v3v3(size, curveMax, curveMin); - + /* find axis along which the bounding box has the greatest * extent. Otherwise, default to the x-axis, as that is quite * frequently used. @@ -3194,15 +3194,15 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar else clamp_axis = CLAMPTO_X - 1; } - else + else clamp_axis = data->flag - 1; - + /* 2. determine position relative to curve on a 0-1 scale based on bounding box */ if (data->flag2 & CLAMPTO_CYCLIC) { /* cyclic, so offset within relative bounding box is used */ float len = (curveMax[clamp_axis] - curveMin[clamp_axis]); float offset; - + /* check to make sure len is not so close to zero that it'll cause errors */ if (IS_EQF(len, 0.0f) == false) { /* find bounding-box range where target is located */ @@ -3238,19 +3238,19 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar curvetime = 1.0f; else if (IS_EQF((curveMax[clamp_axis] - curveMin[clamp_axis]), 0.0f) == false) curvetime = (ownLoc[clamp_axis] - curveMin[clamp_axis]) / (curveMax[clamp_axis] - curveMin[clamp_axis]); - else + else curvetime = 0.0f; } - + /* 3. position on curve */ if (where_on_path(ct->tar, curvetime, vec, dir, NULL, NULL, NULL) ) { unit_m4(totmat); copy_v3_v3(totmat[3], vec); - + mul_m4_m4m4(targetMatrix, ct->tar->obmat, totmat); } } - + /* obtain final object position */ copy_v3_v3(cob->matrix[3], targetMatrix[3]); } @@ -3276,7 +3276,7 @@ static bConstraintTypeInfo CTI_CLAMPTO = { static void transform_new_data(void *cdata) { bTransformConstraint *data = (bTransformConstraint *)cdata; - + data->map[0] = 0; data->map[1] = 1; data->map[2] = 2; @@ -3285,7 +3285,7 @@ static void transform_new_data(void *cdata) static void transform_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTransformConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3295,13 +3295,13 @@ static int transform_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTransformConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3310,7 +3310,7 @@ static void transform_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTransformConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3320,21 +3320,21 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bTransformConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float *from_min, *from_max, *to_min, *to_max; float loc[3], eul[3], size[3]; float dvec[3], sval[3]; int i; - + /* obtain target effect */ switch (data->from) { case TRANS_SCALE: mat4_to_size(dvec, ct->matrix); - + if (is_negative_m4(ct->matrix)) { - /* Bugfix [#27886] + /* Bugfix [#27886] * We can't be sure which axis/axes are negative, though we know that something is negative. * Assume we don't care about negativity of separate axes. <--- This is a limitation that * riggers will have to live with for now. @@ -3356,12 +3356,12 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t from_max = data->from_max; break; } - + /* extract components of owner's matrix */ copy_v3_v3(loc, cob->matrix[3]); mat4_to_eulO(eul, cob->rotOrder, cob->matrix); mat4_to_size(size, cob->matrix); - + /* determine where in range current transforms lie */ if (data->expo) { for (i = 0; i < 3; i++) { @@ -3381,8 +3381,8 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sval[i] = 0.0f; } } - - + + /* apply transforms */ switch (data->to) { case TRANS_SCALE: @@ -3413,7 +3413,7 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t } break; } - + /* apply to matrix */ loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); } @@ -3439,7 +3439,7 @@ static bConstraintTypeInfo CTI_TRANSFORM = { static void shrinkwrap_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bShrinkwrapConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->target, false, userdata); } @@ -3457,12 +3457,12 @@ static int shrinkwrap_get_tars(bConstraint *con, ListBase *list) if (con && list) { bShrinkwrapConstraint *data = con->data; bConstraintTarget *ct; - + SINGLETARGETNS_GET_TARS(con, data->target, ct, list); - + return 1; } - + return 0; } @@ -3472,7 +3472,7 @@ static void shrinkwrap_flush_tars(bConstraint *con, ListBase *list, bool no_copy if (con && list) { bShrinkwrapConstraint *data = con->data; bConstraintTarget *ct = list->first; - + SINGLETARGETNS_FLUSH_TARS(con, data->target, ct, list, no_copy); } } @@ -3481,22 +3481,22 @@ static void shrinkwrap_flush_tars(bConstraint *con, ListBase *list, bool no_copy static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bShrinkwrapConstraint *scon = (bShrinkwrapConstraint *) con->data; - + if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_MESH) ) { bool fail = false; float co[3] = {0.0f, 0.0f, 0.0f}; - + SpaceTransform transform; /* TODO(sergey): use proper for_render flag here when known. */ DerivedMesh *target = object_get_derived_final(ct->tar, false); - + BVHTreeFromMesh treeData = {NULL}; - + unit_m4(ct->matrix); - + if (target != NULL) { BLI_space_transform_from_matrices(&transform, cob->matrix, ct->tar->obmat); - + switch (scon->shrinkType) { case MOD_SHRINKWRAP_NEAREST_SURFACE: case MOD_SHRINKWRAP_NEAREST_VERTEX: @@ -3511,16 +3511,16 @@ static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra bvhtree_from_mesh_get(&treeData, target, BVHTREE_FROM_VERTS, 2); else bvhtree_from_mesh_get(&treeData, target, BVHTREE_FROM_LOOPTRI, 2); - + if (treeData.tree == NULL) { fail = true; break; } - + BLI_space_transform_apply(&transform, co); - + BLI_bvhtree_find_nearest(treeData.tree, co, &nearest, treeData.nearest_callback, &treeData); - + dist = len_v3v3(co, nearest.co); if (dist != 0.0f) { interp_v3_v3v3(co, co, nearest.co, (dist - scon->dist) / dist); /* linear interpolation */ @@ -3547,7 +3547,7 @@ static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra no[scon->projAxis - OB_NEGX] = -1.0f; break; } - + /* transform normal into requested space */ /* Note that in this specific case, we need to keep scaling in non-parented 'local2world' object * case, because SpaceTransform also takes it into account when handling normals. See T42447. */ @@ -3578,14 +3578,14 @@ static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra break; } } - + free_bvhtree_from_mesh(&treeData); - + if (fail == true) { /* Don't move the point */ zero_v3(co); } - + /* co is in local object coordinates, change it to global and update target position */ mul_m4_v3(cob->matrix, co); copy_v3_v3(ct->matrix[3], co); @@ -3596,7 +3596,7 @@ static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra static void shrinkwrap_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { copy_v3_v3(cob->matrix[3], ct->matrix[3]); @@ -3623,14 +3623,14 @@ static bConstraintTypeInfo CTI_SHRINKWRAP = { static void damptrack_new_data(void *cdata) { bDampTrackConstraint *data = (bDampTrackConstraint *)cdata; - + data->trackflag = TRACK_Y; -} +} static void damptrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bDampTrackConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3640,13 +3640,13 @@ static int damptrack_get_tars(bConstraint *con, ListBase *list) if (con && list) { bDampTrackConstraint *data = con->data; bConstraintTarget *ct; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3655,7 +3655,7 @@ static void damptrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bDampTrackConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3671,60 +3671,88 @@ static void damptrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bDampTrackConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float obvec[3], tarvec[3], obloc[3]; float raxis[3], rangle; float rmat[3][3], tmat[4][4]; - - /* find the (unit) direction that the axis we're interested in currently points - * - mul_mat3_m4_v3() only takes the 3x3 (rotation+scaling) components of the 4x4 matrix + + /* find the (unit) direction that the axis we're interested in currently points + * - mul_mat3_m4_v3() only takes the 3x3 (rotation+scaling) components of the 4x4 matrix * - the normalization step at the end should take care of any unwanted scaling * left over in the 3x3 matrix we used */ copy_v3_v3(obvec, track_dir_vecs[data->trackflag]); mul_mat3_m4_v3(cob->matrix, obvec); - + if (normalize_v3(obvec) == 0.0f) { /* exceptional case - just use the track vector as appropriate */ copy_v3_v3(obvec, track_dir_vecs[data->trackflag]); } - + /* find the (unit) direction vector going from the owner to the target */ copy_v3_v3(obloc, cob->matrix[3]); sub_v3_v3v3(tarvec, ct->matrix[3], obloc); - + if (normalize_v3(tarvec) == 0.0f) { /* the target is sitting on the owner, so just make them use the same direction vectors */ /* FIXME: or would it be better to use the pure direction vector? */ copy_v3_v3(tarvec, obvec); //copy_v3_v3(tarvec, track_dir_vecs[data->trackflag]); } - + /* determine the axis-angle rotation, which represents the smallest possible rotation * between the two rotation vectors (i.e. the 'damping' referred to in the name) * - we take this to be the rotation around the normal axis/vector to the plane defined - * by the current and destination vectors, which will 'map' the current axis to the + * by the current and destination vectors, which will 'map' the current axis to the * destination vector * - the min/max wrappers around (obvec . tarvec) result (stored temporarily in rangle) * are used to ensure that the smallest angle is chosen */ - cross_v3_v3v3(raxis, obvec, tarvec); - + cross_v3_v3v3_hi_prec(raxis, obvec, tarvec); + rangle = dot_v3v3(obvec, tarvec); rangle = acosf(max_ff(-1.0f, min_ff(1.0f, rangle))); - - /* construct rotation matrix from the axis-angle rotation found above + + /* construct rotation matrix from the axis-angle rotation found above * - this call takes care to make sure that the axis provided is a unit vector first */ - axis_angle_to_mat3(rmat, raxis, rangle); - + float norm = normalize_v3(raxis); + + if (norm < FLT_EPSILON) { + /* if dot product is nonzero, while cross is zero, we have two opposite vectors! + * - this is an ambiguity in the math that needs to be resolved arbitrarily, + * or there will be a case where damped track strangely does nothing + * - to do that, rotate around a different local axis + */ + float tmpvec[3]; + + if (fabsf(rangle) < M_PI - 0.01f) { + return; + } + + rangle = M_PI; + copy_v3_v3(tmpvec, track_dir_vecs[(data->trackflag + 1) % 6]); + mul_mat3_m4_v3(cob->matrix, tmpvec); + cross_v3_v3v3(raxis, obvec, tmpvec); + + if (normalize_v3(raxis) == 0.0f) { + return; + } + } + else if (norm < 0.1f) { + /* near 0 and Pi arcsin has way better precision than arccos */ + rangle = (rangle > M_PI_2) ? M_PI - asinf(norm) : asinf(norm); + } + + axis_angle_normalized_to_mat3(rmat, raxis, rangle); + /* rotate the owner in the way defined by this rotation matrix, then reapply the location since * we may have destroyed that in the process of multiplying the matrix */ unit_m4(tmat); mul_m4_m3m4(tmat, rmat, cob->matrix); // m1, m3, m2 - + copy_m4_m4(cob->matrix, tmat); copy_v3_v3(cob->matrix[3], obloc); } @@ -3750,17 +3778,17 @@ static bConstraintTypeInfo CTI_DAMPTRACK = { static void splineik_free(bConstraint *con) { bSplineIKConstraint *data = con->data; - + /* binding array */ if (data->points) MEM_freeN(data->points); -} +} static void splineik_copy(bConstraint *con, bConstraint *srccon) { bSplineIKConstraint *src = srccon->data; bSplineIKConstraint *dst = con->data; - + /* copy the binding array */ dst->points = MEM_dupallocN(src->points); } @@ -3778,7 +3806,7 @@ static void splineik_new_data(void *cdata) static void splineik_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bSplineIKConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3788,13 +3816,13 @@ static int splineik_get_tars(bConstraint *con, ListBase *list) if (con && list) { bSplineIKConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -3803,7 +3831,7 @@ static void splineik_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bSplineIKConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -3846,7 +3874,7 @@ static bConstraintTypeInfo CTI_SPLINEIK = { static void pivotcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bPivotConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3856,13 +3884,13 @@ static int pivotcon_get_tars(bConstraint *con, ListBase *list) if (con && list) { bPivotConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3871,7 +3899,7 @@ static void pivotcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bPivotConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3881,20 +3909,20 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta { bPivotConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + float pivot[3], vec[3]; float rotMat[3][3]; /* pivot correction */ float axis[3], angle; - + /* firstly, check if pivoting should take place based on the current rotation */ if (data->rotAxis != PIVOTCON_AXIS_NONE) { float rot[3]; - + /* extract euler-rotation of target */ mat4_to_eulO(rot, cob->rotOrder, cob->matrix); - + /* check which range might be violated */ if (data->rotAxis < PIVOTCON_AXIS_X) { /* negative rotations (data->rotAxis = 0 -> 2) */ @@ -3907,7 +3935,7 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta return; } } - + /* find the pivot-point to use */ if (VALID_CONS_TARGET(ct)) { /* apply offset to target location */ @@ -3924,7 +3952,7 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta copy_v3_v3(pivot, data->offset); } } - + /* get rotation matrix representing the rotation of the owner */ /* TODO: perhaps we might want to include scaling based on the pivot too? */ copy_m3_m4(rotMat, cob->matrix); @@ -4485,7 +4513,7 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_from_type(int type) constraints_init_typeinfo(); CTI_INIT = 0; } - + /* only return for valid types */ if ((type >= CONSTRAINT_TYPE_NULL) && (type < NUM_CONSTRAINT_TYPES)) @@ -4496,10 +4524,10 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_from_type(int type) else { printf("No valid constraint type-info data available. Type = %i\n", type); } - + return NULL; -} - +} + /* This function should always be used to get the appropriate type-info, as it * has checks which prevent segfaults in some weird cases. */ @@ -4516,7 +4544,7 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_get(bConstraint *con) /* The functions here are called by various parts of Blender. Very few (should be none if possible) * constraint-specific code should occur here. */ - + /* ---------- Data Management ------- */ /* helper function for BKE_constraint_free_data() - unlinks references */ @@ -4534,17 +4562,17 @@ void BKE_constraint_free_data_ex(bConstraint *con, bool do_id_user) { if (con->data) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti) { /* perform any special freeing constraint may have */ if (cti->free_data) cti->free_data(con); - + /* unlink the referenced resources it uses */ if (do_id_user && cti->id_looper) cti->id_looper(con, con_unlink_refs_cb, NULL); } - + /* free constraint data now */ MEM_freeN(con->data); } @@ -4559,11 +4587,11 @@ void BKE_constraint_free_data(bConstraint *con) void BKE_constraints_free_ex(ListBase *list, bool do_id_user) { bConstraint *con; - + /* Free constraint data and also any extra data */ for (con = list->first; con; con = con->next) BKE_constraint_free_data_ex(con, do_id_user); - + /* Free the whole list */ BLI_freelistN(list); } @@ -4619,11 +4647,11 @@ static bConstraint *add_new_constraint_internal(const char *name, short type) if (cti) { /* initialize constraint data */ con->data = MEM_callocN(cti->size, cti->structName); - + /* only constraints that change any settings need this */ if (cti->new_data) cti->new_data(con->data); - + /* if no name is provided, use the type of the constraint as the name */ newName = (name && name[0]) ? name : DATA_(cti->name); } @@ -4632,10 +4660,10 @@ static bConstraint *add_new_constraint_internal(const char *name, short type) /* NOTE: any constraint type that gets here really shouldn't get added... */ newName = (name && name[0]) ? name : DATA_("Const"); } - + /* copy the name */ BLI_strncpy(con->name, newName, sizeof(con->name)); - + /* return the new constraint */ return con; } @@ -4645,27 +4673,27 @@ static bConstraint *add_new_constraint(Object *ob, bPoseChannel *pchan, const ch { bConstraint *con; ListBase *list; - + /* add the constraint */ con = add_new_constraint_internal(name, type); - + /* find the constraint stack - bone or object? */ list = (pchan) ? (&pchan->constraints) : (&ob->constraints); - + if (list) { /* add new constraint to end of list of constraints before ensuring that it has a unique name * (otherwise unique-naming code will fail, since it assumes element exists in list) */ BLI_addtail(list, con); BKE_constraint_unique_name(con, list); - + /* if the target list is a list on some PoseChannel belonging to a proxy-protected * Armature layer, we must tag newly added constraints with a flag which allows them * to persist after proxy syncing has been done */ if (BKE_constraints_proxylocked_owner(ob, pchan)) con->flag |= CONSTRAINT_PROXY_LOCAL; - + /* make this constraint the active one */ BKE_constraints_active_set(list, con); } @@ -4684,7 +4712,7 @@ static bConstraint *add_new_constraint(Object *ob, bPoseChannel *pchan, const ch break; } } - + return con; } @@ -4695,7 +4723,7 @@ bConstraint *BKE_constraint_add_for_pose(Object *ob, bPoseChannel *pchan, const { if (pchan == NULL) return NULL; - + return add_new_constraint(ob, pchan, name, type); } @@ -4711,10 +4739,10 @@ bConstraint *BKE_constraint_add_for_object(Object *ob, const char *name, short t void BKE_constraints_id_loop(ListBase *conlist, ConstraintIDFunc func, void *userdata) { bConstraint *con; - + for (con = conlist->first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti) { if (cti->id_looper) cti->id_looper(con, func, userdata); @@ -4790,7 +4818,7 @@ bConstraint *BKE_constraints_find_name(ListBase *list, const char *name) bConstraint *BKE_constraints_active_get(ListBase *list) { bConstraint *con; - + /* search for the first constraint with the 'active' flag set */ if (list) { for (con = list->first; con; con = con->next) { @@ -4798,7 +4826,7 @@ bConstraint *BKE_constraints_active_get(ListBase *list) return con; } } - + /* no active constraint found */ return NULL; } @@ -4807,12 +4835,12 @@ bConstraint *BKE_constraints_active_get(ListBase *list) void BKE_constraints_active_set(ListBase *list, bConstraint *con) { bConstraint *c; - + if (list) { for (c = list->first; c; c = c->next) { - if (c == con) + if (c == con) c->flag |= CONSTRAINT_ACTIVE; - else + else c->flag &= ~CONSTRAINT_ACTIVE; } } @@ -4824,11 +4852,11 @@ void BKE_constraints_active_set(ListBase *list, bConstraint *con) void BKE_constraints_proxylocal_extract(ListBase *dst, ListBase *src) { bConstraint *con, *next; - + /* for each tagged constraint, remove from src and move to dst */ for (con = src->first; con; con = next) { next = con->next; - + /* check if tagged */ if (con->flag & CONSTRAINT_PROXY_LOCAL) { BLI_remlink(src, con); @@ -4844,7 +4872,7 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) if (ob && ob->proxy) { if (ob->pose && pchan) { bArmature *arm = ob->data; - + /* On bone-level, check if bone is on proxy-protected layer */ if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected)) return true; @@ -4854,7 +4882,7 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) return true; } } - + return false; } @@ -4873,7 +4901,7 @@ void BKE_constraint_target_matrix_get(Scene *scene, bConstraint *con, int index, ListBase targets = {NULL, NULL}; bConstraintOb *cob; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { /* make 'constraint-ob' */ cob = MEM_callocN(sizeof(bConstraintOb), "tempConstraintOb"); @@ -4909,19 +4937,19 @@ void BKE_constraint_target_matrix_get(Scene *scene, bConstraint *con, int index, break; } } - + /* get targets - we only need the first one though (and there should only be one) */ cti->get_constraint_targets(con, &targets); - + /* only calculate the target matrix on the first target */ ct = (bConstraintTarget *)BLI_findlink(&targets, index); - + if (ct) { if (cti->get_target_matrix) cti->get_target_matrix(con, cob, ct, ctime); copy_m4_m4(mat, ct->matrix); } - + /* free targets + 'constraint-ob' */ if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); @@ -4937,17 +4965,17 @@ void BKE_constraint_target_matrix_get(Scene *scene, bConstraint *con, int index, void BKE_constraint_targets_for_solving_get(bConstraint *con, bConstraintOb *cob, ListBase *targets, float ctime) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti && cti->get_constraint_targets) { bConstraintTarget *ct; - - /* get targets + + /* get targets * - constraints should use ct->matrix, not directly accessing values - * - ct->matrix members have not yet been calculated here! + * - ct->matrix members have not yet been calculated here! */ cti->get_constraint_targets(con, targets); - - /* set matrices + + /* set matrices * - calculate if possible, otherwise just initialize as identity matrix */ if (cti->get_target_matrix) { @@ -4960,7 +4988,7 @@ void BKE_constraint_targets_for_solving_get(bConstraint *con, bConstraintOb *cob } } } - + /* ---------- Evaluation ----------- */ /* This function is called whenever constraints need to be evaluated. Currently, all @@ -4978,12 +5006,12 @@ void BKE_constraints_solve(ListBase *conlist, bConstraintOb *cob, float ctime) /* check that there is a valid constraint object to evaluate */ if (cob == NULL) return; - + /* loop over available constraints, solving and blending them */ for (con = conlist->first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; - + /* these we can skip completely (invalid constraints...) */ if (cti == NULL) continue; if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) continue; @@ -4991,37 +5019,37 @@ void BKE_constraints_solve(ListBase *conlist, bConstraintOb *cob, float ctime) if (cti->evaluate_constraint == NULL) continue; /* influence == 0 should be ignored */ if (con->enforce == 0.0f) continue; - + /* influence of constraint * - value should have been set from animation data already */ enf = con->enforce; - + /* make copy of worldspace matrix pre-constraint for use with blending later */ copy_m4_m4(oldmat, cob->matrix); - + /* move owner matrix into right space */ BKE_constraint_mat_convertspace(cob->ob, cob->pchan, cob->matrix, CONSTRAINT_SPACE_WORLD, con->ownspace, false); - + /* prepare targets for constraint solving */ BKE_constraint_targets_for_solving_get(con, cob, &targets, ctime); - + /* Solve the constraint and put result in cob->matrix */ cti->evaluate_constraint(con, cob, &targets); - - /* clear targets after use + + /* clear targets after use * - this should free temp targets but no data should be copied back * as constraints may have done some nasty things to it... */ if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 1); } - + /* move owner back into worldspace for next constraint/other business */ - if ((con->flag & CONSTRAINT_SPACEONCE) == 0) + if ((con->flag & CONSTRAINT_SPACEONCE) == 0) BKE_constraint_mat_convertspace(cob->ob, cob->pchan, cob->matrix, con->ownspace, CONSTRAINT_SPACE_WORLD, false); - - /* Interpolate the enforcement, to blend result of constraint into final owner transform + + /* Interpolate the enforcement, to blend result of constraint into final owner transform * - all this happens in worldspace to prevent any weirdness creeping in ([#26014] and [#25725]), * since some constraints may not convert the solution back to the input space before blending * but all are guaranteed to end up in good "worldspace" result diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index 4c01bfd35f21..517d2ebe10e6 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -73,7 +73,7 @@ struct bContext { struct bContextStore *store; const char *operator_poll_msg; /* reason for poll failing */ } wm; - + /* data context */ struct { struct Main *main; @@ -83,7 +83,7 @@ struct bContext { int py_init; /* true if python is initialized */ void *py_context; } data; - + /* data evaluation */ #if 0 struct { @@ -97,7 +97,7 @@ struct bContext { bContext *CTX_create(void) { bContext *C; - + C = MEM_callocN(sizeof(bContext), "bContext"); return C; @@ -413,7 +413,7 @@ PointerRNA CTX_data_pointer_get_type(const bContext *C, const char *member, Stru __func__, member, RNA_struct_identifier(ptr.type), RNA_struct_identifier(type)); } } - + return PointerRNA_NULL; } @@ -454,13 +454,13 @@ int CTX_data_get(const bContext *C, const char *member, PointerRNA *r_ptr, ListB static void data_dir_add(ListBase *lb, const char *member, const bool use_all) { LinkData *link; - + if ((use_all == false) && STREQ(member, "scene")) /* exception */ return; if (BLI_findstring(lb, member, offsetof(LinkData, data))) return; - + link = MEM_callocN(sizeof(LinkData), "LinkData"); link->data = (void *)member; BLI_addtail(lb, link); @@ -1153,4 +1153,3 @@ int CTX_data_editable_gpencil_strokes(const bContext *C, ListBase *list) { return ctx_data_collection_get(C, "editable_gpencil_strokes", list); } - diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index d89e7a126449..792ba08358e3 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -632,6 +632,107 @@ void BKE_nurb_minmax(Nurb *nu, bool use_radius, float min[3], float max[3]) } } +float BKE_nurb_calc_length(const Nurb *nu, int resolution) +{ + BezTriple *bezt, *prevbezt; + BPoint *bp, *prevbp; + int a, b; + float length = 0.0f; + int resolu = resolution ? resolution : nu->resolu; + int pntsu = nu->pntsu; + float *points, *pntsit, *prevpntsit; + + if (nu->type == CU_POLY) { + a = nu->pntsu - 1; + bp = nu->bp; + if (nu->flagu & CU_NURB_CYCLIC) { + ++a; + prevbp = nu->bp + (nu->pntsu - 1); + } + else { + prevbp = bp; + bp++; + } + + while (a--) { + length += len_v3v3(prevbp->vec, bp->vec); + prevbp = bp; + ++bp; + } + } + else if (nu->type == CU_BEZIER) { + points = MEM_mallocN(sizeof(float[3]) * (resolu + 1), "getLength_bezier"); + a = nu->pntsu - 1; + bezt = nu->bezt; + if (nu->flagu & CU_NURB_CYCLIC) { + ++a; + prevbezt = nu->bezt + (nu->pntsu - 1); + } + else { + prevbezt = bezt; + ++bezt; + } + + while (a--) { + if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) { + length += len_v3v3(prevbezt->vec[1], bezt->vec[1]); + } + else { + for (int j = 0; j < 3; j++) { + BKE_curve_forward_diff_bezier( + prevbezt->vec[1][j], prevbezt->vec[2][j], + bezt->vec[0][j], bezt->vec[1][j], + points + j, resolu, 3 * sizeof(float)); + } + + prevpntsit = pntsit = points; + b = resolu; + while (b--) { + pntsit += 3; + length += len_v3v3(prevpntsit, pntsit); + prevpntsit = pntsit; + } + } + prevbezt = bezt; + ++bezt; + } + + MEM_freeN(points); + } + else if (nu->type == CU_NURBS) { + if (nu->pntsv == 1) { + /* important to zero for BKE_nurb_makeCurve. */ + points = MEM_callocN(sizeof(float[3]) * pntsu * resolu, "getLength_nurbs"); + + BKE_nurb_makeCurve( + nu, points, + NULL, NULL, NULL, + resolu, sizeof(float[3])); + + if (nu->flagu & CU_NURB_CYCLIC) { + b = pntsu * resolu + 1; + prevpntsit = points + 3 * (pntsu * resolu - 1); + pntsit = points; + } + else { + b = (pntsu - 1) * resolu; + prevpntsit = points; + pntsit = points + 3; + } + + while (--b) { + length += len_v3v3(prevpntsit, pntsit); + prevpntsit = pntsit; + pntsit += 3; + } + + MEM_freeN(points); + } + } + + return length; +} + /* be sure to call makeknots after this */ void BKE_nurb_points_add(Nurb *nu, int number) { @@ -1026,7 +1127,7 @@ static void basisNurb(float t, short order, int pnts, float *knots, float *basis /* this is for float inaccuracy */ if (t < knots[0]) t = knots[0]; - else if (t > knots[opp2]) + else if (t > knots[opp2]) t = knots[opp2]; /* this part is order '1' */ @@ -1080,9 +1181,10 @@ static void basisNurb(float t, short order, int pnts, float *knots, float *basis } } - -void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv) -/* coord_array has to be (3 * 4 * resolu * resolv) in size, and zero-ed */ +/** + * \param coord_array: has to be (3 * 4 * resolu * resolv) in size, and zero-ed. + */ +void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv) { BPoint *bp; float *basisu, *basis, *basisv, *sum, *fp, *in; @@ -1258,8 +1360,9 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu, * \param tilt_array set when non-NULL * \param radius_array set when non-NULL */ -void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, - int resolu, int stride) +void BKE_nurb_makeCurve( + const Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, + int resolu, int stride) { const float eps = 1e-6f; BPoint *bp; @@ -2135,7 +2238,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float * if (tilt_array == NULL || nu->tilt_interp != nu->radius_interp) { key_curve_position_weights(fac, t, nu->radius_interp); } - *radius_array = + *radius_array = t[0] * pprev->radius + t[1] * prevbezt->radius + t[2] * bezt->radius + t[3] * next->radius; } @@ -2145,7 +2248,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float * if (weight_array) { /* basic interpolation for now, could copy tilt interp too */ - *weight_array = + *weight_array = prevbezt->weight + (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac); @@ -2680,10 +2783,10 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) } for (; nu; nu = nu->next) { - + if (nu->hide && is_editmode) continue; - + /* check if we will calculate tilt data */ do_tilt = CU_DO_TILT(cu, nu); do_radius = CU_DO_RADIUS(cu, nu); /* normal display uses the radius, better just to calculate them */ @@ -5157,7 +5260,7 @@ void BKE_curve_material_index_clear(Curve *cu) } } -int BKE_curve_material_index_validate(Curve *cu) +bool BKE_curve_material_index_validate(Curve *cu) { const int curvetype = BKE_curve_type_get(cu); bool is_valid = true; diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index 023cf76796d1..28280c45922b 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -544,7 +544,7 @@ static void layerSwap_mdisps(void *data, const int *ci) for (S = 0; S < corners; S++) memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float)); - + MEM_freeN(s->disps); s->disps = d; } @@ -649,7 +649,7 @@ static void layerCopy_grid_paint_mask(const void *source, void *dest, int count) d[i].data = NULL; d[i].level = 0; } - + } } @@ -760,7 +760,7 @@ static void layerDoMinMax_mloopcol(const void *data, void *vmin, void *vmax) if (m->g < min->g) min->g = m->g; if (m->b < min->b) min->b = m->b; if (m->a < min->a) min->a = m->a; - + if (m->r > max->r) max->r = m->r; if (m->g > max->g) max->g = m->g; if (m->b > max->b) max->b = m->b; @@ -1023,7 +1023,7 @@ static void layerInterp_mcol( const float *sub_weight; if (count <= 0) return; - + sub_weight = sub_weights; for (i = 0; i < count; ++i) { float weight = weights ? weights[i] : 1; @@ -1051,7 +1051,7 @@ static void layerInterp_mcol( /* delay writing to the destination incase dest is in sources */ for (j = 0; j < 4; ++j) { - + /* Subdivide smooth or fractal can cause problems without clamping * although weights should also not cause this situation */ mc[j].a = round_fl_to_uchar_clamp(col[j].a); @@ -1096,7 +1096,7 @@ static void layerInterp_bweight( float f; float **in = (float **)sources; int i; - + if (count <= 0) return; f = 0.0f; @@ -1147,7 +1147,7 @@ static void layerDefault_mvert_skin(void *data, int count) { MVertSkin *vs = data; int i; - + for (i = 0; i < count; i++) { copy_v3_fl(vs[i].radius, 0.25f); vs[i].flag = 0; @@ -1234,18 +1234,18 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, layerMaxNum_tface}, /* 16: CD_MLOOPUV */ {sizeof(MLoopUV), "MLoopUV", 1, N_("UVMap"), NULL, NULL, layerInterp_mloopuv, NULL, NULL, - layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, + layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv, NULL, NULL, NULL, layerMaxNum_tface}, /* 17: CD_MLOOPCOL */ {sizeof(MLoopCol), "MLoopCol", 1, N_("Col"), NULL, NULL, layerInterp_mloopcol, NULL, - layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, + layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol, NULL, NULL, NULL, layerMaxNum_mloopcol}, /* 18: CD_TANGENT */ {sizeof(float) * 4 * 4, "", 0, N_("Tangent"), NULL, NULL, NULL, NULL, NULL}, /* 19: CD_MDISPS */ {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps, layerFree_mdisps, NULL, layerSwap_mdisps, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps}, /* 20: CD_PREVIEW_MCOL */ {sizeof(MCol) * 4, "MCol", 4, N_("PreviewCol"), NULL, NULL, layerInterp_mcol, @@ -1488,10 +1488,10 @@ bool CustomData_merge(const struct CustomData *source, struct CustomData *dest, else { newlayer = customData_add_layer__internal(dest, type, alloctype, data, totelem, layer->name); } - + if (newlayer) { newlayer->uid = layer->uid; - + newlayer->active = lastactive; newlayer->active_rnd = lastrender; newlayer->active_clone = lastclone; @@ -1569,7 +1569,7 @@ void CustomData_free(CustomData *data, int totelem) if (data->layers) MEM_freeN(data->layers); - + CustomData_external_free(data); CustomData_reset(data); } @@ -1872,7 +1872,7 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ return NULL; } } - + data->totlayer++; /* keep layers ordered by type */ @@ -1902,7 +1902,7 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ data->layers[index].active_clone = 0; data->layers[index].active_mask = 0; } - + customData_update_offsets(data); return &data->layers[index]; @@ -1913,7 +1913,7 @@ void *CustomData_add_layer(CustomData *data, int type, int alloctype, { CustomDataLayer *layer; const LayerTypeInfo *typeInfo = layerType_getInfo(type); - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, typeInfo->defaultname); CustomData_update_typemap(data); @@ -1929,7 +1929,7 @@ void *CustomData_add_layer_named(CustomData *data, int type, int alloctype, void *layerdata, int totelem, const char *name) { CustomDataLayer *layer; - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, name); CustomData_update_typemap(data); @@ -2014,7 +2014,7 @@ int CustomData_number_of_layers(const CustomData *data, int type) for (i = 0; i < data->totlayer; i++) if (data->layers[i].type == type) number++; - + return number; } @@ -2233,7 +2233,7 @@ void CustomData_copy_data(const CustomData *source, CustomData *dest, /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { CustomData_copy_data_layer(source, dest, src_i, dest_i, source_index, dest_index, count); - + /* if there are multiple source & dest layers of the same type, * we don't want to copy all source layers to the same dest, so * increment dest_i @@ -2371,7 +2371,7 @@ void CustomData_swap(struct CustomData *data, const int index_a, const int index void *CustomData_get(const CustomData *data, int index, int type) { int layer_index; - + BLI_assert(index >= 0); /* get the layer index of the active layer of type */ @@ -2450,9 +2450,9 @@ bool CustomData_set_layer_name(const CustomData *data, int type, int n, const ch if ((layer_index == -1) || !name) return false; - + BLI_strncpy(data->layers[layer_index].name, name, sizeof(data->layers[layer_index].name)); - + return true; } @@ -2852,7 +2852,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest, if (*dest_block) memset(*dest_block, 0, dest->totsize); } - + /* copies a layer at a time */ dest_i = 0; for (src_i = 0; src_i < source->totlayer; ++src_i) { @@ -2894,7 +2894,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest, void *CustomData_bmesh_get(const CustomData *data, void *block, int type) { int layer_index; - + /* get the layer index of the first layer of type */ layer_index = CustomData_get_active_layer_index(data, type); if (layer_index == -1) return NULL; @@ -2905,7 +2905,7 @@ void *CustomData_bmesh_get(const CustomData *data, void *block, int type) void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n) { int layer_index; - + /* get the layer index of the first layer of type */ layer_index = CustomData_get_layer_index(data, type); if (layer_index == -1) return NULL; @@ -2924,13 +2924,13 @@ void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n) bool CustomData_layer_has_math(const struct CustomData *data, int layer_n) { const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layer_n].type); - - if (typeInfo->equal && typeInfo->add && typeInfo->multiply && + + if (typeInfo->equal && typeInfo->add && typeInfo->multiply && typeInfo->initminmax && typeInfo->dominmax) { return true; } - + return false; } @@ -3203,7 +3203,7 @@ void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest, if (*dest_block == NULL) CustomData_bmesh_alloc_block(dest, dest_block); - + /* copies a layer at a time */ dest_i = 0; for (src_i = 0; src_i < source->totlayer; ++src_i) { @@ -3405,7 +3405,7 @@ static bool cd_layer_find_dupe(CustomData *data, const char *name, int type, int for (i = 0; i < data->totlayer; i++) { if (i != index) { CustomDataLayer *layer = &data->layers[i]; - + if (CustomData_is_property_layer(type)) { if (CustomData_is_property_layer(layer->type) && STREQ(layer->name, name)) { return true; @@ -3418,7 +3418,7 @@ static bool cd_layer_find_dupe(CustomData *data, const char *name, int type, int } } } - + return false; } @@ -3429,7 +3429,7 @@ static bool customdata_unique_check(void *arg, const char *name) } void CustomData_set_layer_unique_name(CustomData *data, int index) -{ +{ CustomDataLayer *nlayer = &data->layers[index]; const LayerTypeInfo *typeInfo = layerType_getInfo(nlayer->type); @@ -3535,7 +3535,7 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int if (!external) return; - + for (i = 0; i < data->totlayer; i++) { layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c index d17c9ef5cc66..3fee2ef60211 100644 --- a/source/blender/blenkernel/intern/customdata_file.c +++ b/source/blender/blenkernel/intern/customdata_file.c @@ -115,7 +115,7 @@ static int cdf_data_type_size(int datatype) { if (datatype == CDF_DATA_FLOAT) return sizeof(float); - + return 0; } #endif @@ -156,7 +156,7 @@ static int cdf_read_header(CDataFile *cdf) if (!fread(header, sizeof(CDataFileHeader), 1, cdf->readf)) return 0; - + if (memcmp(header->ID, "BCDF", sizeof(header->ID)) != 0) return 0; if (header->version > CDF_VERSION) @@ -179,7 +179,7 @@ static int cdf_read_header(CDataFile *cdf) if (fseek(f, offset, SEEK_SET) != 0) return 0; - + if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; if (!fread(image, sizeof(CDataFileImageHeader), 1, f)) @@ -258,7 +258,7 @@ static int cdf_write_header(CDataFile *cdf) if (!fwrite(header, sizeof(CDataFileHeader), 1, f)) return 0; - + if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; if (!fwrite(image, sizeof(CDataFileImageHeader), 1, f)) @@ -287,7 +287,7 @@ bool cdf_read_open(CDataFile *cdf, const char *filename) f = BLI_fopen(filename, "rb"); if (!f) return 0; - + cdf->readf = f; if (!cdf_read_header(cdf)) { @@ -352,7 +352,7 @@ bool cdf_write_open(CDataFile *cdf, const char *filename) f = BLI_fopen(filename, "wb"); if (!f) return 0; - + cdf->writef = f; /* fill header */ @@ -424,7 +424,7 @@ CDataFileLayer *cdf_layer_find(CDataFile *cdf, int type, const char *name) if (layer->type == type && STREQ(layer->name, name)) return layer; } - + return NULL; } @@ -449,4 +449,3 @@ CDataFileLayer *cdf_layer_add(CDataFile *cdf, int type, const char *name, size_t return layer; } - diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c index 78f564e5e5e0..734aac8a1f76 100644 --- a/source/blender/blenkernel/intern/depsgraph.c +++ b/source/blender/blenkernel/intern/depsgraph.c @@ -27,7 +27,7 @@ * \ingroup bke */ - + #include #include #include @@ -115,7 +115,7 @@ void DAG_exit(void) DEG_free_node_types(); } -/* Queue and stack operations for dag traversal +/* Queue and stack operations for dag traversal * * the queue store a list of freenodes to avoid successive alloc/dealloc */ @@ -125,7 +125,7 @@ DagNodeQueue *queue_create(int slots) DagNodeQueue *queue; DagNodeQueueElem *elem; int i; - + queue = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue"); queue->freenodes = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue"); queue->count = 0; @@ -135,7 +135,7 @@ DagNodeQueue *queue_create(int slots) elem->node = NULL; elem->next = NULL; queue->freenodes->first = queue->freenodes->last = elem; - + for (i = 1; i < slots; i++) { elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem4"); elem->node = NULL; @@ -150,13 +150,13 @@ DagNodeQueue *queue_create(int slots) void queue_raz(DagNodeQueue *queue) { DagNodeQueueElem *elem; - + elem = queue->first; if (queue->freenodes->last) queue->freenodes->last->next = elem; else queue->freenodes->first = queue->freenodes->last = elem; - + elem->node = NULL; queue->freenodes->count++; while (elem->next) { @@ -172,21 +172,21 @@ void queue_delete(DagNodeQueue *queue) { DagNodeQueueElem *elem; DagNodeQueueElem *temp; - + elem = queue->first; while (elem) { temp = elem; elem = elem->next; MEM_freeN(temp); } - + elem = queue->freenodes->first; while (elem) { temp = elem; elem = elem->next; MEM_freeN(temp); } - + MEM_freeN(queue->freenodes); MEM_freeN(queue); } @@ -226,7 +226,7 @@ void push_queue(DagNodeQueue *queue, DagNode *node) queue->freenodes->last = elem; } queue->freenodes->count = DAGQUEUEALLOC; - + elem = queue->freenodes->first; queue->freenodes->first = elem->next; } @@ -271,7 +271,7 @@ void push_stack(DagNodeQueue *queue, DagNode *node) queue->freenodes->last = elem; } queue->freenodes->count = DAGQUEUEALLOC; - + elem = queue->freenodes->first; queue->freenodes->first = elem->next; } @@ -334,25 +334,25 @@ static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node { FCurve *fcu; DagNode *node1; - + for (fcu = adt->drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; int isdata_fcu = (isdata) || (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")); - + /* loop over variables to get the target relationships */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* only used targets */ - DRIVER_TARGETS_USED_LOOPER(dvar) + DRIVER_TARGETS_USED_LOOPER(dvar) { if (dtar->id) { /* FIXME: other data types need to be added here so that they can work! */ if (GS(dtar->id->name) == ID_OB) { Object *ob = (Object *)dtar->id; - + /* normal channel-drives-channel */ node1 = dag_get_node(dag, dtar->id); - + /* check if bone... */ if ((ob->type == OB_ARMATURE) && ( ((dtar->rna_path) && strstr(dtar->rna_path, "pose.bones[")) || @@ -386,7 +386,7 @@ static void dag_add_shader_nodetree_driver_relations(DagForest *dag, DagNode *no if (ntree->adt) { dag_add_driver_relation(ntree->adt, dag, node, 1); } - + /* nodetree's nodes... */ for (n = ntree->nodes.first; n; n = n->next) { if (n->id) { @@ -403,7 +403,7 @@ static void dag_add_shader_nodetree_driver_relations(DagForest *dag, DagNode *no /* recursive handling for material drivers */ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma) { - /* Prevent infinite recursion by checking (and tagging the material) as having been visited + /* Prevent infinite recursion by checking (and tagging the material) as having been visited * already (see build_dag()). This assumes ma->id.tag & LIB_TAG_DOIT isn't set by anything else * in the meantime... [#32017] */ @@ -411,7 +411,7 @@ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Mat return; ma->id.tag |= LIB_TAG_DOIT; - + /* material itself */ if (ma->adt) dag_add_driver_relation(ma->adt, dag, node, 1); @@ -430,7 +430,7 @@ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Mat /* recursive handling for lamp drivers */ static void dag_add_lamp_driver_relations(DagForest *dag, DagNode *node, Lamp *la) { - /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited + /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited * already (see build_dag()). This assumes la->id.tag & LIB_TAG_DOIT isn't set by anything else * in the meantime... [#32017] */ @@ -438,7 +438,7 @@ static void dag_add_lamp_driver_relations(DagForest *dag, DagNode *node, Lamp *l return; la->id.tag |= LIB_TAG_DOIT; - + /* lamp itself */ if (la->adt) dag_add_driver_relation(la->adt, dag, node, 1); @@ -554,9 +554,9 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O Key *key; ParticleSystem *psys; int addtoroot = 1; - + node = dag_get_node(dag, ob); - + if ((ob->data) && (mask & DAG_RL_DATA)) { node2 = dag_get_node(dag, ob->data); dag_add_relation(dag, node, node2, DAG_RL_DATA, "Object-Data Relation"); @@ -565,11 +565,11 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } /* also build a custom data mask for dependencies that need certain layers */ - + if (ob->type == OB_ARMATURE) { if (ob->pose) { bPoseChannel *pchan; - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); @@ -585,12 +585,12 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } else if (cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar && ct->tar != ob) { // fprintf(stderr, "armature %s target :%s\n", ob->id.name, target->id.name); node3 = dag_get_node(dag, ct->tar); - + if (ct->subtarget[0]) { dag_add_relation(dag, node3, node, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, cti->name); if (ct->tar->type == OB_MESH) @@ -608,16 +608,16 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } } } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } - + } } } } - + /* driver dependencies, nla modifiers */ #if 0 // XXX old animation system if (ob->nlastrips.first) { @@ -638,7 +638,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O #endif // XXX old animation system if (ob->adt) dag_add_driver_relation(ob->adt, dag, node, (ob->type == OB_ARMATURE)); // XXX isdata arg here doesn't give an accurate picture of situation - + key = BKE_key_from_object(ob); if (key && key->adt) dag_add_driver_relation(key->adt, dag, node, 1); @@ -654,13 +654,13 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O }; for (md = ob->modifiers.first; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - + if (mti->updateDepgraph) mti->updateDepgraph(md, &ctx); } } if (ob->parent) { node2 = dag_get_node(dag, ob->parent); - + switch (ob->partype) { case PARSKEL: dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Parent"); @@ -677,7 +677,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Lattice Parent"); else if (ob->parent->type == OB_CURVE) { Curve *cu = ob->parent->data; - if (cu->flag & CU_PATH) + if (cu->flag & CU_PATH) dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Curve Parent"); else dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Curve Parent"); @@ -690,7 +690,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O if (ob->type == OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) { dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Duplivert"); } - + addtoroot = 0; } if (ob->proxy) { @@ -698,7 +698,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Proxy"); /* inverted relation, so addtoroot shouldn't be set to zero */ } - + if (ob->transflag & OB_DUPLI) { if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) { GroupObject *go; @@ -725,23 +725,23 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O if (adt) dag_add_driver_relation(adt, dag, node, 1); } - + /* object type/data relationships */ switch (ob->type) { case OB_CAMERA: { Camera *cam = (Camera *)ob->data; - + if (cam->dof_ob) { node2 = dag_get_node(dag, cam->dof_ob); dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Camera DoF"); } break; } - case OB_MBALL: + case OB_MBALL: { Object *mom = BKE_mball_basis_find(G.main, G.main->eval_ctx, scene, ob); - + if (mom != ob) { node2 = dag_get_node(dag, mom); dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball"); /* mom depends on children! */ @@ -752,7 +752,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O case OB_FONT: { Curve *cu = ob->data; - + if (cu->bevobj) { node2 = dag_get_node(dag, cu->bevobj); dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Bevel"); @@ -795,14 +795,14 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O break; } } - + /* material drivers */ if (ob->totcol) { int a; - + for (a = 1; a <= ob->totcol; a++) { Material *ma = give_current_material(ob, a); - + if (ma) { /* recursively figure out if there are drivers, and hook these up to this object */ dag_add_material_driver_relations(dag, node, ma); @@ -812,7 +812,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O else if (ob->type == OB_LAMP) { dag_add_lamp_driver_relations(dag, node, ob->data); } - + /* particles */ psys = ob->particlesystem.first; if (psys) { @@ -889,13 +889,13 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } } } - + /* object constraints */ for (con = ob->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (!cti) continue; @@ -905,15 +905,15 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } else if (cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { Object *obt; - + if (ct->tar) obt = ct->tar; else continue; - + node2 = dag_get_node(dag, obt); if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO)) dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name); @@ -932,7 +932,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } addtoroot = 0; } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } @@ -948,7 +948,7 @@ static void build_dag_group(DagForest *dag, DagNode *scenenode, Main *bmain, Sce if (group->id.tag & LIB_TAG_DOIT) return; - + group->id.tag |= LIB_TAG_DOIT; for (go = group->gobject.first; go; go = go->next) { @@ -982,10 +982,10 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false); BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false); BKE_main_id_tag_idcode(bmain, ID_GR, LIB_TAG_DOIT, false); - + /* add base node for scene. scene is always the first node in DAG */ scenenode = dag_add_node(dag, sce); - + /* add current scene objects */ for (base = sce->base.first; base; base = base->next) { ob = base->object; @@ -993,7 +993,7 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) build_dag_object(dag, scenenode, sce, ob, mask); if (ob->proxy) build_dag_object(dag, scenenode, sce, ob->proxy, mask); - if (ob->dup_group) + if (ob->dup_group) build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask); } @@ -1027,11 +1027,11 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) } BKE_main_id_tag_idcode(bmain, ID_GR, LIB_TAG_DOIT, false); - + /* Now all relations were built, but we need to solve 1 exceptional case; * When objects have multiple "parents" (for example parent + constraint working on same object) * the relation type has to be synced. One of the parents can change, and should give same event to child */ - + /* nodes were callocced, so we can use node->color for temporal storage */ for (node = sce->theDag->DagNode.first; node; node = node->next) { if (node->type == ID_OB) { @@ -1059,21 +1059,21 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) } } } - + /* cycle detection and solving */ // solve_cycles(dag); - + return dag; } -void free_forest(DagForest *Dag) +void free_forest(DagForest *Dag) { /* remove all nodes and deps */ DagNode *tempN; DagAdjList *tempA; DagAdjList *itA; DagNode *itN = Dag->DagNode.first; - + while (itN) { itA = itN->child; while (itA) { @@ -1081,14 +1081,14 @@ void free_forest(DagForest *Dag) itA = itA->next; MEM_freeN(tempA); } - + itA = itN->parent; while (itA) { tempA = itA; itA = itA->next; MEM_freeN(tempA); } - + tempN = itN; itN = itN->next; MEM_freeN(tempN); @@ -1116,7 +1116,7 @@ static int dag_print_dependencies = 0; /* debugging */ DagNode *dag_add_node(DagForest *forest, void *fob) { DagNode *node; - + node = MEM_callocN(sizeof(DagNode), "DAG node"); if (node) { node->ob = fob; @@ -1145,9 +1145,9 @@ DagNode *dag_add_node(DagForest *forest, void *fob) DagNode *dag_get_node(DagForest *forest, void *fob) { DagNode *node; - + node = dag_find_node(forest, fob); - if (!node) + if (!node) node = dag_add_node(forest, fob); return node; } @@ -1158,7 +1158,7 @@ DagNode *dag_get_sub_node(DagForest *forest, void *fob) { DagNode *node; DagAdjList *mainchild, *prev = NULL; - + mainchild = ((DagNode *) forest->DagNode.first)->child; /* remove from first node (scene) adj list if present */ while (mainchild) { @@ -1178,15 +1178,15 @@ DagNode *dag_get_sub_node(DagForest *forest, void *fob) mainchild = mainchild->next; } node = dag_find_node(forest, fob); - if (!node) + if (!node) node = dag_add_node(forest, fob); return node; } -static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, DagNode *fob2, short rel, const char *name) +static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, DagNode *fob2, short rel, const char *name) { DagAdjList *itA = fob2->parent; - + while (itA) { /* search if relation exist already */ if (itA->node == fob1) { itA->type |= rel; @@ -1205,10 +1205,10 @@ static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, Da fob2->parent = itA; } -void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, const char *name) +void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, const char *name) { DagAdjList *itA = fob1->child; - + /* parent relation is for cycle checking */ dag_add_parent_relation(forest, fob1, fob2, rel, name); @@ -1309,7 +1309,7 @@ static int dag_node_recurs_level(DagNode *node, int level) node->color = DAG_BLACK; /* done */ newlevel = ++level; - + for (itA = node->parent; itA; itA = itA->next) { if (itA->node->color == DAG_WHITE) { itA->node->ancestor_count = dag_node_recurs_level(itA->node, level); @@ -1318,7 +1318,7 @@ static int dag_node_recurs_level(DagNode *node, int level) else newlevel = MAX2(newlevel, level + itA->node->ancestor_count); } - + return newlevel; } @@ -1337,13 +1337,13 @@ static void dag_check_cycle(DagForest *dag) /* tag nodes unchecked */ for (node = dag->DagNode.first; node; node = node->next) node->color = DAG_WHITE; - + for (node = dag->DagNode.first; node; node = node->next) { if (node->color == DAG_WHITE) { node->ancestor_count = dag_node_recurs_level(node, 0); } } - + /* check relations, and print errors */ for (node = dag->DagNode.first; node; node = node->next) { for (itA = node->parent; itA; itA = itA->next) { @@ -1370,9 +1370,9 @@ static void dag_check_cycle(DagForest *dag) /* debug test functions */ void graph_print_queue(DagNodeQueue *nqueue) -{ +{ DagNodeQueueElem *queueElem; - + queueElem = nqueue->first; while (queueElem) { fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm); @@ -1382,10 +1382,10 @@ void graph_print_queue(DagNodeQueue *nqueue) } void graph_print_queue_dist(DagNodeQueue *nqueue) -{ +{ DagNodeQueueElem *queueElem; int count; - + queueElem = nqueue->first; count = 0; while (queueElem) { @@ -1405,14 +1405,14 @@ void graph_print_adj_list(DagForest *dag) { DagNode *node; DagAdjList *itA; - + node = dag->DagNode.first; while (node) { fprintf(stderr, "node : %s col: %i", ((ID *) node->ob)->name, node->color); itA = node->child; while (itA) { fprintf(stderr, "-- %s ", ((ID *) itA->node->ob)->name); - + itA = itA->next; } fprintf(stderr, "\n"); @@ -1474,14 +1474,14 @@ static void scene_sort_groups(Main *bmain, Scene *sce) Group *group; GroupObject *go; Object *ob; - + /* test; are group objects all in this scene? */ for (ob = bmain->object.first; ob; ob = ob->id.next) { ob->id.tag &= ~LIB_TAG_DOIT; } for (base = sce->base.first; base; base = base->next) base->object->id.tag |= LIB_TAG_DOIT; - + for (group = bmain->group.first; group; group = group->id.next) { for (go = group->gobject.first; go; go = go->next) { if ((go->ob->id.tag & LIB_TAG_DOIT) == 0) @@ -1490,13 +1490,13 @@ static void scene_sort_groups(Main *bmain, Scene *sce) /* this group is entirely in this scene */ if (go == NULL) { ListBase listb = {NULL, NULL}; - + for (go = group->gobject.first; go; go = go->next) go->ob->id.newid = (ID *)go; - + /* in order of sorted bases we reinsert group objects */ for (base = sce->base.first; base; base = base->next) { - + if (base->object->id.newid) { go = (GroupObject *)base->object->id.newid; base->object->id.newid = NULL; @@ -1668,29 +1668,29 @@ static void dag_scene_build(Main *bmain, Scene *sce) dag_check_cycle(sce->theDag); nqueue = queue_create(DAGQUEUEALLOC); - + for (node = sce->theDag->DagNode.first; node; node = node->next) { node->color = DAG_WHITE; } - + time = 1; - + rootnode = sce->theDag->DagNode.first; rootnode->color = DAG_GRAY; time++; push_stack(nqueue, rootnode); - + while (nqueue->count) { - + skip = 0; node = get_top_node_queue(nqueue); - + itA = node->child; while (itA != NULL) { if (itA->node->color == DAG_WHITE) { itA->node->DFS_dvtm = time; itA->node->color = DAG_GRAY; - + time++; push_stack(nqueue, itA->node); skip = 1; @@ -1698,14 +1698,14 @@ static void dag_scene_build(Main *bmain, Scene *sce) } itA = itA->next; } - + if (!skip) { if (node) { node = pop_queue(nqueue); if (node->ob == sce) /* we are done */ break; node->color = DAG_BLACK; - + time++; base = sce->base.first; while (base && base->object != node->ob) @@ -1717,7 +1717,7 @@ static void dag_scene_build(Main *bmain, Scene *sce) } } } - + /* temporal correction for circular dependencies */ base = sce->base.first; while (base) { @@ -1727,13 +1727,13 @@ static void dag_scene_build(Main *bmain, Scene *sce) printf("cyclic %s\n", base->object->id.name); base = sce->base.first; } - + sce->base = tempbase; queue_delete(nqueue); - + /* all groups with objects in this scene gets resorted too */ scene_sort_groups(bmain, sce); - + if (G.debug & G_DEBUG) { printf("\nordered\n"); for (base = sce->base.first; base; base = base->next) { @@ -1833,9 +1833,9 @@ static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, in int oldflag; bool changed = false; unsigned int all_layer; - + node->lasttime = curtime; - + ob = node->ob; if (ob && (ob->recalc & OB_RECALC_ALL)) { all_layer = node->scelay; @@ -1848,7 +1848,7 @@ static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, in if (itA->node->type == ID_OB) { obc = itA->node->ob; oldflag = obc->recalc; - + /* got a ob->obc relation, now check if flag needs flush */ if (ob->recalc & OB_RECALC_OB) { if (itA->type & DAG_RL_OB_OB) { @@ -1883,11 +1883,11 @@ static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, in /* but existing displaylists or derivedmesh should be freed */ if (ob->recalc & OB_RECALC_DATA) BKE_object_free_derived_caches(ob); - + ob->recalc &= ~OB_RECALC_ALL; } } - + /* check case where child changes and parent forcing obdata to change */ /* should be done regardless if this ob has recalc set */ /* could merge this in with loop above...? (ton) */ @@ -1908,23 +1908,23 @@ static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, in } } } - + /* we only go deeper if node not checked or something changed */ for (itA = node->child; itA; itA = itA->next) { if (changed || itA->node->lasttime != curtime) flush_update_node(bmain, itA->node, layer, curtime); } - + } /* node was checked to have lasttime != curtime, and is of type ID_OB */ static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime) { DagAdjList *itA; - + node->lasttime = curtime; node->lay = node->scelay; - + for (itA = node->child; itA; itA = itA->next) { if (itA->node->type == ID_OB) { if (itA->node->lasttime != curtime) { @@ -1933,7 +1933,7 @@ static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime) else { itA->lay = itA->node->lay; } - + node->lay |= itA->lay; } } @@ -1947,9 +1947,9 @@ static void flush_pointcache_reset(Main *bmain, Scene *scene, DagNode *node, { DagAdjList *itA; Object *ob; - + node->lasttime = curtime; - + for (itA = node->child; itA; itA = itA->next) { if (itA->node->type == ID_OB) { if (itA->node->lasttime != curtime) { @@ -2029,12 +2029,12 @@ static void dag_tag_renderlayers(Scene *sce, unsigned int lay) bNode *node; Base *base; unsigned int lay_changed = 0; - + for (base = sce->base.first; base; base = base->next) if (base->lay & lay) if (base->object->recalc) lay_changed |= base->lay; - + for (node = sce->nodetree->nodes.first; node; node = node->next) { if (node->id == (ID *)sce) { SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1); @@ -2062,7 +2062,7 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho printf("DAG zero... not allowed to happen!\n"); DAG_scene_relations_update(bmain, sce); } - + firstnode = sce->theDag->DagNode.first; /* always scene node */ /* first we flush the layer flags */ @@ -2098,14 +2098,14 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho } } } - + dag_tag_renderlayers(sce, lay); } static bool modifier_nlastrips_use_time(ListBase *strips) { NlaStrip *strip; - + if (strips) { for (strip = strips->first; strip; strip = strip->next) { if (modifier_nlastrips_use_time(&strip->strips)) { @@ -2113,7 +2113,7 @@ static bool modifier_nlastrips_use_time(ListBase *strips) } else if (strip->act) { FCurve *fcu; - + for (fcu = strip->act->curves.first; fcu; fcu = fcu->next) { if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) return true; @@ -2121,26 +2121,26 @@ static bool modifier_nlastrips_use_time(ListBase *strips) } } } - + return false; } static bool object_modifiers_use_time(Object *ob) { ModifierData *md; - + /* check if a modifier in modifier stack needs time input */ for (md = ob->modifiers.first; md; md = md->next) { if (modifier_dependsOnTime(md)) return true; } - + /* check whether any modifiers are animated */ if (ob->adt) { AnimData *adt = ob->adt; NlaTrack *nlt; FCurve *fcu; - + /* action - check for F-Curves with paths containing 'modifiers[' */ if (adt->action) { for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) { @@ -2148,7 +2148,7 @@ static bool object_modifiers_use_time(Object *ob) return true; } } - + /* This here allows modifier properties to get driven and still update properly * * Workaround to get [#26764] (e.g. subsurf levels not updating when animated/driven) @@ -2159,40 +2159,40 @@ static bool object_modifiers_use_time(Object *ob) if (fcu->rna_path && strstr(fcu->rna_path, "modifiers[")) return true; } - + /* Also check NLA Strips... [#T45938] */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (modifier_nlastrips_use_time(&nlt->strips)) return true; } } - + return false; } static short animdata_use_time(AnimData *adt) { NlaTrack *nlt; - + if (adt == NULL) return 0; - + /* check action - only if assigned, and it has anim curves */ if (adt->action && adt->action->curves.first) return 1; - + /* check NLA tracks + strips */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (nlt->strips.first) return 1; } - + /* If we have drivers, more likely than not, on a frame change * they'll need updating because their owner changed - * + * * This is kindof a hack to get around a whole host of problems - * involving drivers using non-object datablock data (which the + * involving drivers using non-object datablock data (which the * depsgraph currently has no way of representing let alone correctly - * dependency sort+tagging). By doing this, at least we ensure that + * dependency sort+tagging). By doing this, at least we ensure that * some commonly attempted drivers (such as scene -> current frame; * see "Driver updates fail" thread on Bf-committers dated July 2) * will work correctly, and that other non-object datablocks will have @@ -2202,7 +2202,7 @@ static short animdata_use_time(AnimData *adt) */ if (adt->drivers.first) return 1; - + return 0; } @@ -2214,7 +2214,7 @@ static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob) const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti) { /* special case for camera tracking -- it doesn't use targets to define relations */ if (ELEM(cti->type, @@ -2227,27 +2227,27 @@ static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob) } else if (cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar) { ob->recalc |= OB_RECALC_OB; break; } } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } - + } } } - + if (ob->parent) { /* motion path or bone child */ if (ob->parent->type == OB_CURVE || ob->parent->type == OB_ARMATURE) ob->recalc |= OB_RECALC_OB; } - + #if 0 // XXX old animation system if (ob->nlastrips.first) { if (ob->dup_group) { @@ -2260,27 +2260,27 @@ static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob) } } #endif // XXX old animation system - + if (animdata_use_time(ob->adt)) { ob->recalc |= OB_RECALC_OB; ob->adt->recalc |= ADT_RECALC_ANIM; } - + if ((ob->adt) && (ob->type == OB_ARMATURE)) ob->recalc |= OB_RECALC_DATA; - + if (object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA; if ((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA; - + // XXX: scene here may not be the scene that contains the rigidbody world affecting this! if (ob->rigidbody_object && BKE_scene_check_rigidbody_active(scene)) ob->recalc |= OB_RECALC_OB; - + { AnimData *adt = BKE_animdata_from_id((ID *)ob->data); Mesh *me; Curve *cu; Lattice *lt; - + switch (ob->type) { case OB_MESH: me = ob->data; @@ -2334,7 +2334,7 @@ static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob) ob->recalc |= OB_RECALC_DATA; break; } - + if (animdata_use_time(adt)) { ob->recalc |= OB_RECALC_DATA; adt->recalc |= ADT_RECALC_ANIM; @@ -2366,7 +2366,7 @@ static void dag_group_update_flags(Main *bmain, Scene *scene, Group *group, cons if (group->id.tag & LIB_TAG_DOIT) return; - + group->id.tag |= LIB_TAG_DOIT; for (go = group->gobject.first; go; go = go->next) { @@ -2396,9 +2396,9 @@ void DAG_scene_update_flags(Main *bmain, Scene *scene, unsigned int lay, const b if (do_time) { /* now if DagNode were part of base, the node->lay could be checked... */ /* we do all now, since the scene_flush checks layers and clears recalc flags even */ - - /* NOTE: "sce_iter" not "scene" so that rigidbodies in background scenes work - * (i.e. muting + rbw availability can be checked and tagged properly) [#33970] + + /* NOTE: "sce_iter" not "scene" so that rigidbodies in background scenes work + * (i.e. muting + rbw availability can be checked and tagged properly) [#33970] */ dag_object_time_update_flags(bmain, sce_iter, ob); } @@ -2410,7 +2410,7 @@ void DAG_scene_update_flags(Main *bmain, Scene *scene, unsigned int lay, const b for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set) DAG_scene_flush_update(bmain, sce_iter, lay, 1); - + if (do_time) { /* test: set time flag, to disable baked systems to update */ for (SETLOOPER(scene, sce_iter, base)) { @@ -2452,12 +2452,12 @@ static void dag_current_scene_layers(Main *bmain, ListBase *lb) { wmWindowManager *wm; wmWindow *win; - + BLI_listbase_clear(lb); /* if we have a windowmanager, look into windows */ if ((wm = bmain->wm.first)) { - + BKE_main_id_flag_listbase(&bmain->scene, LIB_TAG_DOIT, 1); for (win = wm->windows.first; win; win = win->next) { @@ -2499,9 +2499,9 @@ static void dag_current_scene_layers(Main *bmain, ListBase *lb) else { /* if not, use the first sce */ DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer"); - + BLI_addtail(lb, dsl); - + dsl->scene = bmain->scene.first; dsl->layer = dsl->scene->lay; @@ -2517,7 +2517,7 @@ static void dag_group_on_visible_update(Scene *scene, Group *group) if (group->id.tag & LIB_TAG_DOIT) return; - + group->id.tag |= LIB_TAG_DOIT; for (go = group->gobject.first; go; go = go->next) { @@ -2550,7 +2550,7 @@ void DAG_on_visible_update(Main *bmain, const bool do_time) /* get list of visible scenes and layers */ dag_current_scene_layers(bmain, &listbase); - + for (dsl = listbase.first; dsl; dsl = dsl->next) { Scene *scene = dsl->scene; Scene *sce_iter; @@ -2603,7 +2603,7 @@ void DAG_on_visible_update(Main *bmain, const bool do_time) DAG_scene_update_flags(bmain, scene, lay, do_time, true); scene->lay_updated |= lay; } - + BLI_freelistN(&listbase); /* hack to get objects updating on layer changes */ @@ -2623,7 +2623,7 @@ static void dag_id_flush_update__isDependentTexture( void *userData, Object *UNUSED(ob), ID **idpoin, int UNUSED(cb_flag)) { struct { ID *id; bool is_dependent; } *data = userData; - + if (*idpoin && GS((*idpoin)->name) == ID_TE) { if (data->id == (*idpoin)) data->is_dependent = 1; @@ -2726,7 +2726,7 @@ static void dag_id_flush_update(Main *bmain, Scene *sce, ID *id) } } } - + /* set flags based on ShapeKey */ if (idtype == ID_KE) { for (obt = bmain->object.first; obt; obt = obt->id.next) { @@ -2739,7 +2739,7 @@ static void dag_id_flush_update(Main *bmain, Scene *sce, ID *id) } } } - + /* set flags based on particle settings */ if (idtype == ID_PA) { ParticleSystem *psys; @@ -2863,7 +2863,7 @@ void DAG_ids_flush_tagged(Main *bmain) if (id->recalc & ID_RECALC_ALL) { for (dsl = listbase.first; dsl; dsl = dsl->next) dag_id_flush_update(bmain, dsl->scene, id); - + do_flush = true; } } @@ -2875,7 +2875,7 @@ void DAG_ids_flush_tagged(Main *bmain) for (dsl = listbase.first; dsl; dsl = dsl->next) DAG_scene_flush_update(bmain, dsl->scene, dsl->layer, 0); } - + BLI_freelistN(&listbase); } @@ -3112,28 +3112,28 @@ int DAG_id_type_tagged(Main *bmain, short idtype) static int parent_check_node(DagNode *node, int curtime) { DagAdjList *itA; - + node->lasttime = curtime; - + if (node->color == DAG_GRAY) return DAG_GRAY; - + for (itA = node->child; itA; itA = itA->next) { if (itA->node->type == ID_OB) { - + if (itA->node->color == DAG_GRAY) return DAG_GRAY; /* descend if not done */ if (itA->node->lasttime != curtime) { itA->node->color = parent_check_node(itA->node, curtime); - + if (itA->node->color == DAG_GRAY) return DAG_GRAY; } } } - + return DAG_WHITE; } #endif @@ -3154,18 +3154,18 @@ void DAG_pose_sort(Object *ob) DagAdjList *itA; ListBase tempbase; int skip = 0; - + dag = dag_init(); dag->ugly_hack_sorry = false; /* no ID structs */ rootnode = dag_add_node(dag, NULL); /* node->ob becomes NULL */ - + /* we add the hierarchy and the constraints */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { int addtoroot = 1; - + node = dag_get_node(dag, pchan); - + if (pchan->parent) { node2 = dag_get_node(dag, pchan->parent); dag_add_relation(dag, node2, node, 0, "Parent Relation"); @@ -3175,33 +3175,33 @@ void DAG_pose_sort(Object *ob) const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar == ob && ct->subtarget[0]) { bPoseChannel *target = BKE_pose_channel_find_name(ob->pose, ct->subtarget); if (target) { node2 = dag_get_node(dag, target); dag_add_relation(dag, node2, node, 0, "Pose Constraint"); - + if (con->type == CONSTRAINT_TYPE_KINEMATIC) { bKinematicConstraint *data = (bKinematicConstraint *)con->data; bPoseChannel *parchan; int segcount = 0; - + /* exclude tip from chain? */ if (!(data->flag & CONSTRAINT_IK_TIP)) parchan = pchan->parent; else parchan = pchan; - + /* Walk to the chain's root */ while (parchan) { node3 = dag_get_node(dag, parchan); dag_add_relation(dag, node2, node3, 0, "IK Constraint"); - + segcount++; if (segcount == data->rootbone || segcount > 255) break; /* 255 is weak */ parchan = parchan->parent; @@ -3210,7 +3210,7 @@ void DAG_pose_sort(Object *ob) } } } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } @@ -3221,24 +3221,24 @@ void DAG_pose_sort(Object *ob) } dag_check_cycle(dag); - + /* now we try to sort... */ BLI_listbase_clear(&tempbase); nqueue = queue_create(DAGQUEUEALLOC); - + /* tag nodes unchecked */ for (node = dag->DagNode.first; node; node = node->next) node->color = DAG_WHITE; - + rootnode->color = DAG_GRAY; - push_stack(nqueue, rootnode); - + push_stack(nqueue, rootnode); + while (nqueue->count) { - + skip = 0; node = get_top_node_queue(nqueue); - + itA = node->child; while (itA != NULL) { if (itA->node->color == DAG_WHITE) { @@ -3249,21 +3249,21 @@ void DAG_pose_sort(Object *ob) } itA = itA->next; } - + if (!skip) { if (node) { node = pop_queue(nqueue); if (node->ob == NULL) /* we are done */ break; node->color = DAG_BLACK; - + /* put node in new list */ BLI_remlink(&pose->chanbase, node->ob); BLI_addhead(&tempbase, node->ob); } } } - + /* temporal correction for circular dependencies */ while (pose->chanbase.first) { pchan = pose->chanbase.first; @@ -3272,15 +3272,15 @@ void DAG_pose_sort(Object *ob) printf("cyclic %s\n", pchan->name); } - + pose->chanbase = tempbase; queue_delete(nqueue); - + // printf("\nordered\n"); // for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { // printf(" %s\n", pchan->name); // } - + free_forest(dag); MEM_freeN(dag); } @@ -3380,7 +3380,7 @@ void DAG_print_dependencies(Main *bmain, Scene *scene, Object *ob) printf("\nDEPENDENCY RELATIONS for %s\n\n", scene->id.name + 2); DAG_scene_relations_rebuild(bmain, scene); } - + dag_print_dependencies = 0; } diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c index ffa7fdc3ec95..fa4e4372273a 100644 --- a/source/blender/blenkernel/intern/editderivedmesh.c +++ b/source/blender/blenkernel/intern/editderivedmesh.c @@ -1093,7 +1093,7 @@ static void emDM_drawMappedFaces( efa = ltri[0]->f; drawSmooth = lnors || ((flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : BM_elem_flag_test(efa, BM_ELEM_SMOOTH)); - + draw_option = (setDrawOptions ? setDrawOptions(userData, BM_elem_index_get(efa)) : DM_DRAW_OPTION_NORMAL); @@ -1120,7 +1120,7 @@ static void emDM_drawMappedFaces( } prev_mat_nr = efa->mat_nr; } - + if (draw_option == DM_DRAW_OPTION_STIPPLE) { /* enabled with stipple */ if (poly_prev != GL_ZERO) glEnd(); diff --git a/source/blender/blenkernel/intern/editmesh_bvh.c b/source/blender/blenkernel/intern/editmesh_bvh.c index 2927354241c1..c1121d5b1ead 100644 --- a/source/blender/blenkernel/intern/editmesh_bvh.c +++ b/source/blender/blenkernel/intern/editmesh_bvh.c @@ -147,9 +147,9 @@ BMBVHTree *BKE_bmbvh_new_ex( BLI_bvhtree_insert(bmtree->tree, i, (float *)cos, 3); } - + BLI_bvhtree_balance(bmtree->tree); - + return bmtree; } @@ -188,11 +188,11 @@ BMBVHTree *BKE_bmbvh_new( void BKE_bmbvh_free(BMBVHTree *bmtree) { BLI_bvhtree_free(bmtree->tree); - + if (bmtree->cos_cage && bmtree->cos_cage_free) { MEM_freeN((void *)bmtree->cos_cage); } - + MEM_freeN(bmtree); } @@ -313,7 +313,7 @@ BMFace *BKE_bmbvh_ray_cast(BMBVHTree *bmtree, const float co[3], const float dir /* ok to leave 'uv' uninitialized */ bmcb_data.looptris = (const BMLoop *(*)[3])bmtree->looptris; bmcb_data.cos_cage = (const float (*)[3])bmtree->cos_cage; - + BLI_bvhtree_ray_cast(bmtree->tree, co, dir, radius, &hit, bmbvh_ray_cast_cb, &bmcb_data); if (hit.index != -1 && hit.dist != dist) { @@ -547,4 +547,4 @@ BVHTreeOverlap *BKE_bmbvh_overlap(const BMBVHTree *bmtree_a, const BMBVHTree *bm data.epsilon = max_ff(BLI_bvhtree_get_epsilon(bmtree_a->tree), BLI_bvhtree_get_epsilon(bmtree_b->tree)); return BLI_bvhtree_overlap(bmtree_a->tree, bmtree_b->tree, r_overlap_tot, bmbvh_overlap_cb, &data); -} \ No newline at end of file +} diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index e47af83e00eb..89f855304397 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -212,10 +212,10 @@ ListBase *pdInitEffectors(Scene *scene, Object *ob_src, ParticleSystem *psys_src Base *base; unsigned int layer= ob_src->lay; ListBase *effectors = NULL; - + if (weights->group) { GroupObject *go; - + for (go= weights->group->gobject.first; go; go= go->next) { if ( (go->ob->lay & layer) ) { if ( go->ob->pd && go->ob->pd->forcefield ) @@ -245,10 +245,10 @@ ListBase *pdInitEffectors(Scene *scene, Object *ob_src, ParticleSystem *psys_src } } } - + if (for_simulation) pdPrecalculateEffectors(effectors); - + return effectors; } @@ -326,7 +326,7 @@ void pd_point_from_particle(ParticleSimulationData *sim, ParticleData *pa, Parti point->index = pa - sim->psys->particles; point->size = pa->size; point->charge = 0.0f; - + if (part->pd && part->pd->forcefield == PFIELD_CHARGE) point->charge += part->pd->f_strength; @@ -385,7 +385,7 @@ void pd_point_from_soft(Scene *scene, float *loc, float *vel, int index, Effecte // triangle - ray callback function static void eff_tri_ray_hit(void *UNUSED(userData), int UNUSED(index), const BVHTreeRay *UNUSED(ray), BVHTreeRayHit *hit) -{ +{ /* whenever we hit a bounding box, we don't check further */ hit->dist = -1; hit->index = 1; @@ -399,7 +399,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect ColliderCache *col; float norm[3], len = 0.0; float visibility = 1.0, absorption = 0.0; - + if (!(eff->pd->flag & PFIELD_VISIBILITY)) return visibility; @@ -411,7 +411,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect negate_v3_v3(norm, efd->vec_to_point); len = normalize_v3(norm); - + /* check all collision objects */ for (col = colls->first; col; col = col->next) { CollisionModifierData *collmd = col->collmd; @@ -434,7 +434,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect /* visibility is only between 0 and 1, calculated from 1-absorption */ visibility *= CLAMPIS(1.0f-absorption, 0.0f, 1.0f); - + if (visibility <= 0.0f) break; } @@ -443,7 +443,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect if (!colliders) free_collider_cache(&colls); - + return visibility; } @@ -454,11 +454,11 @@ static float wind_func(struct RNG *rng, float strength) float force = BLI_rng_get_float(rng) + 1.0f; float ret; float sign = 0; - + sign = ((float)random > 64.0f) ? 1.0f: -1.0f; // dividing by 2 is not giving equal sign distribution - + ret = sign*((float)random / force)*strength/128.0f; - + return ret; } @@ -551,7 +551,7 @@ int closest_point_on_surface(SurfaceModifierData *surmd, const float co[3], floa if (surface_vel) { const MLoop *mloop = surmd->bvhtree->loop; const MLoopTri *lt = &surmd->bvhtree->looptri[nearest.index]; - + copy_v3_v3(surface_vel, surmd->v[mloop[lt->tri[0]].v].co); add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[1]].v].co); add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[2]].v].co); @@ -632,7 +632,7 @@ int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *poin efd->nor[0] = 1.f; efd->nor[1] = efd->nor[2] = 0.f; mul_qt_v3(state.rot, efd->nor); - + if (real_velocity) copy_v3_v3(efd->vel, state.vel); @@ -705,9 +705,9 @@ static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoin } else if (eff->psys) { *tot = eff->psys->totpart; - + if (eff->pd->forcefield == PFIELD_CHARGE) { - /* Only the charge of the effected particle is used for + /* Only the charge of the effected particle is used for * interaction, not fall-offs. If the fall-offs aren't the * same this will be unphysical, but for animation this * could be the wanted behavior. If you want physical @@ -869,10 +869,10 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected /* new vortex force */ cross_v3_v3v3(temp, efd->nor2, efd->vec_to_point2); mul_v3_fl(temp, strength * efd->falloff); - + cross_v3_v3v3(force, efd->nor2, temp); mul_v3_fl(force, strength * efd->falloff); - + madd_v3_v3fl(temp, point->vel, -point->vel_to_sec); add_v3_v3(force, temp); } @@ -900,7 +900,7 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected break; case PFIELD_LENNARDJ: fac = pow((efd->size + point->size) / efd->distance, 6.0); - + fac = - fac * (1.0f - fac) / efd->distance; /* limit the repulsive term drastically to avoid huge forces */ @@ -1005,7 +1005,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */ /* Check for min distance here? (yes would be cool to add that, ton) */ - + if (effectors) for (eff = effectors->first; eff; eff=eff->next) { /* object effectors were fully checked to be OK to evaluate! */ @@ -1014,7 +1014,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we for (; p 0.0f) efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point); @@ -1029,7 +1029,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we copy_v3_v3(temp1, force); do_physical_effector(eff, &efd, point, force); - + /* for softbody backward compatibility */ if (point->flag & PE_WIND_AS_SPEED && impulse) { sub_v3_v3v3(temp2, force, temp1); @@ -1142,14 +1142,14 @@ void BKE_sim_debug_data_add_element(int type, const float v1[3], const float v2[ { unsigned int category_hash = BLI_ghashutil_strhash_p(category); SimDebugElement *elem; - + if (!_sim_debug_data) { if (G.debug & G_DEBUG_SIMDATA) BKE_sim_debug_data_set_enabled(true); else return; } - + elem = MEM_callocN(sizeof(SimDebugElement), "sim debug data element"); elem->type = type; elem->category_hash = category_hash; @@ -1169,7 +1169,7 @@ void BKE_sim_debug_data_add_element(int type, const float v1[3], const float v2[ BLI_strncpy(elem->str, str, sizeof(elem->str)); else elem->str[0] = '\0'; - + debug_data_insert(_sim_debug_data, elem); } @@ -1178,7 +1178,7 @@ void BKE_sim_debug_data_remove_element(unsigned int hash) SimDebugElement dummy; if (!_sim_debug_data) return; - + dummy.hash = hash; BLI_ghash_remove(_sim_debug_data->gh, &dummy, NULL, debug_element_free); } @@ -1187,7 +1187,7 @@ void BKE_sim_debug_data_clear(void) { if (!_sim_debug_data) return; - + if (_sim_debug_data->gh) BLI_ghash_clear(_sim_debug_data->gh, NULL, debug_element_free); } @@ -1195,17 +1195,17 @@ void BKE_sim_debug_data_clear(void) void BKE_sim_debug_data_clear_category(const char *category) { int category_hash = (int)BLI_ghashutil_strhash_p(category); - + if (!_sim_debug_data) return; - + if (_sim_debug_data->gh) { GHashIterator iter; BLI_ghashIterator_init(&iter, _sim_debug_data->gh); while (!BLI_ghashIterator_done(&iter)) { const SimDebugElement *elem = BLI_ghashIterator_getValue(&iter); BLI_ghashIterator_step(&iter); /* removing invalidates the current iterator, so step before removing */ - + if (elem->category_hash == category_hash) BLI_ghash_remove(_sim_debug_data->gh, elem, NULL, debug_element_free); } diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 0de04e31be9b..95e4d2c92ae2 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -29,7 +29,7 @@ * \ingroup bke */ - + #include #include @@ -58,7 +58,7 @@ #include "BKE_armature.h" #include "BKE_constraint.h" #include "BKE_context.h" -#include "BKE_curve.h" +#include "BKE_curve.h" #include "BKE_global.h" #include "BKE_object.h" #include "BKE_nla.h" @@ -66,7 +66,7 @@ #include "RNA_access.h" #ifdef WITH_PYTHON -#include "BPY_extern.h" +#include "BPY_extern.h" #endif #define SMALL -1.0e-10 @@ -83,20 +83,20 @@ static ThreadMutex python_driver_lock = BLI_MUTEX_INITIALIZER; /* Frees the F-Curve itself too, so make sure BLI_remlink is called before calling this... */ void free_fcurve(FCurve *fcu) { - if (fcu == NULL) + if (fcu == NULL) return; /* free curve data */ MEM_SAFE_FREE(fcu->bezt); MEM_SAFE_FREE(fcu->fpt); - + /* free RNA-path, as this were allocated when getting the path string */ MEM_SAFE_FREE(fcu->rna_path); - + /* free extra data - i.e. modifiers, and driver */ fcurve_free_driver(fcu); free_fmodifiers(&fcu->modifiers); - + /* free f-curve itself */ MEM_freeN(fcu); } @@ -105,12 +105,12 @@ void free_fcurve(FCurve *fcu) void free_fcurves(ListBase *list) { FCurve *fcu, *fcn; - + /* sanity check */ if (list == NULL) return; - - /* free data - no need to call remlink before freeing each curve, + + /* free data - no need to call remlink before freeing each curve, * as we store reference to next, and freeing only touches the curve * it's given */ @@ -118,10 +118,10 @@ void free_fcurves(ListBase *list) fcn = fcu->next; free_fcurve(fcu); } - + /* clear pointers just in case */ BLI_listbase_clear(list); -} +} /* ---------------------- Copy --------------------------- */ @@ -129,30 +129,30 @@ void free_fcurves(ListBase *list) FCurve *copy_fcurve(const FCurve *fcu) { FCurve *fcu_d; - + /* sanity check */ if (fcu == NULL) return NULL; - + /* make a copy */ fcu_d = MEM_dupallocN(fcu); - + fcu_d->next = fcu_d->prev = NULL; fcu_d->grp = NULL; - + /* copy curve data */ fcu_d->bezt = MEM_dupallocN(fcu_d->bezt); fcu_d->fpt = MEM_dupallocN(fcu_d->fpt); - + /* copy rna-path */ fcu_d->rna_path = MEM_dupallocN(fcu_d->rna_path); - + /* copy driver */ fcu_d->driver = fcurve_copy_driver(fcu_d->driver); - + /* copy modifiers */ copy_fmodifiers(&fcu_d->modifiers, &fcu->modifiers); - + /* return new data */ return fcu_d; } @@ -161,14 +161,14 @@ FCurve *copy_fcurve(const FCurve *fcu) void copy_fcurves(ListBase *dst, ListBase *src) { FCurve *dfcu, *sfcu; - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + /* clear destination list first */ BLI_listbase_clear(dst); - + /* copy one-by-one */ for (sfcu = src->first; sfcu; sfcu = sfcu->next) { dfcu = copy_fcurve(sfcu); @@ -192,22 +192,22 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro if (r_driven) *r_driven = false; - + /* only use the current action ??? */ if (ELEM(NULL, adt, adt->action)) return NULL; - + RNA_pointer_create(id, type, data, &ptr); prop = RNA_struct_find_property(&ptr, prop_name); - + if (prop) { path = RNA_path_from_ID_to_property(&ptr, prop); - + if (path) { /* animation takes priority over drivers */ if ((adt->action) && (adt->action->curves.first)) fcu = list_find_fcurve(&adt->action->curves, path, index); - + /* if not animated, check if driven */ if ((fcu == NULL) && (adt->drivers.first)) { fcu = list_find_fcurve(&adt->drivers, path, index); @@ -215,7 +215,7 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro *r_driven = true; fcu = NULL; } - + MEM_freeN(path); } } @@ -228,11 +228,11 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_index) { FCurve *fcu; - + /* sanity checks */ if (ELEM(NULL, list, rna_path) || (array_index < 0) ) return NULL; - + /* check paths of curves, then array indices... */ for (fcu = list->first; fcu; fcu = fcu->next) { /* simple string-compare (this assumes that they have the same root...) */ @@ -242,7 +242,7 @@ FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_ return fcu; } } - + /* return */ return NULL; } @@ -251,7 +251,7 @@ FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) { FCurve *fcu; - + /* sanity checks */ if (ELEM(NULL, fcu_iter, rna_path)) return NULL; @@ -268,7 +268,7 @@ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) return NULL; } -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated * Lists... * - dst: list of LinkData's matching the criteria returned. * List must be freed after use, and is assumed to be empty when passed. @@ -281,36 +281,36 @@ int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, { FCurve *fcu; int matches = 0; - + /* sanity checks */ if (ELEM(NULL, dst, src, dataPrefix, dataName)) return 0; else if ((dataPrefix[0] == 0) || (dataName[0] == 0)) return 0; - + /* search each F-Curve one by one */ for (fcu = src->first; fcu; fcu = fcu->next) { /* check if quoted string matches the path */ if ((fcu->rna_path) && strstr(fcu->rna_path, dataPrefix)) { char *quotedName = BLI_str_quoted_substrN(fcu->rna_path, dataPrefix); - + if (quotedName) { /* check if the quoted name matches the required name */ if (STREQ(quotedName, dataName)) { LinkData *ld = MEM_callocN(sizeof(LinkData), __func__); - + ld->data = fcu; BLI_addtail(dst, ld); - + matches++; } - + /* always free the quoted string, since it needs freeing */ MEM_freeN(quotedName); } } } - + /* return the number of matches */ return matches; } @@ -328,39 +328,39 @@ FCurve *rna_get_fcurve_context_ui( { FCurve *fcu = NULL; PointerRNA tptr = *ptr; - + *r_driven = false; *r_special = false; - + if (r_animdata) *r_animdata = NULL; if (r_action) *r_action = NULL; - + /* Special case for NLA Control Curves... */ if (BKE_nlastrip_has_curves_for_property(ptr, prop)) { NlaStrip *strip = (NlaStrip *)ptr->data; - + /* Set the special flag, since it cannot be a normal action/driver * if we've been told to start looking here... */ *r_special = true; - + /* The F-Curve either exists or it doesn't here... */ fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), rnaindex); return fcu; } - + /* there must be some RNA-pointer + property combon */ if (prop && tptr.id.data && RNA_property_animateable(&tptr, prop)) { AnimData *adt = BKE_animdata_from_id(tptr.id.data); int step = C ? 2 : 1; /* Always 1 in case we have no context (can't check in 'ancestors' of given RNA ptr). */ char *path = NULL; - + if (!adt && C) { path = BKE_animdata_driver_path_hack(C, &tptr, prop, NULL); adt = BKE_animdata_from_id(tptr.id.data); step--; } - + /* Standard F-Curve - Animation (Action) or Drivers */ while (adt && step--) { if ((adt->action && adt->action->curves.first) || (adt->drivers.first)) { @@ -368,27 +368,27 @@ FCurve *rna_get_fcurve_context_ui( if (step) { path = RNA_path_from_ID_to_property(&tptr, prop); } - + // XXX: the logic here is duplicated with a function up above if (path) { /* animation takes priority over drivers */ if (adt->action && adt->action->curves.first) { fcu = list_find_fcurve(&adt->action->curves, path, rnaindex); - + if (fcu && r_action) *r_action = adt->action; } - + /* if not animated, check if driven */ if (!fcu && (adt->drivers.first)) { fcu = list_find_fcurve(&adt->drivers, path, rnaindex); - + if (fcu) { if (r_animdata) *r_animdata = adt; *r_driven = true; } } - + if (fcu && r_action) { if (r_animdata) *r_animdata = adt; *r_action = adt->action; @@ -410,7 +410,7 @@ FCurve *rna_get_fcurve_context_ui( } MEM_SAFE_FREE(path); } - + return fcu; } @@ -423,10 +423,10 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl { int start = 0, end = arraylen; int loopbreaker = 0, maxloop = arraylen * 2; - + /* initialize replace-flag first */ *r_replace = false; - + /* sneaky optimizations (don't go through searching process if...): * - keyframe to be added is to be added out of current bounds * - keyframe to be added would replace one of the existing ones on bounds @@ -438,7 +438,7 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl else { /* check whether to add before/after/on */ float framenum; - + /* 'First' Keyframe (when only one keyframe, this case is used) */ framenum = array[0].vec[1][0]; if (IS_EQT(frame, framenum, threshold)) { @@ -447,7 +447,7 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl } else if (frame < framenum) return 0; - + /* 'Last' Keyframe */ framenum = array[(arraylen - 1)].vec[1][0]; if (IS_EQT(frame, framenum, threshold)) { @@ -457,37 +457,37 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl else if (frame > framenum) return arraylen; } - - + + /* most of the time, this loop is just to find where to put it - * 'loopbreaker' is just here to prevent infinite loops + * 'loopbreaker' is just here to prevent infinite loops */ for (loopbreaker = 0; (start <= end) && (loopbreaker < maxloop); loopbreaker++) { /* compute and get midpoint */ int mid = start + ((end - start) / 2); /* we calculate the midpoint this way to avoid int overflows... */ float midfra = array[mid].vec[1][0]; - + /* check if exactly equal to midpoint */ if (IS_EQT(frame, midfra, threshold)) { *r_replace = true; return mid; } - + /* repeat in upper/lower half */ if (frame > midfra) start = mid + 1; else if (frame < midfra) end = mid - 1; } - + /* print error if loop-limit exceeded */ if (loopbreaker == (maxloop - 1)) { printf("Error: binarysearch_bezt_index() was taking too long\n"); - + /* include debug info */ printf("\tround = %d: start = %d, end = %d, arraylen = %d\n", loopbreaker, start, end, arraylen); } - + /* not found, so return where to place it */ return start; } @@ -509,20 +509,20 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple const bool do_sel_only) { bool found = false; - + /* init outputs */ *first = NULL; *last = NULL; - + /* sanity checks */ if (fcu->bezt == NULL) return found; - + /* only include selected items? */ if (do_sel_only) { BezTriple *bezt; unsigned int i; - + /* find first selected */ bezt = fcu->bezt; for (i = 0; i < fcu->totvert; bezt++, i++) { @@ -532,7 +532,7 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple break; } } - + /* find last selected */ bezt = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert); for (i = 0; i < fcu->totvert; bezt--, i++) { @@ -549,7 +549,7 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple *last = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert); found = true; } - + return found; } @@ -562,18 +562,18 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa float yminv = 999999999.0f, ymaxv = -999999999.0f; bool foundvert = false; unsigned int i; - + if (fcu->totvert) { if (fcu->bezt) { BezTriple *bezt_first = NULL, *bezt_last = NULL; - + if (xmin || xmax) { /* get endpoint keyframes */ foundvert = get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only); - + if (bezt_first) { BLI_assert(bezt_last != NULL); - + if (include_handles) { xminv = min_fff(xminv, bezt_first->vec[0][0], bezt_first->vec[1][0]); xmaxv = max_fff(xmaxv, bezt_last->vec[1][0], bezt_last->vec[2][0]); @@ -584,33 +584,33 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa } } } - + /* only loop over keyframes to find extents for values if needed */ if (ymin || ymax) { BezTriple *bezt, *prevbezt = NULL; - + for (bezt = fcu->bezt, i = 0; i < fcu->totvert; prevbezt = bezt, bezt++, i++) { if ((do_sel_only == false) || BEZT_ISSEL_ANY(bezt)) { /* keyframe itself */ yminv = min_ff(yminv, bezt->vec[1][1]); ymaxv = max_ff(ymaxv, bezt->vec[1][1]); - + if (include_handles) { - /* left handle - only if applicable + /* left handle - only if applicable * NOTE: for the very first keyframe, the left handle actually has no bearings on anything */ if (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ)) { yminv = min_ff(yminv, bezt->vec[0][1]); ymaxv = max_ff(ymaxv, bezt->vec[0][1]); } - + /* right handle - only if applicable */ if (bezt->ipo == BEZT_IPO_BEZ) { yminv = min_ff(yminv, bezt->vec[2][1]); ymaxv = max_ff(ymaxv, bezt->vec[2][1]); } } - + foundvert = true; } } @@ -622,41 +622,41 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa xminv = min_ff(xminv, fcu->fpt[0].vec[0]); xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]); } - + /* only loop over keyframes to find extents for values if needed */ if (ymin || ymax) { FPoint *fpt; - + for (fpt = fcu->fpt, i = 0; i < fcu->totvert; fpt++, i++) { if (fpt->vec[1] < yminv) yminv = fpt->vec[1]; if (fpt->vec[1] > ymaxv) ymaxv = fpt->vec[1]; - + foundvert = true; } } } } - + if (foundvert) { if (xmin) *xmin = xminv; if (xmax) *xmax = xmaxv; - + if (ymin) *ymin = yminv; if (ymax) *ymax = ymaxv; } else { if (G.debug & G_DEBUG) printf("F-Curve calc bounds didn't find anything, so assuming minimum bounds of 1.0\n"); - + if (xmin) *xmin = 0.0f; if (xmax) *xmax = 1.0f; - + if (ymin) *ymin = 0.0f; if (ymax) *ymax = 1.0f; } - + return foundvert; } @@ -670,28 +670,28 @@ bool calc_fcurve_range(FCurve *fcu, float *start, float *end, if (fcu->totvert) { if (fcu->bezt) { BezTriple *bezt_first = NULL, *bezt_last = NULL; - + /* get endpoint keyframes */ get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only); - + if (bezt_first) { BLI_assert(bezt_last != NULL); - + min = min_ff(min, bezt_first->vec[1][0]); max = max_ff(max, bezt_last->vec[1][0]); - + foundvert = true; } } else if (fcu->fpt) { min = min_ff(min, fcu->fpt[0].vec[0]); max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]); - + foundvert = true; } - + } - + if (foundvert == false) { min = max = 0.0f; } @@ -711,7 +711,7 @@ bool calc_fcurve_range(FCurve *fcu, float *start, float *end, /* ----------------- Status Checks -------------------------- */ -/* Are keyframes on F-Curve of any use? +/* Are keyframes on F-Curve of any use? * Usability of keyframes refers to whether they should be displayed, * and also whether they will have any influence on the final result. */ @@ -720,11 +720,11 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) /* F-Curve must exist */ if (fcu == NULL) return false; - + /* F-Curve must not have samples - samples are mutually exclusive of keyframes */ if (fcu->fpt) return false; - + /* if it has modifiers, none of these should "drastically" alter the curve */ if (fcu->modifiers.first) { FModifier *fcm; @@ -735,7 +735,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) /* ignore if muted/disabled */ if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) continue; - + /* type checks */ switch (fcm->type) { /* clearly harmless - do nothing */ @@ -743,12 +743,12 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) case FMODIFIER_TYPE_STEPPED: case FMODIFIER_TYPE_NOISE: break; - + /* sometimes harmful - depending on whether they're "additive" or not */ case FMODIFIER_TYPE_GENERATOR: { FMod_Generator *data = (FMod_Generator *)fcm->data; - + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) return false; break; @@ -756,7 +756,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) case FMODIFIER_TYPE_FN_GENERATOR: { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; - + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) return false; break; @@ -767,7 +767,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) } } } - + /* keyframes are usable */ return true; } @@ -778,7 +778,7 @@ bool BKE_fcurve_is_protected(FCurve *fcu) ((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED))); } -/* Can keyframes be added to F-Curve? +/* Can keyframes be added to F-Curve? * Keyframes can only be added if they are already visible */ bool fcurve_is_keyframable(FCurve *fcu) @@ -786,11 +786,11 @@ bool fcurve_is_keyframable(FCurve *fcu) /* F-Curve's keyframes must be "usable" (i.e. visible + have an effect on final result) */ if (fcurve_are_keyframes_usable(fcu) == 0) return false; - + /* F-Curve must currently be editable too */ if (BKE_fcurve_is_protected(fcu)) return false; - + /* F-Curve is keyframable */ return true; } @@ -801,7 +801,7 @@ bool fcurve_is_keyframable(FCurve *fcu) void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) { CfraElem *ce, *cen; - + for (ce = lb->first; ce; ce = ce->next) { /* double key? */ if (IS_EQT(ce->cfra, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) { @@ -811,7 +811,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) /* should key be inserted before this column? */ else if (ce->cfra > bezt->vec[1][0]) break; } - + /* create a new column */ cen = MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem"); if (ce) BLI_insertlinkbefore(lb, ce, cen); @@ -826,26 +826,26 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) * data imported from BVH/Mocap files), which are specialized for use with high density datasets, * which BezTriples/Keyframe data are ill equipped to do. */ - - -/* Basic sampling callback which acts as a wrapper for evaluate_fcurve() + + +/* Basic sampling callback which acts as a wrapper for evaluate_fcurve() * 'data' arg here is unneeded here... */ float fcurve_samplingcb_evalcurve(FCurve *fcu, void *UNUSED(data), float evaltime) { /* assume any interference from drivers on the curve is intended... */ return evaluate_fcurve(fcu, evaltime); -} +} - -/* Main API function for creating a set of sampled curve data, given some callback function + +/* Main API function for creating a set of sampled curve data, given some callback function * used to retrieve the values to store. */ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb) { FPoint *fpt, *new_fpt; int cfra; - + /* sanity checks */ /* TODO: make these tests report errors using reports not printf's */ if (ELEM(NULL, fcu, sample_cb)) { @@ -856,20 +856,20 @@ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSample printf("Error: Frame range for Sampled F-Curve creation is inappropriate\n"); return; } - + /* set up sample data */ fpt = new_fpt = MEM_callocN(sizeof(FPoint) * (end - start + 1), "FPoint Samples"); - + /* use the sampling callback at 1-frame intervals from start to end frames */ for (cfra = start; cfra <= end; cfra++, fpt++) { fpt->vec[0] = (float)cfra; fpt->vec[1] = sample_cb(fcu, data, (float)cfra); } - + /* free any existing sample/keyframe data on curve */ if (fcu->bezt) MEM_freeN(fcu->bezt); if (fcu->fpt) MEM_freeN(fcu->fpt); - + /* store the samples */ fcu->bezt = NULL; fcu->fpt = new_fpt; @@ -922,7 +922,7 @@ static BezTriple *cycle_offset_triple(bool cycle, BezTriple *out, const BezTripl return out; } -/* This function recalculates the handles of an F-Curve +/* This function recalculates the handles of an F-Curve * If the BezTriples have been rearranged, sort them first before using this. */ void calchandles_fcurve(FCurve *fcu) @@ -935,7 +935,7 @@ void calchandles_fcurve(FCurve *fcu) * - need bezier keys * - only bezier-interpolation has handles (for now) */ - if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) + if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) return; /* if the first modifier is Cycles, smooth the curve through the cycle */ @@ -948,16 +948,16 @@ void calchandles_fcurve(FCurve *fcu) bezt = fcu->bezt; prev = cycle_offset_triple(cycle, &tmp, &fcu->bezt[fcu->totvert - 2], last, first); next = (bezt + 1); - + /* loop over all beztriples, adjusting handles */ while (a--) { /* clamp timing of handles to be on either side of beztriple */ if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0] = bezt->vec[1][0]; if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0] = bezt->vec[1][0]; - + /* calculate auto-handles */ BKE_nurb_handle_calc(bezt, prev, next, true, fcu->auto_smoothing); - + /* for automatic ease in and out */ if (BEZT_IS_AUTOH(bezt) && !cycle) { /* only do this on first or last beztriple */ @@ -975,7 +975,7 @@ void calchandles_fcurve(FCurve *fcu) if (prev && prev->vec[1][0] >= bezt->vec[1][0]) { prev->f5 = bezt->f5 = HD_AUTOTYPE_SPECIAL; } - + /* advance pointers for next iteration */ prev = bezt; @@ -1026,16 +1026,16 @@ void testhandles_fcurve(FCurve *fcu, const bool use_handle) void sort_time_fcurve(FCurve *fcu) { bool ok = true; - + /* keep adjusting order of beztriples until nothing moves (bubble-sort) */ while (ok) { ok = 0; - + /* currently, will only be needed when there are beztriples */ if (fcu->bezt) { BezTriple *bezt; unsigned int a; - + /* loop over ALL points to adjust position in array and recalculate handles */ for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) { /* check if thee's a next beztriple which we could try to swap with current */ @@ -1045,7 +1045,7 @@ void sort_time_fcurve(FCurve *fcu) SWAP(BezTriple, *bezt, *(bezt + 1)); ok = 1; } - + /* if either one of both of the points exceeds crosses over the keyframe time... */ if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) { /* swap handles if they have switched sides for some reason */ @@ -1066,15 +1066,15 @@ void sort_time_fcurve(FCurve *fcu) short test_time_fcurve(FCurve *fcu) { unsigned int a; - + /* sanity checks */ if (fcu == NULL) return 0; - + /* currently, only need to test beztriples */ if (fcu->bezt) { BezTriple *bezt; - + /* loop through all BezTriples, stopping when one exceeds the one after it */ for (a = 0, bezt = fcu->bezt; a < (fcu->totvert - 1); a++, bezt++) { if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) @@ -1083,14 +1083,14 @@ short test_time_fcurve(FCurve *fcu) } else if (fcu->fpt) { FPoint *fpt; - + /* loop through all FPoints, stopping when one exceeds the one after it */ for (a = 0, fpt = fcu->fpt; a < (fcu->totvert - 1); a++, fpt++) { if (fpt->vec[0] > (fpt + 1)->vec[0]) return 1; } } - + /* none need any swapping */ return 0; } @@ -1103,7 +1103,7 @@ short test_time_fcurve(FCurve *fcu) typedef struct DriverVarTypeInfo { /* evaluation callback */ float (*get_value)(ChannelDriver *driver, DriverVar *dvar); - + /* allocation of target slots */ int num_targets; /* number of target slots required */ const char *target_names[MAX_DRIVER_TARGETS]; /* UI names that should be given to the slots */ @@ -1113,7 +1113,7 @@ typedef struct DriverVarTypeInfo { /* Macro to begin definitions */ #define BEGIN_DVAR_TYPEDEF(type) \ { - + /* Macro to end definitions */ #define END_DVAR_TYPEDEF \ } @@ -1135,27 +1135,27 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) ID *id; int index = -1; float value = 0.0f; - + /* sanity check */ if (ELEM(NULL, driver, dtar)) return 0.0f; - + id = dtar_id_ensure_proxy_from(dtar->id); - + /* error check for missing pointer... */ if (id == NULL) { if (G.debug & G_DEBUG) { printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; } - + /* get RNA-pointer for the ID-block given in target */ RNA_id_pointer_create(id, &id_ptr); - + /* get property to read from, and get value as appropriate */ if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) { if (RNA_property_array_check(prop)) { @@ -1178,10 +1178,10 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) else { /* out of bounds */ if (G.debug & G_DEBUG) { - printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)", + printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)", id->name, dtar->rna_path, index); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; @@ -1212,12 +1212,12 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) if (G.debug & G_DEBUG) { printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; } - + /* if we're still here, we should be ok... */ dtar->flag &= ~DTAR_FLAG_INVALID; return value; @@ -1302,7 +1302,7 @@ static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dta /* check if the ID here is a valid object */ if (id && GS(id->name)) { Object *ob = (Object *)id; - + /* get pose, and subsequently, posechannel */ return BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); } @@ -1426,24 +1426,24 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id); bPoseChannel *pchan; float tmp_loc[3]; - + /* after the checks above, the targets should be valid here... */ BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB)); - + /* try to get posechannel */ pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); - + /* check if object or bone */ if (pchan) { /* bone */ if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { float mat[4][4]; - + /* extract transform just like how the constraints do it! */ copy_m4_m4(mat, pchan->pose_mat); BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false); - + /* ... and from that, we get our transform */ copy_v3_v3(tmp_loc, mat[3]); } @@ -1464,11 +1464,11 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* XXX: this should practically be the same as transform space... */ float mat[4][4]; - + /* extract transform just like how the constraints do it! */ copy_m4_m4(mat, ob->obmat); BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false); - + /* ... and from that, we get our transform */ copy_v3_v3(tmp_loc, mat[3]); } @@ -1482,7 +1482,7 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) copy_v3_v3(tmp_loc, ob->obmat[3]); } } - + /* copy the location to the right place */ if (tarIndex) { copy_v3_v3(loc2, tmp_loc); @@ -1492,10 +1492,10 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) } } DRIVER_TARGETS_LOOPER_END - - + + /* if we're still here, there should now be two targets to use, - * so just take the length of the vector between these points + * so just take the length of the vector between these points */ return len_v3v3(loc1, loc2); } @@ -1510,7 +1510,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) float oldEul[3] = {0.0f, 0.0f, 0.0f}; bool use_eulers = false; short rot_order = ROT_MODE_EUL; - + /* check if this target has valid data */ if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) { /* invalid target, so will not have enough targets */ @@ -1522,11 +1522,11 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) /* target should be valid now */ dtar->flag &= ~DTAR_FLAG_INVALID; } - + /* try to get posechannel */ pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); - - /* check if object or bone, and get transform matrix accordingly + + /* check if object or bone, and get transform matrix accordingly * - "useEulers" code is used to prevent the problems associated with non-uniqueness * of euler decomposition from matrices [#20870] * - localspace is for [#21384], where parent results are not wanted @@ -1539,7 +1539,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) rot_order = pchan->rotmode; use_eulers = true; } - + if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* just like how the constraints do it! */ @@ -1547,7 +1547,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false); } else { - /* specially calculate local matrix, since chan_mat is not valid + /* specially calculate local matrix, since chan_mat is not valid * since it stores delta transform of pose_mat so that deforms work * so it cannot be used here for "transform" space */ @@ -1566,7 +1566,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) rot_order = ob->rotmode; use_eulers = true; } - + if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* just like how the constraints do it! */ @@ -1583,7 +1583,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) copy_m4_m4(mat, ob->obmat); } } - + /* check which transform */ if (dtar->transChan >= MAX_DTAR_TRANSCHAN_TYPES) { /* not valid channel */ @@ -1595,22 +1595,22 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) return len_v3(mat[dtar->transChan - DTAR_TRANSCHAN_SCALEX]); } else if (dtar->transChan >= DTAR_TRANSCHAN_ROTX) { - /* extract rotation as eulers (if needed) + /* extract rotation as eulers (if needed) * - definitely if rotation order isn't eulers already * - if eulers, then we have 2 options: * a) decompose transform matrix as required, then try to make eulers from * there compatible with original values - * b) [NOT USED] directly use the original values (no decomposition) + * b) [NOT USED] directly use the original values (no decomposition) * - only an option for "transform space", if quality is really bad with a) */ float eul[3]; - + mat4_to_eulO(eul, rot_order, mat); - + if (use_eulers) { compatible_eul(eul, oldEul); } - + return eul[dtar->transChan - DTAR_TRANSCHAN_ROTX]; } else { @@ -1629,21 +1629,21 @@ static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = { {"Property"}, /* UI names for targets */ {0} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_ROT_DIFF) dvar_eval_rotDiff, /* eval callback */ 2, /* number of targets used */ {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */ {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_LOC_DIFF) dvar_eval_locDiff, /* eval callback */ 2, /* number of targets used */ {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */ {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_TRANSFORM_CHAN) dvar_eval_transChan, /* eval callback */ 1, /* number of targets used */ @@ -1670,20 +1670,20 @@ void driver_free_variable(ListBase *variables, DriverVar *dvar) /* sanity checks */ if (dvar == NULL) return; - - /* free target vars + + /* free target vars * - need to go over all of them, not just up to the ones that are used - * currently, since there may be some lingering RNA paths from + * currently, since there may be some lingering RNA paths from * previous users needing freeing */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { /* free RNA path if applicable */ if (dtar->rna_path) MEM_freeN(dtar->rna_path); } DRIVER_TARGETS_LOOPER_END - + /* remove the variable from the driver */ BLI_freelinkN(variables, dvar); } @@ -1693,7 +1693,7 @@ void driver_free_variable_ex(ChannelDriver *driver, DriverVar *dvar) { /* remove and free the driver variable */ driver_free_variable(&driver->variables, dvar); - + #ifdef WITH_PYTHON /* since driver variables are cached, the expression needs re-compiling too */ if (driver->type == DRIVER_TYPE_PYTHON) @@ -1706,10 +1706,10 @@ void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars) { BLI_assert(BLI_listbase_is_empty(dst_vars)); BLI_duplicatelist(dst_vars, src_vars); - + for (DriverVar *dvar = dst_vars->first; dvar; dvar = dvar->next) { /* need to go over all targets so that we don't leave any dangling paths */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { /* make a copy of target's rna path if available */ if (dtar->rna_path) @@ -1723,25 +1723,25 @@ void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars) void driver_change_variable_type(DriverVar *dvar, int type) { const DriverVarTypeInfo *dvti = get_dvar_typeinfo(type); - + /* sanity check */ if (ELEM(NULL, dvar, dvti)) return; - + /* set the new settings */ dvar->type = type; dvar->num_targets = dvti->num_targets; - - /* make changes to the targets based on the defines for these types + + /* make changes to the targets based on the defines for these types * NOTE: only need to make sure the ones we're using here are valid... */ DRIVER_TARGETS_USED_LOOPER(dvar) { short flags = dvti->target_flags[tarIndex]; - + /* store the flags */ dtar->flag = flags; - + /* object ID types only, or idtype not yet initialized */ if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0)) dtar->idtype = ID_OB; @@ -1758,19 +1758,19 @@ void driver_variable_name_validate(DriverVar *dvar) '/', '\\', '?', ':', ';', '<', '>', '{', '}', '[', ']', '|', ' ', '.', '\t', '\n', '\r' }; - + /* sanity checks */ if (dvar == NULL) return; - + /* clear all invalid-name flags */ dvar->flag &= ~DVAR_ALL_INVALID_FLAGS; - + /* 0) Zero-length identifiers are not allowed */ if (dvar->name[0] == '\0') { dvar->flag |= DVAR_FLAG_INVALID_EMPTY; } - + /* 1) Must start with a letter */ /* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */ if (IN_RANGE_INCL(dvar->name[0], '0', '9')) { @@ -1780,7 +1780,7 @@ void driver_variable_name_validate(DriverVar *dvar) /* NOTE: We don't allow names to start with underscores (i.e. it helps when ruling out security risks) */ dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; } - + /* 2) Must not contain invalid stuff in the middle of the string */ if (strchr(dvar->name, ' ')) { dvar->flag |= DVAR_FLAG_INVALID_HAS_SPACE; @@ -1788,17 +1788,17 @@ void driver_variable_name_validate(DriverVar *dvar) if (strchr(dvar->name, '.')) { dvar->flag |= DVAR_FLAG_INVALID_HAS_DOT; } - + /* 3) Check for special characters - Either at start, or in the middle */ for (int i = 0; i < sizeof(special_char_blacklist); i++) { char *match = strchr(dvar->name, special_char_blacklist[i]); - + if (match == dvar->name) dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; else if (match != NULL) dvar->flag |= DVAR_FLAG_INVALID_HAS_SPECIAL; } - + /* 4) Check if the name is a reserved keyword * NOTE: These won't confuse Python, but it will be impossible to use the variable * in an expression without Python misinterpreting what these are for @@ -1818,29 +1818,29 @@ void driver_variable_name_validate(DriverVar *dvar) DriverVar *driver_add_new_variable(ChannelDriver *driver) { DriverVar *dvar; - + /* sanity checks */ if (driver == NULL) return NULL; - + /* make a new variable */ dvar = MEM_callocN(sizeof(DriverVar), "DriverVar"); BLI_addtail(&driver->variables, dvar); - + /* give the variable a 'unique' name */ strcpy(dvar->name, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var")); BLI_uniquename(&driver->variables, dvar, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"), '_', offsetof(DriverVar, name), sizeof(dvar->name)); - + /* set the default type to 'single prop' */ driver_change_variable_type(dvar, DVAR_TYPE_SINGLE_PROP); - + #ifdef WITH_PYTHON /* since driver variables are cached, the expression needs re-compiling too */ if (driver->type == DRIVER_TYPE_PYTHON) driver->flag |= DRIVER_FLAG_RENAMEVAR; #endif - + /* return the target */ return dvar; } @@ -1850,12 +1850,12 @@ void fcurve_free_driver(FCurve *fcu) { ChannelDriver *driver; DriverVar *dvar, *dvarn; - + /* sanity checks */ if (ELEM(NULL, fcu, fcu->driver)) return; driver = fcu->driver; - + /* free driver targets */ for (dvar = driver->variables.first; dvar; dvar = dvarn) { dvarn = dvar->next; @@ -1877,19 +1877,19 @@ void fcurve_free_driver(FCurve *fcu) ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver) { ChannelDriver *ndriver; - + /* sanity checks */ if (driver == NULL) return NULL; - + /* copy all data */ ndriver = MEM_dupallocN(driver); ndriver->expr_comp = NULL; - + /* copy variables */ - BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */ + BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */ driver_variables_copy(&ndriver->variables, &driver->variables); - + /* return the new driver */ return ndriver; } @@ -1904,18 +1904,18 @@ float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar) /* sanity check */ if (ELEM(NULL, driver, dvar)) return 0.0f; - - /* call the relevant callbacks to get the variable value + + /* call the relevant callbacks to get the variable value * using the variable type info, storing the obtained value * in dvar->curval so that drivers can be debugged */ dvti = get_dvar_typeinfo(dvar->type); - + if (dvti && dvti->get_value) dvar->curval = dvti->get_value(driver, dvar); else dvar->curval = 0.0f; - + return dvar->curval; } @@ -1926,11 +1926,11 @@ float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar) float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime) { DriverVar *dvar; - + /* check if driver can be evaluated */ if (driver->flag & DRIVER_FLAG_INVALID) return 0.0f; - + switch (driver->type) { case DRIVER_TYPE_AVERAGE: /* average values of driver targets */ case DRIVER_TYPE_SUM: /* sum values of driver targets */ @@ -1945,13 +1945,13 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl /* more than one target, so average the values of the targets */ float value = 0.0f; int tot = 0; - + /* loop through targets, adding (hopefully we don't get any overflow!) */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { value += driver_get_variable_value(driver, dvar); tot++; } - + /* perform operations on the total if appropriate */ if (driver->type == DRIVER_TYPE_AVERAGE) driver->curval = tot ? (value / (float)tot) : 0.0f; @@ -1964,23 +1964,23 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl case DRIVER_TYPE_MAX: /* largest value */ { float value = 0.0f; - + /* loop through the variables, getting the values and comparing them to existing ones */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* get value */ float tmp_val = driver_get_variable_value(driver, dvar); - + /* store this value if appropriate */ if (dvar->prev) { /* check if greater/smaller than the baseline */ if (driver->type == DRIVER_TYPE_MAX) { /* max? */ - if (tmp_val > value) + if (tmp_val > value) value = tmp_val; } else { /* min? */ - if (tmp_val < value) + if (tmp_val < value) value = tmp_val; } } @@ -1989,7 +1989,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl value = tmp_val; } } - + /* store value in driver */ driver->curval = value; break; @@ -2020,14 +2020,14 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl } default: { - /* special 'hack' - just use stored value + /* special 'hack' - just use stored value * This is currently used as the mechanism which allows animated settings to be able * to be changed via the UI. */ break; } } - + /* return value for driver */ return driver->curval; } @@ -2041,15 +2041,15 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]) { float h1[2], h2[2], len1, len2, len, fac; - + /* calculate handle deltas */ h1[0] = v1[0] - v2[0]; h1[1] = v1[1] - v2[1]; - + h2[0] = v4[0] - v3[0]; h2[1] = v4[1] - v3[1]; - - /* calculate distances: + + /* calculate distances: * - len = span of time between keyframes * - len1 = length of handle of start key * - len2 = length of handle of end key @@ -2057,20 +2057,20 @@ void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]) len = v4[0] - v1[0]; len1 = fabsf(h1[0]); len2 = fabsf(h2[0]); - + /* if the handles have no length, no need to do any corrections */ if ((len1 + len2) == 0.0f) return; - + /* the two handles cross over each other, so force them - * apart using the proportion they overlap + * apart using the proportion they overlap */ if ((len1 + len2) > len) { fac = len / (len1 + len2); - + v2[0] = (v1[0] - fac * h1[0]); v2[1] = (v1[1] - fac * h1[1]); - + v3[0] = (v4[0] - fac * h2[0]); v3[1] = (v4[1] - fac * h2[1]); } @@ -2086,7 +2086,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) c1 = 3.0f * (q1 - q0); c2 = 3.0f * (q0 - 2.0f * q1 + q2); c3 = q3 - q0 + 3.0f * (q1 - q2); - + if (c3 != 0.0) { a = c2 / c3; b = c1 / c3; @@ -2096,21 +2096,21 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) p = b / 3 - a * a; q = (2 * a * a * a - a * b + c) / 2; d = q * q + p * p * p; - + if (d > 0.0) { t = sqrt(d); o[0] = (float)(sqrt3d(-q + t) + sqrt3d(-q - t) - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1; else return 0; } else if (d == 0.0) { t = sqrt3d(-q); o[0] = (float)(2 * t - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)(-t - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2120,13 +2120,13 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) p = cos(phi / 3); q = sqrt(3 - 3 * p * p); o[0] = (float)(2 * t * p - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)(-t * (p + q) - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) nr++; o[nr] = (float)(-t * (p - q) - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2135,18 +2135,18 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) a = c2; b = c1; c = c0; - + if (a != 0.0) { /* discriminant */ p = b * b - 4 * a * c; - + if (p > 0) { p = sqrt(p); o[0] = (float)((-b - p) / (2 * a)); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)((-b + p) / (2 * a)); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2158,7 +2158,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) } else if (b != 0.0) { o[0] = (float)(-c / b); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1; else return 0; } @@ -2166,7 +2166,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) o[0] = 0.0; return 1; } - + return 0; } } @@ -2217,13 +2217,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime unsigned int a; int b; float cvalue = 0.0f; - + /* get pointers */ a = fcu->totvert - 1; prevbezt = bezts; bezt = prevbezt + 1; lastbezt = prevbezt + a; - + /* evaluation time at or past endpoints? */ if (prevbezt->vec[1][0] >= evaltime) { /* before or on first keyframe */ @@ -2233,7 +2233,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* linear or bezier interpolation */ if (prevbezt->ipo == BEZT_IPO_LIN) { /* Use the next center point instead of our own handle for - * linear interpolated extrapolate + * linear interpolated extrapolate */ if (fcu->totvert == 1) { cvalue = prevbezt->vec[1][1]; @@ -2242,7 +2242,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime bezt = prevbezt + 1; dx = prevbezt->vec[1][0] - evaltime; fac = bezt->vec[1][0] - prevbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac; @@ -2259,7 +2259,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ dx = prevbezt->vec[1][0] - evaltime; fac = prevbezt->vec[1][0] - prevbezt->vec[0][0]; - + /* prevent division by zero */ if (fac) { fac = (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac; @@ -2271,8 +2271,8 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } else { - /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, - * so just extend first keyframe's value + /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, + * so just extend first keyframe's value */ cvalue = prevbezt->vec[1][1]; } @@ -2285,7 +2285,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* linear or bezier interpolation */ if (lastbezt->ipo == BEZT_IPO_LIN) { /* Use the next center point instead of our own handle for - * linear interpolated extrapolate + * linear interpolated extrapolate */ if (fcu->totvert == 1) { cvalue = lastbezt->vec[1][1]; @@ -2294,7 +2294,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime prevbezt = lastbezt - 1; dx = evaltime - lastbezt->vec[1][0]; fac = lastbezt->vec[1][0] - prevbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac; @@ -2311,7 +2311,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ dx = evaltime - lastbezt->vec[1][0]; fac = lastbezt->vec[2][0] - lastbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac; @@ -2323,8 +2323,8 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } else { - /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, - * so just extend last keyframe's value + /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, + * so just extend last keyframe's value */ cvalue = lastbezt->vec[1][1]; } @@ -2332,9 +2332,9 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime else { /* evaltime occurs somewhere in the middle of the curve */ bool exact = false; - + /* Use binary search to find appropriate keyframes... - * + * * The threshold here has the following constraints: * - 0.001 is too coarse -> We get artifacts with 2cm driver movements at 1BU = 1m (see T40332) * - 0.00001 is too fine -> Weird errors, like selecting the wrong keyframe range (see T39207), occur. @@ -2342,9 +2342,9 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ a = binarysearch_bezt_index_ex(bezts, evaltime, fcu->totvert, 0.0001, &exact); if (G.debug & G_DEBUG) printf("eval fcurve '%s' - %f => %u/%u, %d\n", fcu->rna_path, evaltime, a, fcu->totvert, exact); - + if (exact) { - /* index returned must be interpreted differently when it sits on top of an existing keyframe + /* index returned must be interpreted differently when it sits on top of an existing keyframe * - that keyframe is the start of the segment we need (see action_bug_2.blend in T39207) */ prevbezt = bezts + a; @@ -2357,7 +2357,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime bezt = bezts + a; prevbezt = (a > 0) ? (bezt - 1) : bezt; } - + /* use if the key is directly on the frame, rare cases this is needed else we get 0.0 instead. */ /* XXX: consult T39207 for examples of files where failure of these checks can cause issues */ if (exact) { @@ -2374,7 +2374,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime const float time = evaltime - prevbezt->vec[1][0]; const float amplitude = prevbezt->amplitude; const float period = prevbezt->period; - + /* value depends on interpolation mode */ if ((prevbezt->ipo == BEZT_IPO_CONST) || (fcu->flag & FCURVE_DISCRETE_VALUES) || (duration == 0)) { /* constant (evaltime not relevant, so no interpolation needed) */ @@ -2395,7 +2395,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime v3[1] = bezt->vec[0][1]; v4[0] = bezt->vec[1][0]; v4[1] = bezt->vec[1][1]; - + if (fabsf(v1[1] - v4[1]) < FLT_EPSILON && fabsf(v2[1] - v3[1]) < FLT_EPSILON && fabsf(v3[1] - v4[1]) < FLT_EPSILON) @@ -2408,7 +2408,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime else { /* adjust handles so that they don't overlap (forming a loop) */ correct_bezpart(v1, v2, v3, v4); - + /* try to get a value for this position - if failure, try another set of points */ b = findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl); if (b) { @@ -2421,12 +2421,12 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } break; - + case BEZT_IPO_LIN: /* linear - simply linearly interpolate between values of the two keyframes */ cvalue = BLI_easing_linear_ease(time, begin, change, duration); break; - + /* easing ............................................ */ case BEZT_IPO_BACK: switch (prevbezt->easing) { @@ -2439,13 +2439,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_back_ease_in_out(time, begin, change, duration, prevbezt->back); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back); break; } break; - + case BEZT_IPO_BOUNCE: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2457,13 +2457,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_bounce_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration); break; } break; - + case BEZT_IPO_CIRC: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2475,7 +2475,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_circ_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_circ_ease_in(time, begin, change, duration); break; @@ -2493,13 +2493,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_cubic_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_ELASTIC: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2511,13 +2511,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_elastic_ease_in_out(time, begin, change, duration, amplitude, period); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period); break; } break; - + case BEZT_IPO_EXPO: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2529,13 +2529,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_expo_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_expo_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUAD: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2547,13 +2547,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quad_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quad_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUART: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2565,13 +2565,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quart_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quart_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUINT: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2583,13 +2583,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quint_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quint_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_SINE: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2601,14 +2601,14 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_sine_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_sine_ease_in(time, begin, change, duration); break; } break; - - + + default: cvalue = prevbezt->vec[1][1]; break; @@ -2619,7 +2619,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime if (G.debug & G_DEBUG) printf(" ERROR: failed eval - p=%f b=%f, t=%f (%f)\n", prevbezt->vec[1][0], bezt->vec[1][0], evaltime, fabsf(bezt->vec[1][0] - evaltime)); } } - + /* return value */ return cvalue; } @@ -2629,11 +2629,11 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) { FPoint *prevfpt, *lastfpt, *fpt; float cvalue = 0.0f; - + /* get pointers */ prevfpt = fpts; lastfpt = prevfpt + fcu->totvert - 1; - + /* evaluation time at or past endpoints? */ if (prevfpt->vec[0] >= evaltime) { /* before or on first sample, so just extend value */ @@ -2645,24 +2645,24 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) } else { float t = fabsf(evaltime - floorf(evaltime)); - + /* find the one on the right frame (assume that these are spaced on 1-frame intervals) */ fpt = prevfpt + ((int)evaltime - (int)prevfpt->vec[0]); - + /* if not exactly on the frame, perform linear interpolation with the next one */ if ((t != 0.0f) && (t < 1.0f)) cvalue = interpf(fpt->vec[1], (fpt + 1)->vec[1], 1.0f - t); else cvalue = fpt->vec[1]; } - + /* return value */ return cvalue; } /* ***************************** F-Curve - Evaluation ********************************* */ -/* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") +/* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") * Note: this is also used for drivers */ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) @@ -2673,16 +2673,16 @@ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) /* evaluate modifiers which modify time to evaluate the base curve at */ storage = evaluate_fmodifiers_storage_new(&fcu->modifiers); devaltime = evaluate_time_fmodifiers(storage, &fcu->modifiers, fcu, cvalue, evaltime); - - /* evaluate curve-data - * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying + + /* evaluate curve-data + * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying * F-Curve modifier on the stack requested the curve to be evaluated at */ if (fcu->bezt) cvalue = fcurve_eval_keyframes(fcu, fcu->bezt, devaltime); else if (fcu->fpt) cvalue = fcurve_eval_samples(fcu, fcu->fpt, devaltime); - + /* evaluate modifiers */ evaluate_value_fmodifiers(storage, &fcu->modifiers, fcu, &cvalue, devaltime); @@ -2693,7 +2693,7 @@ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) */ if (fcu->flag & FCURVE_INT_VALUES) cvalue = floorf(cvalue + 0.5f); - + /* return evaluated value */ return cvalue; } @@ -2753,7 +2753,7 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evalt /* Calculate the value of the given F-Curve at the given frame, and set its curval */ float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) { - /* only calculate + set curval (overriding the existing value) if curve has + /* only calculate + set curval (overriding the existing value) if curve has * any data which warrants this... */ if ((fcu->totvert) || (fcu->driver && !(fcu->driver->flag & DRIVER_FLAG_INVALID)) || @@ -2774,4 +2774,3 @@ float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) return 0.0f; } } - diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c index 7dc6e3575b2e..0487302d9b62 100644 --- a/source/blender/blenkernel/intern/fluidsim.c +++ b/source/blender/blenkernel/intern/fluidsim.c @@ -104,4 +104,3 @@ void initElbeemMesh(struct Scene *scene, struct Object *ob, dm->release(dm); } - diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index f3d0a5fe085d..b69bce088d2b 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -67,7 +67,7 @@ void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm); * times. In addition to this, each modifier should have a type-info struct, where * its functions are attached for use. */ - + /* Template for type-info data: * - make a copy of this when creating new modifiers, and just change the functions * pointed to as necessary @@ -110,7 +110,7 @@ static FModifierTypeInfo FMI_MODNAME = { static void fcm_generator_free(FModifier *fcm) { FMod_Generator *data = (FMod_Generator *)fcm->data; - + /* free polynomial coefficients array */ if (data->coefficients) MEM_freeN(data->coefficients); @@ -120,7 +120,7 @@ static void fcm_generator_copy(FModifier *fcm, const FModifier *src) { FMod_Generator *gen = (FMod_Generator *)fcm->data; FMod_Generator *ogen = (FMod_Generator *)src->data; - + /* copy coefficients array? */ if (ogen->coefficients) gen->coefficients = MEM_dupallocN(ogen->coefficients); @@ -130,19 +130,19 @@ static void fcm_generator_new_data(void *mdata) { FMod_Generator *data = (FMod_Generator *)mdata; float *cp; - + /* set default generator to be linear 0-1 (gradient = 1, y-offset = 0) */ data->poly_order = 1; data->arraysize = 2; cp = data->coefficients = MEM_callocN(sizeof(float) * 2, "FMod_Generator_Coefs"); - cp[0] = 0; // y-offset + cp[0] = 0; // y-offset cp[1] = 1; // gradient } static void fcm_generator_verify(FModifier *fcm) { FMod_Generator *data = (FMod_Generator *)fcm->data; - + /* requirements depend on mode */ switch (data->mode) { case FCM_GENERATOR_POLYNOMIAL: /* expanded polynomial expression */ @@ -173,8 +173,8 @@ static void fcm_generator_verify(FModifier *fcm) static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime) { FMod_Generator *data = (FMod_Generator *)fcm->data; - - /* behavior depends on mode + + /* behavior depends on mode * NOTE: the data in its default state is fine too */ switch (data->mode) { @@ -184,8 +184,8 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c float *powers = MEM_callocN(sizeof(float) * data->arraysize, "Poly Powers"); float value = 0.0f; unsigned int i; - - /* for each x^n, precalculate value based on previous one first... this should be + + /* for each x^n, precalculate value based on previous one first... this should be * faster that calling pow() for each entry */ for (i = 0; i < data->arraysize; i++) { @@ -195,11 +195,11 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c else powers[0] = 1; } - + /* for each coefficient, add to value, which we'll write to *cvalue in one go */ for (i = 0; i < data->arraysize; i++) value += data->coefficients[i] * powers[i]; - + /* only if something changed, write *cvalue in one go */ if (data->poly_order) { if (data->flag & FCM_GENERATOR_ADDITIVE) @@ -207,9 +207,9 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c else *cvalue = value; } - + /* cleanup */ - if (powers) + if (powers) MEM_freeN(powers); break; } @@ -217,11 +217,11 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c { float value = 1.0f, *cp = NULL; unsigned int i; - + /* for each coefficient pair, solve for that bracket before accumulating in value by multiplying */ for (cp = data->coefficients, i = 0; (cp) && (i < (unsigned int)data->poly_order); cp += 2, i++) value *= (cp[0] * evaltime + cp[1]); - + /* only if something changed, write *cvalue in one go */ if (data->poly_order) { if (data->flag & FCM_GENERATOR_ADDITIVE) @@ -266,7 +266,7 @@ static FModifierTypeInfo FMI_GENERATOR = { static void fcm_fn_generator_new_data(void *mdata) { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)mdata; - + /* set amplitude and phase multiplier to 1.0f so that something is generated */ data->amplitude = 1.0f; data->phase_multiplier = 1.0f; @@ -289,9 +289,9 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; double arg = data->phase_multiplier * evaltime + data->phase_offset; double (*fn)(double v) = NULL; - + /* get function pointer to the func to use: - * WARNING: must perform special argument validation hereto guard against crashes + * WARNING: must perform special argument validation hereto guard against crashes */ switch (data->type) { /* simple ones */ @@ -304,7 +304,7 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float case FCM_GENERATOR_FN_SINC: /* normalized sine wave */ fn = sinc; break; - + /* validation required */ case FCM_GENERATOR_FN_TAN: /* tangent wave */ { @@ -346,11 +346,11 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float break; } - + /* execute function callback to set value if appropriate */ if (fn) { float value = (float)(data->amplitude * (float)fn(arg) + data->value_offset); - + if (data->flag & FCM_GENERATOR_ADDITIVE) *cvalue += value; else @@ -380,7 +380,7 @@ static FModifierTypeInfo FMI_FN_GENERATOR = { static void fcm_envelope_free(FModifier *fcm) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; - + /* free envelope data array */ if (env->data) MEM_freeN(env->data); @@ -390,7 +390,7 @@ static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; FMod_Envelope *oenv = (FMod_Envelope *)src->data; - + /* copy envelope data array */ if (oenv->data) env->data = MEM_dupallocN(oenv->data); @@ -399,7 +399,7 @@ static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) static void fcm_envelope_new_data(void *mdata) { FMod_Envelope *env = (FMod_Envelope *)mdata; - + /* set default min/max ranges */ env->min = -1.0f; env->max = 1.0f; @@ -408,7 +408,7 @@ static void fcm_envelope_new_data(void *mdata) static void fcm_envelope_verify(FModifier *fcm) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; - + /* if the are points, perform bubble-sort on them, as user may have changed the order */ if (env->data) { /* XXX todo... */ @@ -421,13 +421,13 @@ static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cv FCM_EnvelopeData *fed, *prevfed, *lastfed; float min = 0.0f, max = 0.0f, fac = 0.0f; int a; - + /* get pointers */ if (env->data == NULL) return; prevfed = env->data; fed = prevfed + 1; lastfed = prevfed + (env->totvert - 1); - + /* get min/max values for envelope at evaluation time (relative to mid-value) */ if (prevfed->time >= evaltime) { /* before or on first sample, so just extend value */ @@ -446,20 +446,20 @@ static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cv /* evaltime occurs within the interval defined by these two envelope points */ if ((prevfed->time <= evaltime) && (fed->time >= evaltime)) { float afac, bfac, diff; - + diff = fed->time - prevfed->time; afac = (evaltime - prevfed->time) / diff; bfac = (fed->time - evaltime) / diff; - + min = bfac * prevfed->min + afac * fed->min; max = bfac * prevfed->max + afac * fed->max; - + break; } } } - - /* adjust *cvalue + + /* adjust *cvalue * - fac is the ratio of how the current y-value corresponds to the reference range * - thus, the new value is found by mapping the old range to the new! */ @@ -572,7 +572,7 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], float frame, int array /* Cycles F-Curve Modifier --------------------------- */ -/* This modifier changes evaltime to something that exists within the curve's frame-range, +/* This modifier changes evaltime to something that exists within the curve's frame-range, * then re-evaluates modifier stack up to this point using the new time. This re-entrant behavior * is very likely to be more time-consuming than the original approach... (which was tightly integrated into * the calculation code...). @@ -588,11 +588,11 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], float frame, int array typedef struct tFCMED_Cycles { float cycyofs; /* y-offset to apply */ } tFCMED_Cycles; - + static void fcm_cycles_new_data(void *mdata) { FMod_Cycles *data = (FMod_Cycles *)mdata; - + /* turn on cycles by default */ data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC; } @@ -605,38 +605,38 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif short side = 0, mode = 0; int cycles = 0; float ofs = 0; - + /* check if modifier is first in stack, otherwise disable ourself... */ /* FIXME... */ if (fcm->prev) { fcm->flag |= FMODIFIER_FLAG_DISABLED; return evaltime; } - + /* calculate new evaltime due to cyclic interpolation */ if (fcu && fcu->bezt) { BezTriple *prevbezt = fcu->bezt; BezTriple *lastbezt = prevbezt + fcu->totvert - 1; - + prevkey[0] = prevbezt->vec[1][0]; prevkey[1] = prevbezt->vec[1][1]; - + lastkey[0] = lastbezt->vec[1][0]; lastkey[1] = lastbezt->vec[1][1]; } else if (fcu && fcu->fpt) { FPoint *prevfpt = fcu->fpt; FPoint *lastfpt = prevfpt + fcu->totvert - 1; - + prevkey[0] = prevfpt->vec[0]; prevkey[1] = prevfpt->vec[1]; - + lastkey[0] = lastfpt->vec[0]; lastkey[1] = lastfpt->vec[1]; } else return evaltime; - + /* check if modifier will do anything * 1) if in data range, definitely don't do anything * 2) if before first frame or after last frame, make sure some cycling is in use @@ -659,26 +659,26 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } if ((ELEM(0, side, mode))) return evaltime; - + /* find relative place within a cycle */ { float cycdx = 0, cycdy = 0; float cycle = 0, cyct = 0; - + /* calculate period and amplitude (total height) of a cycle */ cycdx = lastkey[0] - prevkey[0]; cycdy = lastkey[1] - prevkey[1]; - + /* check if cycle is infinitely small, to be point of being impossible to use */ if (cycdx == 0) return evaltime; - + /* calculate the 'number' of the cycle */ cycle = ((float)side * (evaltime - ofs) / cycdx); - + /* calculate the time inside the cycle */ cyct = fmod(evaltime - ofs, cycdx); - + /* check that cyclic is still enabled for the specified time */ if (cycles == 0) { /* catch this case so that we don't exit when we have (cycles = 0) @@ -687,11 +687,11 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } else if (cycle > cycles) { /* we are too far away from range to evaluate - * TODO: but we should still hold last value... + * TODO: but we should still hold last value... */ return evaltime; } - + /* check if 'cyclic extrapolation', and thus calculate y-offset for this cycle */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { if (side < 0) @@ -700,17 +700,17 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif cycyofs = (float)ceil((evaltime - ofs) / cycdx); cycyofs *= cycdy; } - + /* special case for cycle start/end */ if (cyct == 0.0f) { evaltime = (side == 1 ? lastkey[0] : prevkey[0]); - + if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)cycle % 2)) evaltime = (side == 1 ? prevkey[0] : lastkey[0]); } /* calculate where in the cycle we are (overwrite evaltime to reflect this) */ else if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)(cycle + 1) % 2)) { - /* when 'mirror' option is used and cycle number is odd, this cycle is played in reverse + /* when 'mirror' option is used and cycle number is odd, this cycle is played in reverse * - for 'before' extrapolation, we need to flip in a different way, otherwise values past * then end of the curve get referenced (result of fmod will be negative, and with different phase) */ @@ -725,22 +725,22 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } if (evaltime < prevkey[0]) evaltime += cycdx; } - + /* store temp data if needed */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { tFCMED_Cycles *edata; - + /* for now, this is just a float, but we could get more stuff... */ edata = MEM_callocN(sizeof(tFCMED_Cycles), "tFCMED_Cycles"); edata->cycyofs = cycyofs; fmodifiers_storage_put(storage, fcm, edata); } - + /* return the new frame to evaluate */ return evaltime; } - + static void fcm_cycles_evaluate(FModifierStackStorage *storage, FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float UNUSED(evaltime)) { @@ -750,7 +750,7 @@ static void fcm_cycles_evaluate(FModifierStackStorage *storage, FCurve *UNUSED(f if (edata) { /* add cyclic offset - no need to check for now, otherwise the data wouldn't exist! */ *cvalue += edata->cycyofs; - + /* free temp data */ MEM_freeN(edata); fmodifiers_storage_remove(storage, fcm); @@ -779,7 +779,7 @@ static FModifierTypeInfo FMI_CYCLES = { static void fcm_noise_new_data(void *mdata) { FMod_Noise *data = (FMod_Noise *)mdata; - + /* defaults */ data->size = 1.0f; data->strength = 1.0f; @@ -788,18 +788,18 @@ static void fcm_noise_new_data(void *mdata) data->depth = 0; data->modification = FCM_NOISE_MODIF_REPLACE; } - + static void fcm_noise_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime) { FMod_Noise *data = (FMod_Noise *)fcm->data; float noise; - + /* generate noise using good ol' Blender Noise * - 0.1 is passed as the 'z' value, otherwise evaluation fails for size = phase = 1 * with evaltime being an integer (which happens when evaluating on frame by frame basis) */ noise = BLI_turbulence(data->size, evaltime - data->offset, data->phase, 0.1f, data->depth); - + /* combine the noise with existing motion data */ switch (data->modification) { case FCM_NOISE_MODIF_ADD: @@ -837,7 +837,7 @@ static FModifierTypeInfo FMI_NOISE = { /* Filter F-Curve Modifier --------------------------- */ -#if 0 // XXX not yet implemented +#if 0 // XXX not yet implemented static FModifierTypeInfo FMI_FILTER = { FMODIFIER_TYPE_FILTER, /* type */ sizeof(FMod_Filter), /* size */ @@ -862,7 +862,7 @@ static FModifierTypeInfo FMI_FILTER = { static void fcm_python_free(FModifier *fcm) { FMod_Python *data = (FMod_Python *)fcm->data; - + /* id-properties */ IDP_FreeProperty(data->prop); MEM_freeN(data->prop); @@ -871,7 +871,7 @@ static void fcm_python_free(FModifier *fcm) static void fcm_python_new_data(void *mdata) { FMod_Python *data = (FMod_Python *)mdata; - + /* everything should be set correctly by calloc, except for the prop->type constant.*/ data->prop = MEM_callocN(sizeof(IDProperty), "PyFModifierProps"); data->prop->type = IDP_GROUP; @@ -881,7 +881,7 @@ static void fcm_python_copy(FModifier *fcm, const FModifier *src) { FMod_Python *pymod = (FMod_Python *)fcm->data; FMod_Python *opymod = (FMod_Python *)src->data; - + pymod->prop = IDP_CopyProperty(opymod->prop); } @@ -889,9 +889,9 @@ static void fcm_python_evaluate(FCurve *UNUSED(fcu), FModifier *UNUSED(fcm), flo { #ifdef WITH_PYTHON //FMod_Python *data = (FMod_Python *)fcm->data; - + /* FIXME... need to implement this modifier... - * It will need it execute a script using the custom properties + * It will need it execute a script using the custom properties */ #endif /* WITH_PYTHON */ } @@ -919,13 +919,13 @@ static FModifierTypeInfo FMI_PYTHON = { static float fcm_limits_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(cvalue), float evaltime) { FMod_Limits *data = (FMod_Limits *)fcm->data; - + /* check for the time limits */ if ((data->flag & FCM_LIMIT_XMIN) && (evaltime < data->rect.xmin)) return data->rect.xmin; if ((data->flag & FCM_LIMIT_XMAX) && (evaltime > data->rect.xmax)) return data->rect.xmax; - + /* modifier doesn't change time */ return evaltime; } @@ -933,7 +933,7 @@ static float fcm_limits_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(c static void fcm_limits_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float UNUSED(evaltime)) { FMod_Limits *data = (FMod_Limits *)fcm->data; - + /* value limits now */ if ((data->flag & FCM_LIMIT_YMIN) && (*cvalue < data->rect.ymin)) *cvalue = data->rect.ymin; @@ -944,7 +944,7 @@ static void fcm_limits_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cval static FModifierTypeInfo FMI_LIMITS = { FMODIFIER_TYPE_LIMITS, /* type */ sizeof(FMod_Limits), /* size */ - FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ + FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Limits"), /* name */ "FMod_Limits", /* struct name */ @@ -963,7 +963,7 @@ static FModifierTypeInfo FMI_LIMITS = { static void fcm_stepped_new_data(void *mdata) { FMod_Stepped *data = (FMod_Stepped *)mdata; - + /* just need to set the step-size to 2-frames by default */ /* XXX: or would 5 be more normal? */ data->step_size = 2.0f; @@ -973,7 +973,7 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( { FMod_Stepped *data = (FMod_Stepped *)fcm->data; int snapblock; - + /* check range clamping to see if we should alter the timing to achieve the desired results */ if (data->flag & FCM_STEPPED_NO_BEFORE) { if (evaltime < data->start_frame) @@ -983,15 +983,15 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( if (evaltime > data->end_frame) return evaltime; } - - /* we snap to the start of the previous closest block of 'step_size' frames - * after the start offset has been discarded + + /* we snap to the start of the previous closest block of 'step_size' frames + * after the start offset has been discarded * - i.e. round down */ snapblock = (int)((evaltime - data->offset) / data->step_size); - - /* reapply the offset, and multiple the snapblock by the size of the steps to get - * the new time to evaluate at + + /* reapply the offset, and multiple the snapblock by the size of the steps to get + * the new time to evaluate at */ return ((float)snapblock * data->step_size) + data->offset; } @@ -999,7 +999,7 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( static FModifierTypeInfo FMI_STEPPED = { FMODIFIER_TYPE_STEPPED, /* type */ sizeof(FMod_Limits), /* size */ - FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ + FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Stepped"), /* name */ "FMod_Stepped", /* struct name */ @@ -1047,7 +1047,7 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) fmods_init_typeinfo(); FMI_INIT = 0; } - + /* only return for valid types */ if ((type >= FMODIFIER_TYPE_NULL) && (type < FMODIFIER_NUM_TYPES)) @@ -1058,10 +1058,10 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) else { printf("No valid F-Curve Modifier type-info data available. Type = %i\n", type); } - + return NULL; -} - +} + /* This function should always be used to get the appropriate type-info, as it * has checks which prevent segfaults in some weird cases. */ @@ -1081,11 +1081,11 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) { const FModifierTypeInfo *fmi = get_fmodifier_typeinfo(type); FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, fmi)) return NULL; - + /* special checks for whether modifier can be added */ if ((modifiers->first) && (type == FMODIFIER_TYPE_CYCLES)) { /* cycles modifier must be first in stack, so for now, don't add if it can't be */ @@ -1093,7 +1093,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) printf("Error: Cannot add 'Cycles' modifier to F-Curve, as 'Cycles' modifier can only be first in stack.\n"); return NULL; } - + /* add modifier itself */ fcm = MEM_callocN(sizeof(FModifier), "F-Curve Modifier"); fcm->type = type; @@ -1101,14 +1101,14 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) fcm->curve = owner_fcu; fcm->influence = 1.0f; BLI_addtail(modifiers, fcm); - + /* tag modifier as "active" if no other modifiers exist in the stack yet */ if (BLI_listbase_is_single(modifiers)) fcm->flag |= FMODIFIER_FLAG_ACTIVE; - + /* add modifier's data */ fcm->data = MEM_callocN(fmi->size, fmi->structName); - + /* init custom settings if necessary */ if (fmi->new_data) fmi->new_data(fcm->data); @@ -1116,7 +1116,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) /* update the fcurve if the Cycles modifier is added */ if ((owner_fcu) && (type == FMODIFIER_TYPE_CYCLES)) calchandles_fcurve(owner_fcu); - + /* return modifier for further editing */ return fcm; } @@ -1126,23 +1126,23 @@ FModifier *copy_fmodifier(const FModifier *src) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(src); FModifier *dst; - + /* sanity check */ if (src == NULL) return NULL; - + /* copy the base data, clearing the links */ dst = MEM_dupallocN(src); dst->next = dst->prev = NULL; dst->curve = NULL; - + /* make a new copy of the F-Modifier's data */ dst->data = MEM_dupallocN(src->data); - + /* only do specific constraints if required */ if (fmi && fmi->copy_data) fmi->copy_data(dst, src); - + /* return the new modifier */ return dst; } @@ -1151,20 +1151,20 @@ FModifier *copy_fmodifier(const FModifier *src) void copy_fmodifiers(ListBase *dst, const ListBase *src) { FModifier *fcm, *srcfcm; - + if (ELEM(NULL, dst, src)) return; - + BLI_listbase_clear(dst); BLI_duplicatelist(dst, src); - + for (fcm = dst->first, srcfcm = src->first; fcm && srcfcm; srcfcm = srcfcm->next, fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - + /* make a new copy of the F-Modifier's data */ fcm->data = MEM_dupallocN(fcm->data); fcm->curve = NULL; - + /* only do specific constraints if required */ if (fmi && fmi->copy_data) fmi->copy_data(fcm, srcfcm); @@ -1175,11 +1175,11 @@ void copy_fmodifiers(ListBase *dst, const ListBase *src) bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - + /* sanity check */ if (fcm == NULL) return false; - + /* removing the cycles modifier requires a handle update */ FCurve *update_fcu = (fcm->type == FMODIFIER_TYPE_CYCLES) ? fcm->curve : NULL; @@ -1187,11 +1187,11 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) if (fcm->data) { if (fmi && fmi->free_data) fmi->free_data(fcm); - + /* free modifier's data (fcm->data) */ MEM_freeN(fcm->data); } - + /* remove modifier from stack */ if (modifiers) { BLI_freelinkN(modifiers, fcm); @@ -1214,11 +1214,11 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) void free_fmodifiers(ListBase *modifiers) { FModifier *fcm, *fmn; - + /* sanity check */ if (modifiers == NULL) return; - + /* free each modifier in order - modifier is unlinked from list and freed */ for (fcm = modifiers->first; fcm; fcm = fmn) { fmn = fcm->next; @@ -1230,17 +1230,17 @@ void free_fmodifiers(ListBase *modifiers) FModifier *find_active_fmodifier(ListBase *modifiers) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return NULL; - + /* loop over modifiers until 'active' one is found */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { if (fcm->flag & FMODIFIER_FLAG_ACTIVE) return fcm; } - + /* no modifier is active */ return NULL; } @@ -1249,55 +1249,55 @@ FModifier *find_active_fmodifier(ListBase *modifiers) void set_active_fmodifier(ListBase *modifiers, FModifier *fcm) { FModifier *fm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return; - + /* deactivate all, and set current one active */ for (fm = modifiers->first; fm; fm = fm->next) fm->flag &= ~FMODIFIER_FLAG_ACTIVE; - + /* make given modifier active */ if (fcm) fcm->flag |= FMODIFIER_FLAG_ACTIVE; } -/* Do we have any modifiers which match certain criteria +/* Do we have any modifiers which match certain criteria * - mtype - type of modifier (if 0, doesn't matter) * - acttype - type of action to perform (if -1, doesn't matter) */ bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype) { FModifier *fcm; - + /* if there are no specific filtering criteria, just skip */ if ((mtype == 0) && (acttype == 0)) return (modifiers && modifiers->first); - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return false; - + /* find the first mdifier fitting these criteria */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); short mOk = 1, aOk = 1; /* by default 1, so that when only one test, won't fail */ - + /* check if applicable ones are fullfilled */ if (mtype) mOk = (fcm->type == mtype); if (acttype > -1) aOk = (fmi->acttype == acttype); - + /* if both are ok, we've found a hit */ if (mOk && aOk) return true; } - + /* no matches */ return false; -} +} /* Evaluation API --------------------------- */ @@ -1359,19 +1359,19 @@ void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm) static float eval_fmodifier_influence(FModifier *fcm, float evaltime) { float influence; - + /* sanity check */ - if (fcm == NULL) + if (fcm == NULL) return 0.0f; - - /* should we use influence stored in modifier or not + + /* should we use influence stored in modifier or not * NOTE: this is really just a hack so that we don't need to version patch old files ;) */ if (fcm->flag & FMODIFIER_FLAG_USEINFLUENCE) influence = fcm->influence; else influence = 1.0f; - + /* restricted range or full range? */ if (fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) { if ((evaltime <= fcm->sfra) || (evaltime >= fcm->efra)) { @@ -1391,7 +1391,7 @@ static float eval_fmodifier_influence(FModifier *fcm, float evaltime) return influence * (evaltime - a) / (b - a); } } - + /* just return the influence of the modifier */ return influence; } @@ -1411,7 +1411,7 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie FCurve *fcu, float cvalue, float evaltime) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->last)) return evaltime; @@ -1419,22 +1419,22 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie if (fcu && fcu->flag & FCURVE_MOD_OFF) return evaltime; - /* Starting from the end of the stack, calculate the time effects of various stacked modifiers - * on the time the F-Curve should be evaluated at. + /* Starting from the end of the stack, calculate the time effects of various stacked modifiers + * on the time the F-Curve should be evaluated at. * * This is done in reverse order to standard evaluation, as when this is done in standard * order, each modifier would cause jumps to other points in the curve, forcing all - * previous ones to be evaluated again for them to be correct. However, if we did in the + * previous ones to be evaluated again for them to be correct. However, if we did in the * reverse order as we have here, we can consider them a macro to micro type of waterfall * effect, which should get us the desired effects when using layered time manipulations * (such as multiple 'stepped' modifiers in sequence, causing different stepping rates) */ for (fcm = modifiers->last; fcm; fcm = fcm->prev) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - - if (fmi == NULL) + + if (fmi == NULL) continue; - + /* if modifier cannot be applied on this frame (whatever scale it is on, it won't affect the results) * hence we shouldn't bother seeing what it would do given the chance */ @@ -1453,13 +1453,13 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie else { nval = fmi->evaluate_modifier_time_storage(storage, fcu, fcm, cvalue, evaltime); } - + evaltime = interpf(nval, evaltime, influence); } } } } - + /* return the modified evaltime */ return evaltime; } @@ -1471,21 +1471,21 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie FCurve *fcu, float *cvalue, float evaltime) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return; if (fcu->flag & FCURVE_MOD_OFF) return; - + /* evaluate modifiers */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - - if (fmi == NULL) + + if (fmi == NULL) continue; - + /* only evaluate if there's a callback for this, and if F-Modifier can be evaluated on this frame */ if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 || ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime)) ) @@ -1507,7 +1507,7 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie } } } -} +} /* ---------- */ @@ -1517,24 +1517,24 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie void fcurve_bake_modifiers(FCurve *fcu, int start, int end) { ChannelDriver *driver; - + /* sanity checks */ /* TODO: make these tests report errors using reports not printf's */ if (ELEM(NULL, fcu, fcu->modifiers.first)) { printf("Error: No F-Curve with F-Curve Modifiers to Bake\n"); return; } - + /* temporarily, disable driver while we sample, so that they don't influence the outcome */ driver = fcu->driver; fcu->driver = NULL; - + /* bake the modifiers, by sampling the curve at each frame */ fcurve_store_samples(fcu, NULL, start, end, fcurve_samplingcb_evalcurve); - + /* free the modifiers now */ free_fmodifiers(&fcu->modifiers); - + /* restore driver */ fcu->driver = driver; } diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 73199cebe36b..cf2521509b55 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -148,7 +148,7 @@ static PackedFile *get_builtin_packedfile(void) void *mem = MEM_mallocN(builtin_font_size, "vfd_builtin"); memcpy(mem, builtin_font_data, builtin_font_size); - + return newPackedFileMemory(mem, builtin_font_size); } } @@ -205,7 +205,7 @@ static VFontData *vfont_get_data(VFont *vfont) pf = get_builtin_packedfile(); } } - + if (pf) { vfont->data = BLI_vfontdata_from_freetypefont(pf); if (pf != vfont->packedfile) { @@ -246,10 +246,10 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) PackedFile *pf; PackedFile *temp_pf = NULL; bool is_builtin; - + if (STREQ(filepath, FO_BUILTIN_NAME)) { BLI_strncpy(filename, filepath, sizeof(filename)); - + pf = get_builtin_packedfile(); is_builtin = true; } @@ -257,7 +257,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) BLI_split_file_part(filepath, filename, sizeof(filename)); pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain)); temp_pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain)); - + is_builtin = false; } @@ -291,7 +291,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) freePackedFile(pf); } } - + return vfont; } @@ -348,13 +348,13 @@ static VFont *which_vfont(Curve *cu, CharInfo *info) VFont *BKE_vfont_builtin_get(void) { VFont *vfont; - + for (vfont = G_MAIN->vfont.first; vfont; vfont = vfont->id.next) { if (BKE_vfont_is_builtin(vfont)) { return vfont; } } - + return BKE_vfont_load(G_MAIN, FO_BUILTIN_NAME); } @@ -368,7 +368,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect, { Nurb *nu2; BPoint *bp; - + nu2 = (Nurb *) MEM_callocN(sizeof(Nurb), "underline_nurb"); nu2->resolu = cu->resolu; nu2->bezt = NULL; @@ -454,7 +454,7 @@ static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharI co = cosf(rot); che = find_vfont_char(vfd, character); - + /* Select the glyph data */ if (che) nu1 = che->nurbsbase.first; @@ -488,10 +488,10 @@ static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharI } memcpy(bezt2, bezt1, i * sizeof(struct BezTriple)); nu2->bezt = bezt2; - + if (shear != 0.0f) { bezt2 = nu2->bezt; - + for (i = nu2->pntsu; i > 0; i--) { bezt2->vec[0][0] += shear * bezt2->vec[0][1]; bezt2->vec[1][0] += shear * bezt2->vec[1][1]; @@ -544,10 +544,10 @@ static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharI fp[7] = (fp[7] + ofsy) * fsize; bezt2++; } - + BLI_addtail(nubase, nu2); } - + nu1 = nu1->next; } } @@ -557,7 +557,7 @@ int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end) Curve *cu = ob->data; EditFont *ef = cu->editfont; int start, end, direction; - + if ((ob->type != OB_FONT) || (ef == NULL)) return 0; BLI_assert(ef->len >= 0); @@ -681,7 +681,7 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, /* The VFont Data can not be found */ if (!vfd) return ok; - + if (ef) { slen = ef->len; mem = ef->textbuf; @@ -734,9 +734,9 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, /* We assume the worst case: 1 character per line (is freed at end anyway) */ lineinfo = MEM_malloc_arrayN((slen * 2 + 1), sizeof(*lineinfo), "lineinfo"); - + linedist = cu->linedist; - + curbox = 0; textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize); use_textbox = (tb_scale.w != 0.0f); @@ -886,7 +886,7 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, } else if (ascii == 9) { /* TAB */ float tabfac; - + ct->xof = xof; ct->yof = yof; ct->linenr = lnr; @@ -911,27 +911,27 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, sb->h = linedist * cu->fsize; sb->w = xof * cu->fsize; } - + if (ascii == 32) { - wsfac = cu->wordspace; + wsfac = cu->wordspace; wsnr++; } else { wsfac = 1.0f; } - + /* Set the width of the character */ twidth = char_width(cu, che, info); xof += (twidth * wsfac * (1.0f + (info->kern / 40.0f)) ) + xtrax; - + if (sb) { sb->w = (xof * cu->fsize) - sb->w; } } ct++; } - + cu->lines = 1; for (i = 0; i <= slen; i++) { ascii = mem[i]; @@ -1092,7 +1092,7 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, copy_m3_m4(cmat, cu->textoncurve->obmat); mul_m3_m3m3(cmat, cmat, imat3); sizefac = normalize_v3(cmat[0]) / cu->fsize; - + minx = miny = 1.0e20f; maxx = maxy = -1.0e20f; ct = chartransdata; @@ -1102,17 +1102,17 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, if (miny > ct->yof) miny = ct->yof; if (maxy < ct->yof) maxy = ct->yof; } - + /* we put the x-coordinaat exact at the curve, the y is rotated */ - + /* length correction */ distfac = sizefac * cu->textoncurve->curve_cache->path->totdist / (maxx - minx); timeofs = 0.0f; - + if (distfac > 1.0f) { /* path longer than text: spacemode involves */ distfac = 1.0f / distfac; - + if (cu->spacemode == CU_ALIGN_X_RIGHT) { timeofs = 1.0f - distfac; } @@ -1128,14 +1128,14 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, } distfac /= (maxx - minx); - + timeofs += distfac * cu->xof; /* not cyclic */ - + ct = chartransdata; for (i = 0; i < slen; i++, ct++) { float ctime, dtime, vec[4], tvec[4], rotvec[3]; float si, co; - + /* rotate around center character */ info = &custrinfo[i]; ascii = mem[i]; @@ -1144,7 +1144,7 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, } che = find_vfont_char(vfd, ascii); - + twidth = char_width(cu, che, info); dtime = distfac * 0.5f * twidth; @@ -1156,16 +1156,16 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, /* vec, tvec need 4 items */ where_on_path(cu->textoncurve, ctime, vec, tvec, NULL, NULL, NULL); where_on_path(cu->textoncurve, ctime + dtime, tvec, rotvec, NULL, NULL, NULL); - + mul_v3_fl(vec, sizefac); - + ct->rot = (float)M_PI - atan2f(rotvec[1], rotvec[0]); si = sinf(ct->rot); co = cosf(ct->rot); yof = ct->yof; - + ct->xof = vec[0] + si * yof; ct->yof = vec[1] + co * yof; @@ -1224,29 +1224,29 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, } } } - + /* cursor first */ if (ef) { float si, co; - + ct = &chartransdata[ef->pos]; si = sinf(ct->rot); co = cosf(ct->rot); f = ef->textcurs[0]; - + f[0] = cu->fsize * (-0.1f * co + ct->xof); f[1] = cu->fsize * ( 0.1f * si + ct->yof); - + f[2] = cu->fsize * ( 0.1f * co + ct->xof); f[3] = cu->fsize * (-0.1f * si + ct->yof); - + f[4] = cu->fsize * ( 0.1f * co + 0.8f * si + ct->xof); f[5] = cu->fsize * (-0.1f * si + 0.8f * co + ct->yof); - + f[6] = cu->fsize * (-0.1f * co + 0.8f * si + ct->xof); f[7] = cu->fsize * ( 0.1f * si + 0.8f * co + ct->yof); - + } if (mode == FO_SELCHANGE) { @@ -1258,7 +1258,7 @@ bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, if (mode == FO_EDIT) { /* make nurbdata */ BKE_nurbList_free(r_nubase); - + ct = chartransdata; for (i = 0; i < slen; i++) { unsigned int cha = (unsigned int) mem[i]; diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index 6a59ea4439f3..e89508fd6c0f 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -27,7 +27,7 @@ * \ingroup bke */ - + #include #include #include @@ -96,14 +96,14 @@ bool BKE_gpencil_free_strokes(bGPDframe *gpf) void BKE_gpencil_free_frames(bGPDlayer *gpl) { bGPDframe *gpf_next; - + /* error checking */ if (gpl == NULL) return; - + /* free frames */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf_next) { gpf_next = gpf->next; - + /* free strokes and their associated memory */ BKE_gpencil_free_strokes(gpf); BLI_freelinkN(&gpl->frames, gpf); @@ -177,14 +177,14 @@ void BKE_gpencil_free_brushes(ListBase *list) void BKE_gpencil_free_layers(ListBase *list) { bGPDlayer *gpl_next; - + /* error checking */ if (list == NULL) return; - + /* delete layers */ for (bGPDlayer *gpl = list->first; gpl; gpl = gpl_next) { gpl_next = gpl->next; - + /* free layers and their data */ BKE_gpencil_free_frames(gpl); BLI_freelinkN(list, gpl); @@ -212,15 +212,15 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) { bGPDframe *gpf = NULL, *gf = NULL; short state = 0; - + /* error checking */ if (gpl == NULL) return NULL; - + /* allocate memory for this frame */ gpf = MEM_callocN(sizeof(bGPDframe), "bGPDframe"); gpf->framenum = cframe; - + /* find appropriate place to add frame */ if (gpl->frames.first) { for (gf = gpl->frames.first; gf; gf = gf->next) { @@ -229,7 +229,7 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) state = -1; break; } - + /* if current frame has already exceeded the frame to add, add before */ if (gf->framenum > cframe) { BLI_insertlinkbefore(&gpl->frames, gf, gpf); @@ -238,14 +238,14 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) } } } - + /* check whether frame was added successfully */ if (state == -1) { printf("Error: Frame (%d) existed already for this layer. Using existing frame\n", cframe); - + /* free the newly created one, and use the old one instead */ MEM_freeN(gpf); - + /* return existing frame instead... */ BLI_assert(gf != NULL); gpf = gf; @@ -254,7 +254,7 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) /* add to end then! */ BLI_addtail(&gpl->frames, gpf); } - + /* return frame */ return gpf; } @@ -264,7 +264,7 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) { bGPDframe *new_frame; bool found = false; - + /* Error checking/handling */ if (gpl == NULL) { /* no layer */ @@ -274,16 +274,16 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) /* no active frame, so just create a new one from scratch */ return BKE_gpencil_frame_addnew(gpl, cframe); } - + /* Create a copy of the frame */ new_frame = BKE_gpencil_frame_duplicate(gpl->actframe); - + /* Find frame to insert it before */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) { if (gpf->framenum > cframe) { /* Add it here */ BLI_insertlinkbefore(&gpl->frames, gpf, new_frame); - + found = true; break; } @@ -294,23 +294,23 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) BKE_gpencil_free_strokes(new_frame); MEM_freeN(new_frame); new_frame = NULL; - + found = true; break; } } - + if (found == false) { /* Add new frame to the end */ BLI_addtail(&gpl->frames, new_frame); } - + /* Ensure that frame is set up correctly, and return it */ if (new_frame) { new_frame->framenum = cframe; gpl->actframe = new_frame; } - + return new_frame; } @@ -318,17 +318,17 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setactive) { bGPDlayer *gpl; - + /* check that list is ok */ if (gpd == NULL) return NULL; - + /* allocate memory for frame and add to end of list */ gpl = MEM_callocN(sizeof(bGPDlayer), "bGPDlayer"); - + /* add to datablock */ BLI_addtail(&gpd->layers, gpl); - + /* set basic settings */ copy_v4_v4(gpl->color, U.gpencil_new_layer_col); /* Since GPv2 thickness must be 0 */ @@ -339,23 +339,23 @@ bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setacti /* onion-skinning settings */ if (gpd->flag & GP_DATA_SHOW_ONIONSKINS) gpl->flag |= GP_LAYER_ONIONSKIN; - + gpl->flag |= (GP_LAYER_GHOST_PREVCOL | GP_LAYER_GHOST_NEXTCOL); - + ARRAY_SET_ITEMS(gpl->gcolor_prev, 0.145098f, 0.419608f, 0.137255f); /* green */ ARRAY_SET_ITEMS(gpl->gcolor_next, 0.125490f, 0.082353f, 0.529412f); /* blue */ - + /* high quality fill by default */ gpl->flag |= GP_LAYER_HQ_FILL; - + /* auto-name */ BLI_strncpy(gpl->info, name, sizeof(gpl->info)); BLI_uniquename(&gpd->layers, gpl, DATA_("GP_Layer"), '.', offsetof(bGPDlayer, info), sizeof(gpl->info)); - + /* make this one the active one */ if (setactive) BKE_gpencil_layer_setactive(gpd, gpl); - + /* return layer */ return gpl; } @@ -625,18 +625,18 @@ bGPDpalettecolor *BKE_gpencil_palettecolor_addnew(bGPDpalette *palette, const ch bGPdata *BKE_gpencil_data_addnew(Main *bmain, const char name[]) { bGPdata *gpd; - + /* allocate memory for a new block */ gpd = BKE_libblock_alloc(bmain, ID_GD, name, 0); - + /* initial settings */ gpd->flag = (GP_DATA_DISPINFO | GP_DATA_EXPAND); - + /* for now, stick to view is also enabled by default * since this is more useful... */ gpd->flag |= GP_DATA_VIEWALIGN; - + return gpd; } @@ -647,16 +647,16 @@ bGPDframe *BKE_gpencil_frame_duplicate(const bGPDframe *gpf_src) { bGPDstroke *gps_dst; bGPDframe *gpf_dst; - + /* error checking */ if (gpf_src == NULL) { return NULL; } - + /* make a copy of the source frame */ gpf_dst = MEM_dupallocN(gpf_src); gpf_dst->prev = gpf_dst->next = NULL; - + /* copy strokes */ BLI_listbase_clear(&gpf_dst->strokes); for (bGPDstroke *gps_src = gpf_src->strokes.first; gps_src; gps_src = gps_src->next) { @@ -667,7 +667,7 @@ bGPDframe *BKE_gpencil_frame_duplicate(const bGPDframe *gpf_src) gps_dst->flag |= GP_STROKE_RECALC_CACHES; BLI_addtail(&gpf_dst->strokes, gps_dst); } - + /* return new frame */ return gpf_dst; } @@ -727,28 +727,28 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src) const bGPDframe *gpf_src; bGPDframe *gpf_dst; bGPDlayer *gpl_dst; - + /* error checking */ if (gpl_src == NULL) { return NULL; } - + /* make a copy of source layer */ gpl_dst = MEM_dupallocN(gpl_src); gpl_dst->prev = gpl_dst->next = NULL; - + /* copy frames */ BLI_listbase_clear(&gpl_dst->frames); for (gpf_src = gpl_src->frames.first; gpf_src; gpf_src = gpf_src->next) { /* make a copy of source frame */ gpf_dst = BKE_gpencil_frame_duplicate(gpf_src); BLI_addtail(&gpl_dst->frames, gpf_dst); - + /* if source frame was the current layer's 'active' frame, reassign that too */ if (gpf_src == gpl_dst->actframe) gpl_dst->actframe = gpf_dst; } - + /* return new layer */ return gpl_dst; } @@ -824,16 +824,16 @@ void BKE_gpencil_stroke_sync_selection(bGPDstroke *gps) { bGPDspoint *pt; int i; - + /* error checking */ if (gps == NULL) return; - + /* we'll stop when we find the first selected point, * so initially, we must deselect */ gps->flag &= ~GP_STROKE_SELECT; - + for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { if (pt->flag & GP_SPOINT_SELECT) { gps->flag |= GP_STROKE_SELECT; @@ -849,16 +849,16 @@ void BKE_gpencil_frame_delete_laststroke(bGPDlayer *gpl, bGPDframe *gpf) { bGPDstroke *gps = (gpf) ? gpf->strokes.last : NULL; int cfra = (gpf) ? gpf->framenum : 0; /* assume that the current frame was not locked */ - + /* error checking */ if (ELEM(NULL, gpf, gps)) return; - + /* free the stroke and its data */ MEM_freeN(gps->points); MEM_freeN(gps->triangles); BLI_freelinkN(&gpf->strokes, gps); - + /* if frame has no strokes after this, delete it */ if (BLI_listbase_is_empty(&gpf->strokes)) { BKE_gpencil_layer_delframe(gpl, gpf); @@ -874,7 +874,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) /* Sanity check */ if (gpl == NULL) return false; - + /* Layer must be: Visible + Editable */ if ((gpl->flag & (GP_LAYER_HIDE | GP_LAYER_LOCKED)) == 0) { /* Opacity must be sufficiently high that it is still "visible" @@ -884,7 +884,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) return true; } } - + /* Something failed */ return false; } @@ -893,7 +893,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) bGPDframe *BKE_gpencil_layer_find_frame(bGPDlayer *gpl, int cframe) { bGPDframe *gpf; - + /* Search in reverse order, since this is often used for playback/adding, * where it's less likely that we're interested in the earlier frames */ @@ -902,7 +902,7 @@ bGPDframe *BKE_gpencil_layer_find_frame(bGPDlayer *gpl, int cframe) return gpf; } } - + return NULL; } @@ -914,23 +914,23 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M { bGPDframe *gpf = NULL; short found = 0; - + /* error checking */ if (gpl == NULL) return NULL; - + /* check if there is already an active frame */ if (gpl->actframe) { gpf = gpl->actframe; - + /* do not allow any changes to layer's active frame if layer is locked from changes * or if the layer has been set to stay on the current frame */ if (gpl->flag & GP_LAYER_FRAMELOCK) return gpf; /* do not allow any changes to actframe if frame has painting tag attached to it */ - if (gpf->flag & GP_FRAME_PAINT) + if (gpf->flag & GP_FRAME_PAINT) return gpf; - + /* try to find matching frame */ if (gpf->framenum < cframe) { for (; gpf; gpf = gpf->next) { @@ -943,7 +943,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M break; } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -965,7 +965,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M break; } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -985,7 +985,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* check which of the ends to start checking from */ const int first = ((bGPDframe *)(gpl->frames.first))->framenum; const int last = ((bGPDframe *)(gpl->frames.last))->framenum; - + if (abs(cframe - first) > abs(cframe - last)) { /* find gp-frame which is less than or equal to cframe */ for (gpf = gpl->frames.last; gpf; gpf = gpf->prev) { @@ -1004,7 +1004,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M } } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -1029,7 +1029,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* gpl->actframe should still be NULL */ } } - + /* return */ return gpl->actframe; } @@ -1038,23 +1038,23 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M bool BKE_gpencil_layer_delframe(bGPDlayer *gpl, bGPDframe *gpf) { bool changed = false; - + /* error checking */ if (ELEM(NULL, gpl, gpf)) return false; - - /* if this frame was active, make the previous frame active instead + + /* if this frame was active, make the previous frame active instead * since it's tricky to set active frame otherwise */ if (gpl->actframe == gpf) gpl->actframe = gpf->prev; else gpl->actframe = NULL; - + /* free the frame and its data */ changed = BKE_gpencil_free_strokes(gpf); BLI_freelinkN(&gpl->frames, gpf); - + return changed; } @@ -1062,17 +1062,17 @@ bool BKE_gpencil_layer_delframe(bGPDlayer *gpl, bGPDframe *gpf) bGPDlayer *BKE_gpencil_layer_getactive(bGPdata *gpd) { bGPDlayer *gpl; - + /* error checking */ if (ELEM(NULL, gpd, gpd->layers.first)) return NULL; - + /* loop over layers until found (assume only one active) */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { if (gpl->flag & GP_LAYER_ACTIVE) return gpl; } - + /* no active layer found */ return NULL; } @@ -1081,15 +1081,15 @@ bGPDlayer *BKE_gpencil_layer_getactive(bGPdata *gpd) void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) { bGPDlayer *gpl; - + /* error checking */ if (ELEM(NULL, gpd, gpd->layers.first, active)) return; - + /* loop over layers deactivating all */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) gpl->flag &= ~GP_LAYER_ACTIVE; - + /* set as active one */ active->flag |= GP_LAYER_ACTIVE; } @@ -1098,9 +1098,9 @@ void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) void BKE_gpencil_layer_delete(bGPdata *gpd, bGPDlayer *gpl) { /* error checking */ - if (ELEM(NULL, gpd, gpl)) + if (ELEM(NULL, gpd, gpl)) return; - + /* free layer */ BKE_gpencil_free_frames(gpl); BLI_freelinkN(&gpd->layers, gpl); @@ -1281,11 +1281,11 @@ void BKE_gpencil_palettecolor_changename(bGPdata *gpd, char *oldname, const char bGPDlayer *gpl; bGPDframe *gpf; bGPDstroke *gps; - + /* Sanity checks (gpd may not be set in the RNA pointers sometimes) */ if (ELEM(NULL, gpd, oldname, newname)) return; - + for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { for (gpf = gpl->frames.first; gpf; gpf = gpf->next) { for (gps = gpf->strokes.first; gps; gps = gps->next) { @@ -1295,7 +1295,7 @@ void BKE_gpencil_palettecolor_changename(bGPdata *gpd, char *oldname, const char } } } - + } /* Delete all strokes of the color */ @@ -1304,11 +1304,11 @@ void BKE_gpencil_palettecolor_delete_strokes(struct bGPdata *gpd, char *name) bGPDlayer *gpl; bGPDframe *gpf; bGPDstroke *gps, *gpsn; - + /* Sanity checks (gpd may not be set in the RNA pointers sometimes) */ if (ELEM(NULL, gpd, name)) return; - + for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { for (gpf = gpl->frames.first; gpf; gpf = gpf->next) { for (gps = gpf->strokes.first; gps; gps = gpsn) { diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c index f268c419e2f6..62f608f8565e 100644 --- a/source/blender/blenkernel/intern/group.c +++ b/source/blender/blenkernel/intern/group.c @@ -78,7 +78,7 @@ void BKE_group_free(Group *group) Group *BKE_group_add(Main *bmain, const char *name) { Group *group; - + group = BKE_libblock_alloc(bmain, ID_GR, name, 0); id_us_min(&group->id); id_us_ensure_real(&group->id); @@ -126,22 +126,22 @@ void BKE_group_make_local(Main *bmain, Group *group, const bool lib_local) static bool group_object_add_internal(Group *group, Object *ob) { GroupObject *go; - + if (group == NULL || ob == NULL) { return false; } - + /* check if the object has been added already */ if (BLI_findptr(&group->gobject, ob, offsetof(GroupObject, ob))) { return false; } - + go = MEM_callocN(sizeof(GroupObject), "groupobject"); BLI_addtail(&group->gobject, go); - + go->ob = ob; id_us_ensure_real(&go->ob->id); - + return true; } @@ -171,7 +171,7 @@ static int group_object_unlink_internal(Group *group, Object *ob) GroupObject *go, *gon; int removed = 0; if (group == NULL) return 0; - + go = group->gobject.first; while (go) { gon = go->next; @@ -259,7 +259,7 @@ Group *BKE_group_object_find(Main *bmain, Group *group, Object *ob) group = group->id.next; else group = bmain->group.first; - + while (group) { if (BKE_group_object_exists(group, ob)) return group; @@ -293,9 +293,9 @@ static void group_replaces_nla(Object *parent, Object *target, char mode) static bAction *action = NULL; static bool done = false; bActionStrip *strip, *nstrip; - + if (mode == 's') { - + for (strip = parent->nlastrips.first; strip; strip = strip->next) { if (strip->object == target) { if (done == 0) { @@ -317,7 +317,7 @@ static void group_replaces_nla(Object *parent, Object *target, char mode) BLI_freelistN(&target->nlastrips); target->nlastrips = nlastrips; target->action = action; - + BLI_listbase_clear(&nlastrips); /* not needed, but yah... :) */ action = NULL; done = false; @@ -334,7 +334,7 @@ void BKE_group_handle_recalc_and_update( Main *bmain, EvaluationContext *eval_ctx, Scene *scene, Object *UNUSED(parent), Group *group) { GroupObject *go; - + #if 0 /* warning, isn't clearing the recalc flag on the object which causes it to run all the time, * not just on frame change. * This isn't working because the animation data is only re-evaluated on frame change so commenting for now @@ -343,24 +343,24 @@ void BKE_group_handle_recalc_and_update( /* if animated group... */ if (parent->nlastrips.first) { int cfrao; - + /* switch to local time */ cfrao = scene->r.cfra; - + /* we need a DAG per group... */ for (go = group->gobject.first; go; go = go->next) { if (go->ob && go->recalc) { go->ob->recalc = go->recalc; - + group_replaces_nla(parent, go->ob, 's'); BKE_object_handle_update(eval_ctx, scene, go->ob); group_replaces_nla(parent, go->ob, 'e'); - + /* leave recalc tags in case group members are in normal scene */ go->ob->recalc = go->recalc; } } - + /* restore */ scene->r.cfra = cfrao; } diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c index 9483543f1f0e..071c10acaa56 100644 --- a/source/blender/blenkernel/intern/icons.c +++ b/source/blender/blenkernel/intern/icons.c @@ -105,7 +105,7 @@ static int get_next_free_id(void) /* if we haven't used up the int number range, we just return the next int */ if (gNextIconId >= gFirstIconId) return gNextIconId++; - + /* now we try to find the smallest icon id not stored in the gIcons hash */ while (BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(startId)) && startId >= gFirstIconId) startId++; @@ -203,7 +203,7 @@ void BKE_previewimg_freefunc(void *link) if (prv->gputexture[i]) GPU_texture_free(prv->gputexture[i]); } - + MEM_freeN(prv); } } @@ -468,11 +468,11 @@ void BKE_icon_changed(const int icon_id) BLI_assert(BLI_thread_is_main()); Icon *icon = NULL; - + if (!icon_id || G.background) return; icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id)); - + if (icon) { /* We *only* expect ID-tied icons here, not non-ID icon/preview! */ BLI_assert(icon->id_type != 0); @@ -599,7 +599,7 @@ Icon *BKE_icon_get(const int icon_id) Icon *icon = NULL; icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id)); - + if (!icon) { printf("%s: Internal error, no icon for icon ID: %d\n", __func__, icon_id); return NULL; diff --git a/source/blender/blenkernel/intern/idcode.c b/source/blender/blenkernel/intern/idcode.c index 70d037d85f35..d995dce1259e 100644 --- a/source/blender/blenkernel/intern/idcode.c +++ b/source/blender/blenkernel/intern/idcode.c @@ -47,7 +47,7 @@ typedef struct { const char *name, *plural; const char *i18n_context; - + int flags; #define IDTYPE_FLAGS_ISLINKABLE (1 << 0) } IDType; @@ -99,7 +99,7 @@ static IDType idtypes[] = { /* -1 for ID_ID */ BLI_STATIC_ASSERT((ARRAY_SIZE(idtypes) - 1 == MAX_LIBARRAY), "Missing IDType"); -static IDType *idtype_from_name(const char *str) +static IDType *idtype_from_name(const char *str) { int i = ARRAY_SIZE(idtypes); @@ -118,7 +118,7 @@ static IDType *idtype_from_code(short idcode) while (i--) if (idcode == idtypes[i].code) return &idtypes[i]; - + return NULL; } diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index fe00d68b4ea8..7a526d315675 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -86,7 +86,7 @@ IDProperty *IDP_NewIDPArray(const char *name) prop->type = IDP_IDPARRAY; prop->len = 0; BLI_strncpy(prop->name, name, MAX_IDPROP_NAME); - + return prop; } @@ -113,14 +113,14 @@ IDProperty *IDP_CopyIDPArray(const IDProperty *array, const int flag) memcpy(GETPROP(narray, i), tmp, sizeof(IDProperty)); MEM_freeN(tmp); } - + return narray; } static void IDP_FreeIDPArray(IDProperty *prop, const bool do_id_user) { int i; - + BLI_assert(prop->type == IDP_IDPARRAY); for (i = 0; i < prop->len; i++) @@ -472,7 +472,7 @@ static IDProperty *IDP_CopyID(const IDProperty *prop, const int flag) static IDProperty *IDP_CopyGroup(const IDProperty *prop, const int flag) { IDProperty *newp, *link; - + BLI_assert(prop->type == IDP_GROUP); newp = idp_generic_copy(prop, flag); newp->len = prop->len; @@ -886,7 +886,6 @@ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is case IDP_ID: return (IDP_Id(prop1) == IDP_Id(prop2)); default: - /* should never get here */ BLI_assert(0); break; } @@ -988,7 +987,8 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char * prop->data.pointer = MEM_mallocN(DEFAULT_ALLOC_FOR_NULL_STRINGS, "id property string 1"); *IDP_String(prop) = '\0'; prop->totallen = DEFAULT_ALLOC_FOR_NULL_STRINGS; - prop->len = 1; /*NULL string, has len of 1 to account for null byte.*/ + /* NULL string, has len of 1 to account for null byte. */ + prop->len = 1; } else { BLI_assert((int)val->string.len <= (int)strlen(st) + 1); @@ -1003,8 +1003,8 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char * } case IDP_GROUP: { + /* Values are set properly by calloc. */ prop = MEM_callocN(sizeof(IDProperty), "IDProperty group"); - /* heh I think all needed values are set properly by calloc anyway :) */ break; } case IDP_ID: @@ -1024,7 +1024,7 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char * prop->type = type; BLI_strncpy(prop->name, name, MAX_IDPROP_NAME); - + return prop; } @@ -1068,4 +1068,3 @@ void IDP_ClearProperty(IDProperty *prop) } /** \} */ - diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index 95fb96c875f9..c520714b076c 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -574,7 +574,7 @@ static void image_init_color_management(Image *ima) char BKE_image_alpha_mode_from_extension_ex(const char *filepath) { - if (BLI_testextensie_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) { + if (BLI_path_extension_check_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) { return IMA_ALPHA_PREMUL; } else { @@ -605,7 +605,7 @@ Image *BKE_image_load(Main *bmain, const char *filepath) ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE); STRNCPY(ima->name, filepath); - if (BLI_testextensie_array(filepath, imb_ext_movie)) + if (BLI_path_extension_check_array(filepath, imb_ext_movie)) ima->source = IMA_SRC_MOVIE; image_init_color_management(ima); @@ -1367,63 +1367,63 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF (void)im_format; /* may be unused, depends on build options */ if (imtype == R_IMF_IMTYPE_IRIS) { - if (!BLI_testextensie(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_IRIZ) { - if (!BLI_testextensie(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) extension = extension_test; } #ifdef WITH_HDR else if (imtype == R_IMF_IMTYPE_RADHDR) { - if (!BLI_testextensie(string, extension_test = ".hdr")) + if (!BLI_path_extension_check(string, extension_test = ".hdr")) extension = extension_test; } #endif else if (ELEM(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, extension_test = ".png")) + if (!BLI_path_extension_check(string, extension_test = ".png")) extension = extension_test; } #ifdef WITH_DDS else if (imtype == R_IMF_IMTYPE_DDS) { - if (!BLI_testextensie(string, extension_test = ".dds")) + if (!BLI_path_extension_check(string, extension_test = ".dds")) extension = extension_test; } #endif else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) { - if (!BLI_testextensie(string, extension_test = ".tga")) + if (!BLI_path_extension_check(string, extension_test = ".tga")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_BMP) { - if (!BLI_testextensie(string, extension_test = ".bmp")) + if (!BLI_path_extension_check(string, extension_test = ".bmp")) extension = extension_test; } #ifdef WITH_TIFF else if (imtype == R_IMF_IMTYPE_TIFF) { - if (!BLI_testextensie_n(string, extension_test = ".tif", ".tiff", NULL)) { + if (!BLI_path_extension_check_n(string, extension_test = ".tif", ".tiff", NULL)) { extension = extension_test; } } #endif #ifdef WITH_OPENIMAGEIO else if (imtype == R_IMF_IMTYPE_PSD) { - if (!BLI_testextensie(string, extension_test = ".psd")) + if (!BLI_path_extension_check(string, extension_test = ".psd")) extension = extension_test; } #endif #ifdef WITH_OPENEXR else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) { - if (!BLI_testextensie(string, extension_test = ".exr")) + if (!BLI_path_extension_check(string, extension_test = ".exr")) extension = extension_test; } #endif #ifdef WITH_CINEON else if (imtype == R_IMF_IMTYPE_CINEON) { - if (!BLI_testextensie(string, extension_test = ".cin")) + if (!BLI_path_extension_check(string, extension_test = ".cin")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_DPX) { - if (!BLI_testextensie(string, extension_test = ".dpx")) + if (!BLI_path_extension_check(string, extension_test = ".dpx")) extension = extension_test; } #endif @@ -1431,35 +1431,35 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF else if (imtype == R_IMF_IMTYPE_JP2) { if (im_format) { if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) { - if (!BLI_testextensie(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) extension = extension_test; } else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) { - if (!BLI_testextensie(string, extension_test = ".j2c")) + if (!BLI_path_extension_check(string, extension_test = ".j2c")) extension = extension_test; } else BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); } else { - if (!BLI_testextensie(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) extension = extension_test; } } #endif else { // R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc - if (!(BLI_testextensie_n(string, extension_test = ".jpg", ".jpeg", NULL))) + if (!(BLI_path_extension_check_n(string, extension_test = ".jpg", ".jpeg", NULL))) extension = extension_test; } if (extension) { /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */ /* remove any other known image extension */ - if (BLI_testextensie_array(string, imb_ext_image)) { - return BLI_replace_extension(string, FILE_MAX, extension); + if (BLI_path_extension_check_array(string, imb_ext_image)) { + return BLI_path_extension_replace(string, FILE_MAX, extension); } else { - return BLI_ensure_extension(string, FILE_MAX, extension); + return BLI_path_extension_ensure(string, FILE_MAX, extension); } } @@ -3043,7 +3043,7 @@ bool BKE_image_is_openexr(struct Image *ima) { #ifdef WITH_OPENEXR if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) { - return BLI_testextensie(ima->name, ".exr"); + return BLI_path_extension_check(ima->name, ".exr"); } #else UNUSED_VARS(ima); @@ -4095,12 +4095,12 @@ ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock) void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock) { - if (lock) { + if (lock != NULL) { /* for getting image during threaded render / compositing, need to release */ if (lock == ima) { BLI_thread_unlock(LOCK_VIEWER); /* viewer image */ } - else if (lock) { + else { RE_ReleaseResultImage(lock); /* render result */ BLI_thread_unlock(LOCK_VIEWER); /* view image imbuf */ } diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 611c1e3bafb5..fd8cb6d6d98b 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -37,7 +37,7 @@ * * -- Joshua Leung, Jan 2009 */ - + #include #include #include @@ -93,18 +93,18 @@ void BKE_ipo_free(Ipo *ipo) { IpoCurve *icu, *icn; int n = 0; - + for (icu = ipo->curve.first; icu; icu = icn) { icn = icu->next; n++; - + if (icu->bezt) MEM_freeN(icu->bezt); if (icu->bp) MEM_freeN(icu->bp); if (icu->driver) MEM_freeN(icu->driver); - + BLI_freelinkN(&ipo->curve, icu); } - + if (G.debug & G_DEBUG) printf("Freed %d (Unconverted) Ipo-Curves from IPO '%s'\n", n, ipo->id.name + 2); } @@ -177,7 +177,7 @@ static AdrBit2Path *adrcode_bitmaps_to_paths(int blocktype, int adrcode, int *to RET_ABP(ma_mode_bits); } // XXX TODO: add other types... - + /* Normal curve */ return NULL; } @@ -191,7 +191,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case OB_LOC_X: @@ -206,7 +206,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "delta_location"; case OB_DLOC_Z: *array_index = 2; return "delta_location"; - + case OB_ROT_X: *array_index = 0; return "rotation_euler"; case OB_ROT_Y: @@ -219,7 +219,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "delta_rotation_euler"; case OB_DROT_Z: *array_index = 2; return "delta_rotation_euler"; - + case OB_SIZE_X: *array_index = 0; return "scale"; case OB_SIZE_Y: @@ -261,18 +261,18 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) break; #endif } - + return NULL; } -/* PoseChannel types +/* PoseChannel types * NOTE: pchan name comes from 'actname' added earlier... */ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case AC_QUAT_W: @@ -283,21 +283,21 @@ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 2; return "rotation_quaternion"; case AC_QUAT_Z: *array_index = 3; return "rotation_quaternion"; - + case AC_EUL_X: *array_index = 0; return "rotation_euler"; case AC_EUL_Y: *array_index = 1; return "rotation_euler"; case AC_EUL_Z: *array_index = 2; return "rotation_euler"; - + case AC_LOC_X: *array_index = 0; return "location"; case AC_LOC_Y: *array_index = 1; return "location"; case AC_LOC_Z: *array_index = 2; return "location"; - + case AC_SIZE_X: *array_index = 0; return "scale"; case AC_SIZE_Y: @@ -305,7 +305,7 @@ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) case AC_SIZE_Z: *array_index = 2; return "scale"; } - + /* for debugging only */ printf("ERROR: unmatched PoseChannel setting (code %d)\n", adrcode); return NULL; @@ -316,7 +316,7 @@ static const char *constraint_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case CO_ENFORCE: @@ -324,18 +324,18 @@ static const char *constraint_adrcodes_to_paths(int adrcode, int *array_index) case CO_HEADTAIL: // XXX this needs to be wrapped in RNA.. probably then this path will be invalid return "data.head_tail"; } - + return NULL; } -/* ShapeKey types +/* ShapeKey types * NOTE: as we don't have access to the keyblock where the data comes from (for now), * we'll just use numerical indices for now... */ static char *shapekey_adrcodes_to_paths(ID *id, int adrcode, int *UNUSED(array_index)) { static char buf[128]; - + /* block will be attached to ID_KE block... */ if (adrcode == 0) { /* adrcode=0 was the misnamed "speed" curve (now "evaluation time") */ @@ -345,7 +345,7 @@ static char *shapekey_adrcodes_to_paths(ID *id, int adrcode, int *UNUSED(array_i /* Find the name of the ShapeKey (i.e. KeyBlock) to look for */ Key *key = (Key *)id; KeyBlock *kb = BKE_keyblock_from_key(key, adrcode); - + /* setting that we alter is the "value" (i.e. keyblock.curval) */ if (kb) { /* Use the keyblock name, escaped, so that path lookups for this will work */ @@ -364,7 +364,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) { const char *base = NULL, *prop = NULL; static char buf[128]; - + /* base part of path */ if (adrcode & MA_MAP1) base = "textures[0]"; else if (adrcode & MA_MAP2) base = "textures[1]"; @@ -384,7 +384,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) else if (adrcode & MA_MAP16) base = "textures[15]"; else if (adrcode & MA_MAP17) base = "textures[16]"; else if (adrcode & MA_MAP18) base = "textures[17]"; - + /* property identifier for path */ adrcode = (adrcode & (MA_MAP1 - 1)); switch (adrcode) { @@ -419,7 +419,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) case MAP_DISP: prop = "warp_factor"; break; } - + /* only build and return path if there's a property */ if (prop) { BLI_snprintf(buf, 128, "%s.%s", base, prop); @@ -434,26 +434,26 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case TE_NSIZE: return "noise_size"; case TE_TURB: return "turbulence"; - + case TE_NDEPTH: // XXX texture RNA undefined //poin= &(tex->noisedepth); *type= IPO_SHORT; break; break; case TE_NTYPE: // XXX texture RNA undefined //poin= &(tex->noisetype); *type= IPO_SHORT; break; break; - + case TE_N_BAS1: return "noise_basis"; case TE_N_BAS2: return "noise_basis"; // XXX this is not yet defined in RNA... - + /* voronoi */ case TE_VNW1: *array_index = 0; return "feature_weights"; @@ -469,15 +469,15 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) return "distance_metric"; case TE_VN_COLT: return "color_type"; - + /* distorted noise / voronoi */ case TE_ISCA: return "noise_intensity"; - + /* distorted noise */ case TE_DISTA: return "distortion_amount"; - + /* musgrave */ case TE_MG_TYP: // XXX texture RNA undefined // poin= &(tex->stype); *type= IPO_SHORT; break; @@ -492,20 +492,20 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) return "offset"; case TE_MG_GAIN: return "gain"; - + case TE_COL_R: *array_index = 0; return "rgb_factor"; case TE_COL_G: *array_index = 1; return "rgb_factor"; case TE_COL_B: *array_index = 2; return "rgb_factor"; - + case TE_BRIGHT: return "brightness"; case TE_CONTRA: return "constrast"; } - + return NULL; } @@ -514,7 +514,7 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case MA_COL_R: @@ -523,73 +523,73 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "diffuse_color"; case MA_COL_B: *array_index = 2; return "diffuse_color"; - + case MA_SPEC_R: *array_index = 0; return "specular_color"; case MA_SPEC_G: *array_index = 1; return "specular_color"; case MA_SPEC_B: *array_index = 2; return "specular_color"; - + case MA_MIR_R: *array_index = 0; return "mirror_color"; case MA_MIR_G: *array_index = 1; return "mirror_color"; case MA_MIR_B: *array_index = 2; return "mirror_color"; - + case MA_ALPHA: return "alpha"; - + case MA_REF: return "diffuse_intensity"; - + case MA_EMIT: return "emit"; - + case MA_AMB: return "ambient"; - + case MA_SPEC: return "specular_intensity"; - + case MA_HARD: return "specular_hardness"; - + case MA_SPTR: return "specular_opacity"; - + case MA_IOR: return "ior"; - + case MA_HASIZE: return "halo.size"; - + case MA_TRANSLU: return "translucency"; - + case MA_RAYM: return "raytrace_mirror.reflect"; - + case MA_FRESMIR: return "raytrace_mirror.fresnel"; - + case MA_FRESMIRI: return "raytrace_mirror.fresnel_factor"; - + case MA_FRESTRA: return "raytrace_transparency.fresnel"; - + case MA_FRESTRAI: return "raytrace_transparency.fresnel_factor"; - + case MA_ADD: return "halo.add"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + return NULL; } @@ -598,7 +598,7 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case CAM_LENS: @@ -606,29 +606,29 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) if (ca->type == CAM_ORTHO) return "ortho_scale"; else - return "lens"; + return "lens"; #else // XXX lazy hack for now... return "lens"; #endif // XXX this cannot be resolved easily - + case CAM_STA: return "clip_start"; case CAM_END: return "clip_end"; - + #if 0 // XXX these are not defined in RNA case CAM_YF_APERT: poin = &(ca->YF_aperture); break; case CAM_YF_FDIST: poin = &(ca->YF_dofdist); break; #endif // XXX these are not defined in RNA - + case CAM_SHIFT_X: return "shift_x"; case CAM_SHIFT_Y: return "shift_y"; } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -638,39 +638,39 @@ static const char *lamp_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case LA_ENERGY: return "energy"; - + case LA_COL_R: *array_index = 0; return "color"; case LA_COL_G: *array_index = 1; return "color"; case LA_COL_B: *array_index = 2; return "color"; - + case LA_DIST: return "distance"; - + case LA_SPOTSI: return "spot_size"; case LA_SPOTBL: return "spot_blend"; - + case LA_QUAD1: return "linear_attenuation"; case LA_QUAD2: return "quadratic_attenuation"; - + case LA_HALOINT: return "halo_intensity"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -680,7 +680,7 @@ static const char *sound_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case SND_VOLUME: @@ -695,7 +695,7 @@ static const char *sound_adrcodes_to_paths(int adrcode, int *array_index) case SND_ATTEN: return "attenuation"; } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -705,7 +705,7 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case WO_HOR_R: @@ -720,10 +720,10 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "zenith_color"; case WO_ZEN_B: *array_index = 2; return "zenith_color"; - + case WO_EXPOS: return "exposure"; - + case WO_MISI: return "mist.intensity"; case WO_MISTDI: @@ -732,11 +732,11 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) return "mist.start"; case WO_MISTHI: return "mist.height"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + return NULL; } @@ -745,7 +745,7 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case PART_CLUMP: @@ -776,7 +776,7 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) return "settings.kink_shape"; case PART_BB_TILT: return "settings.billboard_tilt"; - + /* PartDeflect needs to be sorted out properly in rna_object_force; * If anyone else works on this, but is unfamiliar, these particular * settings reference the particles of the system themselves @@ -826,64 +826,64 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], char *rpath = NULL; char buf[512]; int dummy_index = 0; - + /* hack: if constname is set, we can only be dealing with an Constraint curve */ if (constname) blocktype = ID_CO; - + /* get property name based on blocktype */ switch (blocktype) { case ID_OB: /* object */ propname = ob_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_PO: /* pose channel */ propname = pchan_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_KE: /* shapekeys */ propname = shapekey_adrcodes_to_paths(id, adrcode, &dummy_index); break; - + case ID_CO: /* constraint */ propname = constraint_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_TE: /* texture */ propname = texture_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_MA: /* material */ propname = material_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_CA: /* camera */ propname = camera_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_LA: /* lamp */ propname = lamp_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_SO: /* sound */ propname = sound_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_WO: /* world */ propname = world_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_PA: /* particle */ propname = particle_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_CU: /* curve */ - /* this used to be a 'dummy' curve which got evaluated on the fly... + /* this used to be a 'dummy' curve which got evaluated on the fly... * now we've got real var for this! */ propname = "eval_time"; break; - + /* XXX problematic blocktypes */ case ID_SEQ: /* sequencer strip */ //SEQ_FAC1: @@ -900,28 +900,28 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], } // poin= &(seq->facf0); // XXX this doesn't seem to be included anywhere in sequencer RNA... break; - + /* special hacks */ case -1: /* special case for rotdiff drivers... we don't need a property for this... */ break; - + /* TODO... add other blocktypes... */ default: printf("IPO2ANIMATO WARNING: No path for blocktype %d, adrcode %d yet\n", blocktype, adrcode); break; } - - /* check if any property found + + /* check if any property found * - blocktype < 0 is special case for a specific type of driver, where we don't need a property name... */ if ((propname == NULL) && (blocktype > 0)) { /* nothing was found, so exit */ - if (array_index) + if (array_index) *array_index = 0; - + BLI_dynstr_free(path); - + return NULL; } else { @@ -963,24 +963,24 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], } BLI_dynstr_append(path, buf); - + /* need to add dot before property if there was anything precceding this */ if (buf[0]) BLI_dynstr_append(path, "."); - + /* now write name of property */ BLI_dynstr_append(path, propname); - + /* if there was no array index pointer provided, add it to the path */ if (array_index == NULL) { BLI_snprintf(buf, sizeof(buf), "[\"%d\"]", dummy_index); BLI_dynstr_append(path, buf); } - + /* convert to normal MEM_malloc'd string */ rpath = BLI_dynstr_get_cstring(path); BLI_dynstr_free(path); - + /* return path... */ return rpath; } @@ -998,21 +998,21 @@ static short adrcode_to_dtar_transchan(short adrcode) return DTAR_TRANSCHAN_LOCY; case OB_LOC_Z: return DTAR_TRANSCHAN_LOCZ; - + case OB_ROT_X: return DTAR_TRANSCHAN_ROTX; case OB_ROT_Y: return DTAR_TRANSCHAN_ROTY; case OB_ROT_Z: return DTAR_TRANSCHAN_ROTZ; - + case OB_SIZE_X: return DTAR_TRANSCHAN_SCALEX; case OB_SIZE_Y: return DTAR_TRANSCHAN_SCALEX; case OB_SIZE_Z: return DTAR_TRANSCHAN_SCALEX; - + default: return 0; } @@ -1022,10 +1022,10 @@ static short adrcode_to_dtar_transchan(short adrcode) static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) { ChannelDriver *cdriver; - + /* allocate memory for new driver */ cdriver = MEM_callocN(sizeof(ChannelDriver), "ChannelDriver"); - + /* if 'pydriver', just copy data across */ if (idriver->type == IPO_DRIVER_TYPE_PYTHON) { /* PyDriver only requires the expression to be copied */ @@ -1037,24 +1037,24 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) else { DriverVar *dvar = NULL; DriverTarget *dtar = NULL; - + /* this should be ok for all types here... */ cdriver->type = DRIVER_TYPE_AVERAGE; - + /* what to store depends on the 'blocktype' - object or posechannel */ if (idriver->blocktype == ID_AR) { /* PoseChannel */ if (idriver->adrcode == OB_ROT_DIFF) { /* Rotational Difference requires a special type of variable */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_ROT_DIFF); - + /* first bone target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; if (idriver->name[0]) BLI_strncpy(dtar->pchan_name, idriver->name, sizeof(dtar->pchan_name)); - + /* second bone target (name was stored in same var as the first one) */ dtar = &dvar->targets[1]; dtar->id = (ID *)idriver->ob; @@ -1066,7 +1066,7 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) /* only a single variable, of type 'transform channel' */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_TRANSFORM_CHAN); - + /* only requires a single target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; @@ -1081,7 +1081,7 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) /* only a single variable, of type 'transform channel' */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_TRANSFORM_CHAN); - + /* only requires single target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; @@ -1089,12 +1089,12 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) dtar->transChan = adrcode_to_dtar_transchan(idriver->adrcode); } } - + /* return the new one */ return cdriver; } -/* Add F-Curve to the correct list +/* Add F-Curve to the correct list * - grpname is needed to be used as group name where relevant, and is usually derived from actname */ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, char *grpname, int muteipo) @@ -1106,7 +1106,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch */ bAction tmp_act; bActionGroup *agrp = NULL; - + /* init the temp action */ memset(&tmp_act, 0, sizeof(bAction)); // XXX only enable this line if we get errors tmp_act.groups.first = groups->first; @@ -1114,7 +1114,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch tmp_act.curves.first = list->first; tmp_act.curves.last = list->last; /* ... xxx, the other vars don't need to be filled in */ - + /* get the group to use */ agrp = BKE_action_group_find_name(&tmp_act, grpname); /* no matching group, so add one */ @@ -1131,14 +1131,14 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch BLI_uniquename(&tmp_act.groups, agrp, DATA_("Group"), '.', offsetof(bActionGroup, name), sizeof(agrp->name)); } - + /* add F-Curve to group */ /* WARNING: this func should only need to look at the stuff we initialized, if not, things may crash */ action_groups_add_channel(&tmp_act, agrp, fcu); - + if (agrp->flag & AGRP_MUTED) /* flush down */ fcu->flag |= FCURVE_MUTED; - + /* set the output lists based on the ones in the temp action */ groups->first = tmp_act.groups.first; groups->last = tmp_act.groups.last; @@ -1151,7 +1151,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch } } -/* Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that +/* Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that * is not relevant, BUT do not free the IPO-Curve itself... * actname: name of Action-Channel (if applicable) that IPO-Curve's IPO-block belonged to * constname: name of Constraint-Channel (if applicable) that IPO-Curve's IPO-block belonged to @@ -1162,21 +1162,21 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i AdrBit2Path *abp; FCurve *fcu; int totbits; - + /* allocate memory for a new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "FCurve"); - + /* convert driver */ if (icu->driver) fcu->driver = idriver_to_cdriver(icu->driver); - + /* copy flags */ if (icu->flag & IPO_VISIBLE) fcu->flag |= FCURVE_VISIBLE; if (icu->flag & IPO_SELECT) fcu->flag |= FCURVE_SELECTED; if (icu->flag & IPO_ACTIVE) fcu->flag |= FCURVE_ACTIVE; if (icu->flag & IPO_MUTE) fcu->flag |= FCURVE_MUTED; if (icu->flag & IPO_PROTECT) fcu->flag |= FCURVE_PROTECTED; - + /* set extrapolation */ switch (icu->extrap) { case IPO_HORIZ: /* constant extrapolation */ @@ -1189,12 +1189,12 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i case IPO_CYCL: /* cyclic extrapolation */ case IPO_CYCLX: /* cyclic extrapolation + offset */ { - /* Add a new FModifier (Cyclic) instead of setting extend value + /* Add a new FModifier (Cyclic) instead of setting extend value * as that's the new equivalent of that option. */ FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, fcu); FMod_Cycles *data = (FMod_Cycles *)fcm->data; - + /* if 'offset' one is in use, set appropriate settings */ if (icu->extrap == IPO_CYCLX) data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC_OFFSET; @@ -1203,20 +1203,20 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i break; } } - + /* -------- */ - + /* get adrcode <-> bitflags mapping to handle nasty bitflag curves? */ abp = adrcode_bitmaps_to_paths(icu->blocktype, icu->adrcode, &totbits); if (abp && totbits) { FCurve *fcurve; int b; - + if (G.debug & G_DEBUG) printf("\tconvert bitflag ipocurve, totbits = %d\n", totbits); - + /* add the 'only int values' flag */ fcu->flag |= (FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES); - + /* for each bit we have to remap + check for: * 1) we need to make copy the existing F-Curve data (fcu -> fcurve), * except for the last one which will use the original @@ -1225,46 +1225,46 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i */ for (b = 0; b < totbits; b++, abp++) { unsigned int i = 0; - + /* make a copy of existing base-data if not the last curve */ if (b < (totbits - 1)) fcurve = copy_fcurve(fcu); else fcurve = fcu; - + /* set path */ fcurve->rna_path = BLI_strdup(abp->path); fcurve->array_index = abp->array_index; - - /* convert keyframes + + /* convert keyframes * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) */ fcurve->totvert = icu->totvert; - + if (icu->bezt) { BezTriple *dst, *src; - + /* allocate new array for keyframes/beztriples */ fcurve->bezt = MEM_callocN(sizeof(BezTriple) * fcurve->totvert, "BezTriples"); - + /* loop through copying all BezTriples individually, as we need to modify a few things */ for (dst = fcurve->bezt, src = icu->bezt, i = 0; i < fcurve->totvert; i++, dst++, src++) { /* firstly, copy BezTriple data */ *dst = *src; - + /* interpolation can only be constant... */ dst->ipo = BEZT_IPO_CONST; - + /* 'hide' flag is now used for keytype - only 'keyframes' existed before */ dst->hide = BEZT_KEYTYPE_KEYFRAME; - + /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { if (dst->h1 == HD_AUTO) dst->h1 = HD_AUTO_ANIM; if (dst->h2 == HD_AUTO) dst->h2 = HD_AUTO_ANIM; } - + /* correct values, by checking if the flag of interest is set */ if ( ((int)(dst->vec[1][1])) & (abp->bit) ) dst->vec[0][1] = dst->vec[1][1] = dst->vec[2][1] = 1.0f; @@ -1277,80 +1277,80 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i //BPoint *bp; //FPoint *fpt; } - + /* add new F-Curve to list */ fcurve_add_to_list(groups, list, fcurve, actname, muteipo); } } else { unsigned int i = 0; - + /* get rna-path * - we will need to set the 'disabled' flag if no path is able to be made (for now) */ fcu->rna_path = get_rna_access(id, icu->blocktype, icu->adrcode, actname, constname, seq, &fcu->array_index); if (fcu->rna_path == NULL) fcu->flag |= FCURVE_DISABLED; - - /* convert keyframes + + /* convert keyframes * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) */ fcu->totvert = icu->totvert; - + if (icu->bezt) { BezTriple *dst, *src; - + /* allocate new array for keyframes/beztriples */ fcu->bezt = MEM_callocN(sizeof(BezTriple) * fcu->totvert, "BezTriples"); - + /* loop through copying all BezTriples individually, as we need to modify a few things */ for (dst = fcu->bezt, src = icu->bezt, i = 0; i < fcu->totvert; i++, dst++, src++) { /* firstly, copy BezTriple data */ *dst = *src; - + /* now copy interpolation from curve (if not already set) */ if (icu->ipo != IPO_MIXED) dst->ipo = icu->ipo; - + /* 'hide' flag is now used for keytype - only 'keyframes' existed before */ dst->hide = BEZT_KEYTYPE_KEYFRAME; - + /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { if (dst->h1 == HD_AUTO) dst->h1 = HD_AUTO_ANIM; if (dst->h2 == HD_AUTO) dst->h2 = HD_AUTO_ANIM; } - - /* correct values for euler rotation curves - * - they were degrees/10 + + /* correct values for euler rotation curves + * - they were degrees/10 * - we need radians for RNA to do the right thing */ if ( ((icu->blocktype == ID_OB) && ELEM(icu->adrcode, OB_ROT_X, OB_ROT_Y, OB_ROT_Z)) || ((icu->blocktype == ID_PO) && ELEM(icu->adrcode, AC_EUL_X, AC_EUL_Y, AC_EUL_Z)) ) { const float fac = (float)M_PI / 18.0f; //10.0f * M_PI/180.0f; - + dst->vec[0][1] *= fac; dst->vec[1][1] *= fac; dst->vec[2][1] *= fac; } - - /* correct values for path speed curves + + /* correct values for path speed curves * - their values were 0-1 * - we now need as 'frames' */ - if ( (id) && (icu->blocktype == GS(id->name)) && + if ( (id) && (icu->blocktype == GS(id->name)) && (fcu->rna_path && STREQ(fcu->rna_path, "eval_time")) ) { Curve *cu = (Curve *)id; - + dst->vec[0][1] *= cu->pathlen; dst->vec[1][1] *= cu->pathlen; dst->vec[2][1] *= cu->pathlen; } - - /* correct times for rotation drivers + + /* correct times for rotation drivers * - need to go from degrees to radians... * - there's only really 1 target to worry about * - were also degrees/10 @@ -1358,27 +1358,27 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i if (fcu->driver && fcu->driver->variables.first) { DriverVar *dvar = fcu->driver->variables.first; DriverTarget *dtar = &dvar->targets[0]; - + if (ELEM(dtar->transChan, DTAR_TRANSCHAN_ROTX, DTAR_TRANSCHAN_ROTY, DTAR_TRANSCHAN_ROTZ)) { const float fac = (float)M_PI / 18.0f; - + dst->vec[0][0] *= fac; dst->vec[1][0] *= fac; dst->vec[2][0] *= fac; } } - + /* correct values for sequencer curves, that were not locked to frame */ if (seq && (seq->flag & SEQ_IPO_FRAME_LOCKED) == 0) { const float mul = (seq->enddisp - seq->startdisp) / 100.0f; const float offset = seq->startdisp; - + dst->vec[0][0] *= mul; dst->vec[0][0] += offset; - + dst->vec[1][0] *= mul; dst->vec[1][0] += offset; - + dst->vec[2][0] *= mul; dst->vec[2][0] += offset; } @@ -1389,7 +1389,7 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i //BPoint *bp; //FPoint *fpt; } - + /* add new F-Curve to list */ fcurve_add_to_list(groups, list, fcu, actname, muteipo); } @@ -1404,16 +1404,16 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq, ListBase *animgroups, ListBase *anim, ListBase *drivers) { IpoCurve *icu; - + /* sanity check */ if (ELEM(NULL, ipo, anim, drivers)) return; - + if (G.debug & G_DEBUG) printf("ipo_to_animato\n"); - - /* validate actname and constname + + /* validate actname and constname * - clear actname if it was one of the generic ones (i.e. 'Object', or 'Shapes') - * - actname can then be used to assign F-Curves in Action to Action Groups + * - actname can then be used to assign F-Curves in Action to Action Groups * (i.e. thus keeping the benefits that used to be provided by Action Channels for grouping * F-Curves for bones). This may be added later... for now let's just dump without them... */ @@ -1423,10 +1423,10 @@ static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], S else if ((ipo->blocktype == ID_OB) && STREQ(actname, "Shape")) actname = NULL; } - + /* loop over IPO-Curves, freeing as we progress */ for (icu = ipo->curve.first; icu; icu = icu->next) { - /* Since an IPO-Curve may end up being made into many F-Curves (i.e. bitflag curves), + /* Since an IPO-Curve may end up being made into many F-Curves (i.e. bitflag curves), * we figure out the best place to put the channel, then tell the curve-converter to just dump there */ if (icu->driver) { @@ -1442,23 +1442,23 @@ static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], S else icu_to_fcurves(id, animgroups, anim, icu, actname, constname, seq, ipo->muteipo); } - + /* if this IPO block doesn't have any users after this one, free... */ id_us_min(&ipo->id); if (ID_REAL_USERS(ipo) <= 0) { IpoCurve *icn; - + for (icu = ipo->curve.first; icu; icu = icn) { icn = icu->next; - + /* free driver */ if (icu->driver) MEM_freeN(icu->driver); - + /* free old data of curve now that it's no longer needed for converting any more curves */ if (icu->bezt) MEM_freeN(icu->bezt); if (icu->bp) MEM_freeN(icu->bezt); - + /* free this IPO-Curve */ BLI_freelinkN(&ipo->curve, icu); } @@ -1474,44 +1474,44 @@ static void action_to_animato(ID *id, bAction *act, ListBase *groups, ListBase * { bActionChannel *achan, *achann; bConstraintChannel *conchan, *conchann; - + /* only continue if there are Action Channels (indicating unconverted data) */ if (BLI_listbase_is_empty(&act->chanbase)) return; - + /* get rid of all Action Groups */ // XXX this is risky if there's some old + some new data in the Action... - if (act->groups.first) + if (act->groups.first) BLI_freelistN(&act->groups); - + /* loop through Action-Channels, converting data, freeing as we go */ for (achan = act->chanbase.first; achan; achan = achann) { /* get pointer to next Action Channel */ achann = achan->next; - + /* convert Action Channel's IPO data */ if (achan->ipo) { ipo_to_animato(id, achan->ipo, achan->name, NULL, NULL, groups, curves, drivers); id_us_min(&achan->ipo->id); achan->ipo = NULL; } - + /* convert constraint channel IPO-data */ for (conchan = achan->constraintChannels.first; conchan; conchan = conchann) { /* get pointer to next Constraint Channel */ conchann = conchan->next; - + /* convert Constraint Channel's IPO data */ if (conchan->ipo) { ipo_to_animato(id, conchan->ipo, achan->name, conchan->name, NULL, groups, curves, drivers); id_us_min(&conchan->ipo->id); conchan->ipo = NULL; } - + /* free Constraint Channel */ BLI_freelinkN(&achan->constraintChannels, conchan); } - + /* free Action Channel */ BLI_freelinkN(&act->chanbase, achan); } @@ -1529,7 +1529,7 @@ static void ipo_to_animdata(Main *bmain, ID *id, Ipo *ipo, char actname[], char AnimData *adt = BKE_animdata_from_id(id); ListBase anim = {NULL, NULL}; ListBase drivers = {NULL, NULL}; - + /* sanity check */ if (ELEM(NULL, id, ipo)) return; @@ -1537,36 +1537,36 @@ static void ipo_to_animdata(Main *bmain, ID *id, Ipo *ipo, char actname[], char printf("ERROR ipo_to_animdata(): adt invalid\n"); return; } - + if (G.debug & G_DEBUG) { printf("ipo to animdata - ID:%s, IPO:%s, actname:%s constname:%s seqname:%s curves:%d\n", id->name + 2, ipo->id.name + 2, (actname) ? actname : "", (constname) ? constname : "", (seq) ? (seq->name + 2) : "", BLI_listbase_count(&ipo->curve)); } - + /* Convert curves to animato system (separated into separate lists of F-Curves for animation and drivers), * and the try to put these lists in the right places, but do not free the lists here */ - // XXX there shouldn't be any need for the groups, so don't supply pointer for that now... + // XXX there shouldn't be any need for the groups, so don't supply pointer for that now... ipo_to_animato(id, ipo, actname, constname, seq, NULL, &anim, &drivers); - + /* deal with animation first */ if (anim.first) { if (G.debug & G_DEBUG) printf("\thas anim\n"); /* try to get action */ if (adt->action == NULL) { char nameBuf[MAX_ID_NAME]; - + BLI_snprintf(nameBuf, sizeof(nameBuf), "CDA:%s", ipo->id.name + 2); - + adt->action = BKE_action_add(bmain, nameBuf); if (G.debug & G_DEBUG) printf("\t\tadded new action - '%s'\n", nameBuf); } - + /* add F-Curves to action */ BLI_movelisttolist(&adt->action->curves, &anim); } - + /* deal with drivers */ if (drivers.first) { if (G.debug & G_DEBUG) printf("\thas drivers\n"); @@ -1581,18 +1581,18 @@ static void ipo_to_animdata(Main *bmain, ID *id, Ipo *ipo, char actname[], char static void action_to_animdata(ID *id, bAction *act) { AnimData *adt = BKE_animdata_from_id(id); - + /* only continue if there are Action Channels (indicating unconverted data) */ if (ELEM(NULL, adt, act->chanbase.first)) return; - + /* check if we need to set this Action as the AnimData's action */ if (adt->action == NULL) { /* set this Action as AnimData's Action */ if (G.debug & G_DEBUG) printf("act_to_adt - set adt action to act\n"); adt->action = act; } - + /* convert Action data */ action_to_animato(id, act, &adt->action->groups, &adt->action->curves, &adt->drivers); } @@ -1610,25 +1610,25 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) NlaTrack *nlt = NULL; NlaStrip *strip; bActionStrip *as, *asn; - + /* for each one of the original strips, convert to a new strip and free the old... */ for (as = strips->first; as; as = asn) { asn = as->next; - + /* this old strip is only worth something if it had an action... */ if (as->act) { /* convert Action data (if not yet converted), storing the results in the same Action */ action_to_animato(id, as->act, &as->act->groups, &as->act->curves, &adt->drivers); - + /* create a new-style NLA-strip which references this Action, then copy over relevant settings */ { - /* init a new strip, and assign the action to it - * - no need to muck around with the user-counts, since this is just + /* init a new strip, and assign the action to it + * - no need to muck around with the user-counts, since this is just * passing over the ref to the new owner, not creating an additional ref */ strip = MEM_callocN(sizeof(NlaStrip), "NlaStrip"); strip->act = as->act; - + /* endpoints */ strip->start = as->start; strip->end = as->end; @@ -1657,25 +1657,25 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) if ((as->flag & ACTSTRIP_HOLDLASTFRAME) == 0) strip->extendmode = NLASTRIP_EXTEND_NOTHING; } - + /* try to add this strip to the current NLA-Track (i.e. the 'last' one on the stack atm) */ if (BKE_nlatrack_add_strip(nlt, strip) == 0) { - /* trying to add to the current failed (no space), + /* trying to add to the current failed (no space), * so add a new track to the stack, and add to that... */ nlt = BKE_nlatrack_add(adt, NULL); BKE_nlatrack_add_strip(nlt, strip); } - + /* ensure that strip has a name */ BKE_nlastrip_validate_name(adt, strip); } - + /* modifiers */ // FIXME: for now, we just free them... if (as->modifiers.first) BLI_freelistN(&as->modifiers); - + /* free the old strip */ BLI_freelinkN(strips, as); } @@ -1694,17 +1694,17 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) * Data that has been converted should be freed immediately, which means that it is immediately * clear which datablocks have yet to be converted, and also prevent freeing errors when we exit. */ -// XXX currently done after all file reading... +// XXX currently done after all file reading... void do_versions_ipos_to_animato(Main *bmain) { ListBase drivers = {NULL, NULL}; ID *id; - + if (bmain == NULL) { printf("Argh! Main is NULL in do_versions_ipos_to_animato()\n"); return; } - + /* only convert if version is right */ if (bmain->versionfile >= 250) { printf("WARNING: Animation data too new to convert (Version %d)\n", bmain->versionfile); @@ -1712,61 +1712,60 @@ void do_versions_ipos_to_animato(Main *bmain) } else if (G.debug & G_DEBUG) printf("INFO: Converting to Animato...\n"); - + /* ----------- Animation Attached to Data -------------- */ - + /* objects */ for (id = bmain->object.first; id; id = id->next) { Object *ob = (Object *)id; bPoseChannel *pchan; bConstraint *con; bConstraintChannel *conchan, *conchann; - + if (G.debug & G_DEBUG) printf("\tconverting ob %s\n", id->name + 2); - + /* check if object has any animation data */ if (ob->nlastrips.first) { /* Add AnimData block */ BKE_animdata_add_id(id); - + /* IPO first to take into any non-NLA'd Object Animation */ if (ob->ipo) { ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); - - id_us_min(&ob->ipo->id); + /* No need to id_us_min ipo ID here, ipo_to_animdata already does it. */ ob->ipo = NULL; } - - /* Action is skipped since it'll be used by some strip in the NLA anyway, + + /* Action is skipped since it'll be used by some strip in the NLA anyway, * causing errors with evaluation in the new evaluation pipeline */ if (ob->action) { id_us_min(&ob->action->id); ob->action = NULL; } - + /* finally NLA */ nlastrips_to_animdata(id, &ob->nlastrips); } else if ((ob->ipo) || (ob->action)) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Action first - so that Action name get conserved */ if (ob->action) { action_to_animdata(id, ob->action); - + /* only decrease usercount if this Action isn't now being used by AnimData */ if (ob->action != adt->action) { id_us_min(&ob->action->id); ob->action = NULL; } } - + /* IPO second... */ if (ob->ipo) { ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); - id_us_min(&ob->ipo->id); + /* No need to id_us_min ipo ID here, ipo_to_animdata already does it. */ ob->ipo = NULL; { @@ -1787,19 +1786,19 @@ void do_versions_ipos_to_animato(Main *bmain) } } } - + /* check PoseChannels for constraints with local data */ if (ob->pose) { /* Verify if there's AnimData block */ BKE_animdata_add_id(id); - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { - /* if constraint has own IPO, convert add these to Object - * (NOTE: they're most likely to be drivers too) + /* if constraint has own IPO, convert add these to Object + * (NOTE: they're most likely to be drivers too) */ if (con->ipo) { - /* although this was the constraint's local IPO, we still need to provide pchan + con + /* although this was the constraint's local IPO, we still need to provide pchan + con * so that drivers can be added properly... */ ipo_to_animdata(bmain, id, con->ipo, pchan->name, con->name, NULL); @@ -1809,49 +1808,49 @@ void do_versions_ipos_to_animato(Main *bmain) } } } - + /* check constraints for local IPO's */ for (con = ob->constraints.first; con; con = con->next) { - /* if constraint has own IPO, convert add these to Object - * (NOTE: they're most likely to be drivers too) + /* if constraint has own IPO, convert add these to Object + * (NOTE: they're most likely to be drivers too) */ if (con->ipo) { /* Verify if there's AnimData block, just in case */ BKE_animdata_add_id(id); - - /* although this was the constraint's local IPO, we still need to provide con + + /* although this was the constraint's local IPO, we still need to provide con * so that drivers can be added properly... */ ipo_to_animdata(bmain, id, con->ipo, NULL, con->name, NULL); id_us_min(&con->ipo->id); con->ipo = NULL; } - + /* check for Action Constraint */ // XXX do we really want to do this here? } - + /* check constraint channels - we need to remove them anyway... */ if (ob->constraintChannels.first) { /* Verify if there's AnimData block */ BKE_animdata_add_id(id); - + for (conchan = ob->constraintChannels.first; conchan; conchan = conchann) { /* get pointer to next Constraint Channel */ conchann = conchan->next; - + /* convert Constraint Channel's IPO data */ if (conchan->ipo) { ipo_to_animdata(bmain, id, conchan->ipo, NULL, conchan->name, NULL); id_us_min(&conchan->ipo->id); conchan->ipo = NULL; } - + /* free Constraint Channel */ BLI_freelinkN(&ob->constraintChannels, conchan); } } - + /* object's action will always be object-rooted */ { AnimData *adt = BKE_animdata_from_id(id); @@ -1859,100 +1858,100 @@ void do_versions_ipos_to_animato(Main *bmain) adt->action->idroot = ID_OB; } } - + /* shapekeys */ for (id = bmain->key.first; id; id = id->next) { Key *key = (Key *)id; - + if (G.debug & G_DEBUG) printf("\tconverting key %s\n", id->name + 2); - - /* we're only interested in the IPO + + /* we're only interested in the IPO * NOTE: for later, it might be good to port these over to Object instead, as many of these * are likely to be drivers, but it's hard to trace that from here, so move this to Ob loop? */ if (key->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Shapekey data... */ ipo_to_animdata(bmain, id, key->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = key->ipo->blocktype; - + id_us_min(&key->ipo->id); key->ipo = NULL; } } - + /* materials */ for (id = bmain->mat.first; id; id = id->next) { Material *ma = (Material *)id; - + if (G.debug & G_DEBUG) printf("\tconverting material %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (ma->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Material data... */ ipo_to_animdata(bmain, id, ma->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = ma->ipo->blocktype; - + id_us_min(&ma->ipo->id); ma->ipo = NULL; } } - + /* worlds */ for (id = bmain->world.first; id; id = id->next) { World *wo = (World *)id; - + if (G.debug & G_DEBUG) printf("\tconverting world %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (wo->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert World data... */ ipo_to_animdata(bmain, id, wo->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = wo->ipo->blocktype; - + id_us_min(&wo->ipo->id); wo->ipo = NULL; } } - + /* sequence strips */ for (id = bmain->scene.first; id; id = id->next) { Scene *scene = (Scene *)id; Editing *ed = scene->ed; if (ed && ed->seqbasep) { Sequence *seq; - + AnimData *adt = BKE_animdata_add_id(id); - + SEQ_BEGIN(ed, seq) { IpoCurve *icu = (seq->ipo) ? seq->ipo->curve.first : NULL; short adrcode = SEQ_FAC1; - + if (G.debug & G_DEBUG) printf("\tconverting sequence strip %s\n", seq->name + 2); - + if (ELEM(NULL, seq->ipo, icu)) { seq->flag |= SEQ_USE_EFFECT_DEFAULT_FADE; continue; } - + /* patch adrcode, so that we can map - * to different DNA variables later + * to different DNA variables later * (semi-hack (tm) ) */ switch (seq->type) { @@ -1968,13 +1967,13 @@ void do_versions_ipos_to_animato(Main *bmain) break; } icu->adrcode = adrcode; - + /* convert IPO */ ipo_to_animdata(bmain, (ID *)scene, seq->ipo, NULL, NULL, seq); - + if (adt->action) adt->action->idroot = ID_SCE; /* scene-rooted */ - + id_us_min(&seq->ipo->id); seq->ipo = NULL; } @@ -1986,141 +1985,140 @@ void do_versions_ipos_to_animato(Main *bmain) /* textures */ for (id = bmain->tex.first; id; id = id->next) { Tex *te = (Tex *)id; - + if (G.debug & G_DEBUG) printf("\tconverting texture %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (te->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Texture data... */ ipo_to_animdata(bmain, id, te->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = te->ipo->blocktype; - + id_us_min(&te->ipo->id); te->ipo = NULL; } } - + /* cameras */ for (id = bmain->camera.first; id; id = id->next) { Camera *ca = (Camera *)id; - + if (G.debug & G_DEBUG) printf("\tconverting camera %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (ca->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Camera data... */ ipo_to_animdata(bmain, id, ca->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = ca->ipo->blocktype; - + id_us_min(&ca->ipo->id); ca->ipo = NULL; } } - + /* lamps */ for (id = bmain->lamp.first; id; id = id->next) { Lamp *la = (Lamp *)id; - + if (G.debug & G_DEBUG) printf("\tconverting lamp %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (la->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Lamp data... */ ipo_to_animdata(bmain, id, la->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = la->ipo->blocktype; - + id_us_min(&la->ipo->id); la->ipo = NULL; } } - + /* curves */ for (id = bmain->curve.first; id; id = id->next) { Curve *cu = (Curve *)id; - + if (G.debug & G_DEBUG) printf("\tconverting curve %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (cu->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Curve data... */ ipo_to_animdata(bmain, id, cu->ipo, NULL, NULL, NULL); - + if (adt->action) adt->action->idroot = cu->ipo->blocktype; - + id_us_min(&cu->ipo->id); cu->ipo = NULL; } } - + /* --------- Unconverted Animation Data ------------------ */ - /* For Animation data which may not be directly connected (i.e. not linked) to any other + /* For Animation data which may not be directly connected (i.e. not linked) to any other * data, we need to perform a separate pass to make sure that they are converted to standalone * Actions which may then be able to be reused. This does mean that we will be going over data that's * already been converted, but there are no problems with that. * - * The most common case for this will be Action Constraints, or IPO's with Fake-Users. - * We collect all drivers that were found into a temporary collection, and free them in one go, as they're + * The most common case for this will be Action Constraints, or IPO's with Fake-Users. + * We collect all drivers that were found into a temporary collection, and free them in one go, as they're * impossible to resolve. */ - + /* actions */ for (id = bmain->action.first; id; id = id->next) { bAction *act = (bAction *)id; - + if (G.debug & G_DEBUG) printf("\tconverting action %s\n", id->name + 2); - + /* if old action, it will be object-only... */ if (act->chanbase.first) act->idroot = ID_OB; - + /* be careful! some of the actions we encounter will be converted ones... */ action_to_animato(NULL, act, &act->groups, &act->curves, &drivers); } - + /* ipo's */ for (id = bmain->ipo.first; id; id = id->next) { Ipo *ipo = (Ipo *)id; - + if (G.debug & G_DEBUG) printf("\tconverting ipo %s\n", id->name + 2); - + /* most likely this IPO has already been processed, so check if any curves left to convert */ if (ipo->curve.first) { bAction *new_act; - + /* add a new action for this, and convert all data into that action */ new_act = BKE_action_add(bmain, id->name + 2); ipo_to_animato(NULL, ipo, NULL, NULL, NULL, NULL, &new_act->curves, &drivers); new_act->idroot = ipo->blocktype; } - + /* clear fake-users, and set user-count to zero to make sure it is cleared on file-save */ ipo->id.us = 0; ipo->id.flag &= ~LIB_FAKEUSER; } - + /* free unused drivers from actions + ipos */ free_fcurves(&drivers); - + if (G.debug & G_DEBUG) printf("INFO: Animato convert done\n"); } - diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index e63f7d7cefef..4689575655e7 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -106,14 +106,14 @@ Key *BKE_key_add(Main *bmain, ID *id) /* common function */ { Key *key; char *el; - + key = BKE_libblock_alloc(bmain, ID_KE, "Key", 0); - + key->type = KEY_NORMAL; key->from = id; key->uidgen = 1; - + /* XXX the code here uses some defines which will soon be deprecated... */ switch (GS(id->name)) { case ID_ME: @@ -150,7 +150,7 @@ Key *BKE_key_add(Main *bmain, ID *id) /* common function */ default: break; } - + return key; } @@ -192,24 +192,24 @@ Key *BKE_key_copy_nolib(Key *key) { Key *keyn; KeyBlock *kbn, *kb; - + keyn = MEM_dupallocN(key); keyn->adt = NULL; BLI_duplicatelist(&keyn->block, &key->block); - + kb = key->block.first; kbn = keyn->block.first; while (kbn) { - + if (kbn->data) kbn->data = MEM_dupallocN(kbn->data); if (kb == key->refkey) keyn->refkey = kbn; - + kbn = kbn->next; kb = kb->next; } - + return keyn; } @@ -223,7 +223,7 @@ void BKE_key_sort(Key *key) KeyBlock *kb; KeyBlock *kb2; - /* locate the key which is out of position */ + /* locate the key which is out of position */ for (kb = key->block.first; kb; kb = kb->next) if ((kb->next) && (kb->pos > kb->next->pos)) break; @@ -232,7 +232,7 @@ void BKE_key_sort(Key *key) if (kb) { kb = kb->next; /* next key is the out-of-order one */ BLI_remlink(&key->block, kb); - + /* find the right location and insert before */ for (kb2 = key->block.first; kb2; kb2 = kb2->next) { if (kb2->pos > kb->pos) { @@ -251,7 +251,7 @@ void BKE_key_sort(Key *key) void key_curve_position_weights(float t, float data[4], int type) { float t2, t3, fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = -t + 1.0f; @@ -293,7 +293,7 @@ void key_curve_position_weights(float t, float data[4], int type) void key_curve_tangent_weights(float t, float data[4], int type) { float t2, fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = -1.0f; @@ -332,7 +332,7 @@ void key_curve_tangent_weights(float t, float data[4], int type) void key_curve_normal_weights(float t, float data[4], int type) { float fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = 0.0f; @@ -415,7 +415,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) t[3] = k[3]->pos; k1 = k[3]; } - + while (t[2] < fac) { /* find correct location */ if (k1->next == NULL) { if (cycl) { @@ -441,7 +441,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) if (ofs > 2.1f + lastpos) break; } - + bsplinetype = 0; if (k[1]->type == KEY_BSPLINE || k[2]->type == KEY_BSPLINE) bsplinetype = 1; @@ -499,7 +499,7 @@ static void flerp(int tot, float *in, float *f0, float *f1, float *f2, float *f3 static void rel_flerp(int tot, float *in, float *ref, float *out, float fac) { int a; - + for (a = 0; a < tot; a++) { in[a] -= fac * (ref[a] - out[a]); } @@ -588,7 +588,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key return; if (end > tot) end = tot; - + if (tot != kb->totelem) { ktot = 0.0; flagflo = 1; @@ -605,9 +605,9 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key /* this exception is needed curves with multiple splines */ if (start != 0) { - + poin += poinsize * start; - + if (flagflo) { ktot += start * kd; a = (int)floor(ktot); @@ -620,13 +620,13 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key k1 += start * key->elemsize; } } - + if (mode == KEY_MODE_BEZTRIPLE) { elemstr[0] = 1; elemstr[1] = IPO_BEZTRIPLE; elemstr[2] = 0; } - + /* just do it here, not above! */ elemsize = key->elemsize; if (mode == KEY_MODE_BEZTRIPLE) elemsize *= 3; @@ -668,7 +668,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key poin += *ofsp; cp += 2; ofsp++; } - + /* are we going to be nasty? */ if (flagflo) { ktot += kd; @@ -682,7 +682,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key k1 += elemsize; kref += elemsize; } - + if (mode == KEY_MODE_BEZTRIPLE) { a += 2; } @@ -748,13 +748,13 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba /* step 1 init */ cp_key(start, end, tot, basispoin, key, actkb, key->refkey, NULL, mode); - + /* step 2: do it */ - + for (kb = key->block.first, keyblock_index = 0; kb; kb = kb->next, keyblock_index++) { if (kb != key->refkey) { float icuval = kb->curval; - + /* only with value, and no difference allowed */ if (!(kb->flag & KEYBLOCK_MUTE) && icuval != 0.0f && kb->totelem == tot) { KeyBlock *refb; @@ -764,7 +764,7 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba /* reference now can be any block */ refb = BLI_findlink(&key->block, kb->relative); if (refb == NULL) continue; - + poin = basispoin; from = key_block_get_data(key, actkb, kb, &freefrom); reffrom = key_block_get_data(key, actkb, refb, &freereffrom); @@ -772,18 +772,18 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba poin += start * poinsize; reffrom += key->elemsize * start; // key elemsize yes! from += key->elemsize * start; - + for (b = start; b < end; b++) { - + weight = weights ? (*weights * icuval) : icuval; - + cp = key->elemstr; if (mode == KEY_MODE_BEZTRIPLE) cp = elemstr; - + ofsp = ofs; - + while (cp[0]) { /* (cp[0] == amount) */ - + switch (cp[1]) { case IPO_FLOAT: rel_flerp(3, (float *)poin, (float *)reffrom, (float *)from, weight); @@ -803,14 +803,14 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba } poin += *ofsp; - + cp += 2; ofsp++; } - + reffrom += elemsize; from += elemsize; - + if (mode == KEY_MODE_BEZTRIPLE) b += 2; if (weights) weights++; } @@ -837,7 +837,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (!key_pointer_size(key, mode, &poinsize, &ofs[0])) return; - + if (end > tot) end = tot; k1 = key_block_get_data(key, actkb, k[0], &freek1); @@ -891,7 +891,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (start != 0) { poin += poinsize * start; - + if (flagdo & 1) { if (flagflo & 1) { k1tot += start * k1d; @@ -957,10 +957,10 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (mode == KEY_MODE_BEZTRIPLE) elemsize *= 3; for (a = start; a < end; a++) { - + cp = key->elemstr; if (mode == KEY_MODE_BEZTRIPLE) cp = elemstr; - + ofsp = ofs; while (cp[0]) { /* (cp[0] == amount) */ @@ -984,7 +984,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key BLI_assert(!"invalid 'cp[1]'"); return; } - + poin += *ofsp; cp += 2; ofsp++; @@ -1038,7 +1038,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key k4 += elemsize; } } - + if (mode == KEY_MODE_BEZTRIPLE) a += 2; } @@ -1055,10 +1055,10 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac BMIter iter; BMVert *eve; int totvert = 0, defgrp_index = 0; - + /* no vgroup string set? */ if (vgroup[0] == 0) return NULL; - + /* gather dvert and totvert */ if (ob->type == OB_MESH) { Mesh *me = ob->data; @@ -1073,9 +1073,9 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac dvert = lt->dvert; totvert = lt->pntsu * lt->pntsv * lt->pntsw; } - + if (dvert == NULL) return NULL; - + /* find the group (weak loop-in-loop) */ defgrp_index = defgroup_name_index(ob, vgroup); if (defgrp_index != -1) { @@ -1197,7 +1197,7 @@ static void do_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock **k, float { Nurb *nu; int a, step; - + for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) { if (nu->bp) { step = nu->pntsu * nu->pntsv; @@ -1217,7 +1217,7 @@ static void do_rel_cu_key(Curve *cu, Key *key, KeyBlock *actkb, char *out, const { Nurb *nu; int a, step; - + for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) { if (nu->bp) { step = nu->pntsu * nu->pntsv; @@ -1263,7 +1263,7 @@ static void do_latt_key(Object *ob, Key *key, char *out, const int tot) KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob); float t[4]; int flag; - + if (key->type == KEY_RELATIVE) { float **per_keyblock_weights; per_keyblock_weights = BKE_keyblock_get_per_block_weights(ob, key, NULL); @@ -1272,7 +1272,7 @@ static void do_latt_key(Object *ob, Key *key, char *out, const int tot) } else { const float ctime_scaled = key->ctime / 100.0f; - + flag = setkeys(ctime_scaled, &key->block, k, t, 0); if (flag == 0) { @@ -1331,7 +1331,7 @@ float *BKE_key_evaluate_object_ex( /* if nothing to interpolate, cancel */ if (tot == 0 || size == 0) return NULL; - + /* allocate array */ if (arr == NULL) { out = MEM_callocN(size, "BKE_key_evaluate_object out"); @@ -1346,11 +1346,11 @@ float *BKE_key_evaluate_object_ex( /* prevent python from screwing this up? anyhoo, the from pointer could be dropped */ key->from = (ID *)ob->data; - + if (ob->shapeflag & OB_SHAPE_LOCK) { /* shape locked, copy the locked shape instead of blending */ KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1); - + if (kb && (kb->flag & KEYBLOCK_MUTE)) kb = key->refkey; @@ -1358,7 +1358,7 @@ float *BKE_key_evaluate_object_ex( kb = key->block.first; ob->shapenr = 1; } - + if (OB_TYPE_SUPPORT_VGROUP(ob->type)) { float *weights = get_weights_array(ob, kb->vgroup, NULL); @@ -1370,13 +1370,13 @@ float *BKE_key_evaluate_object_ex( cp_cu_key(ob->data, key, actkb, kb, 0, tot, out, tot); } else { - + if (ob->type == OB_MESH) do_mesh_key(ob, key, out, tot); else if (ob->type == OB_LATTICE) do_latt_key(ob, key, out, tot); else if (ob->type == OB_CURVE) do_curve_key(ob, key, out, tot); else if (ob->type == OB_SURF) do_curve_key(ob, key, out, tot); } - + if (r_totelem) { *r_totelem = tot; } @@ -1451,14 +1451,14 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) KeyBlock *kb; float curpos = -0.1; int tot; - + kb = key->block.last; if (kb) curpos = kb->pos; - + kb = MEM_callocN(sizeof(KeyBlock), "Keyblock"); BLI_addtail(&key->block, kb); kb->type = KEY_CARDINAL; - + tot = BLI_listbase_count(&key->block); if (name) { BLI_strncpy(kb->name, name, sizeof(kb->name)); @@ -1476,7 +1476,7 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) key->totkey++; if (key->totkey == 1) key->refkey = kb; - + kb->slidermin = 0.0f; kb->slidermax = 1.0f; @@ -1523,10 +1523,10 @@ KeyBlock *BKE_keyblock_add_ctime(Key *key, const char *name, const bool do_force } /* only the active keyblock */ -KeyBlock *BKE_keyblock_from_object(Object *ob) +KeyBlock *BKE_keyblock_from_object(Object *ob) { Key *key = BKE_key_from_object(ob); - + if (key) { KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1); return kb; @@ -1538,7 +1538,7 @@ KeyBlock *BKE_keyblock_from_object(Object *ob) KeyBlock *BKE_keyblock_from_object_reference(Object *ob) { Key *key = BKE_key_from_object(ob); - + if (key) return key->refkey; @@ -1550,18 +1550,18 @@ KeyBlock *BKE_keyblock_from_key(Key *key, int index) { KeyBlock *kb; int i; - + if (key) { kb = key->block.first; - + for (i = 1; i < key->totkey; i++) { kb = kb->next; - + if (index == i) return kb; } } - + return NULL; } @@ -1585,23 +1585,23 @@ void BKE_keyblock_copy_settings(KeyBlock *kb_dst, const KeyBlock *kb_src) kb_dst->slidermax = kb_src->slidermax; } -/* Get RNA-Path for 'value' setting of the given ShapeKey +/* Get RNA-Path for 'value' setting of the given ShapeKey * NOTE: the user needs to free the returned string once they're finish with it */ char *BKE_keyblock_curval_rnapath_get(Key *key, KeyBlock *kb) { PointerRNA ptr; PropertyRNA *prop; - + /* sanity checks */ if (ELEM(NULL, key, kb)) return NULL; - + /* create the RNA pointer */ RNA_pointer_create(&key->id, &RNA_ShapeKey, kb, &ptr); /* get pointer to the property too */ prop = RNA_struct_find_property(&ptr, "value"); - + /* return the path */ return RNA_path_from_ID_to_property(&ptr, prop); } @@ -1689,7 +1689,7 @@ void BKE_keyblock_update_from_curve(Curve *UNUSED(cu), KeyBlock *kb, ListBase *n } } else { - + ; for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, fp += 4, bp++) { copy_v3_v3(fp, bp->vec); diff --git a/source/blender/blenkernel/intern/lamp.c b/source/blender/blenkernel/intern/lamp.c index ae07641ad78b..387bb2b0dfec 100644 --- a/source/blender/blenkernel/intern/lamp.c +++ b/source/blender/blenkernel/intern/lamp.c @@ -102,7 +102,7 @@ void BKE_lamp_init(Lamp *la) la->sky_colorspace = BLI_XYZ_CIE; la->sky_exposure = 1.0f; la->shadow_frustum_size = 10.0f; - + curvemapping_initialize(la->curfalloff); } @@ -168,7 +168,7 @@ Lamp *BKE_lamp_localize(Lamp *la) Lamp *lan; int a; - + lan = BKE_libblock_copy_nolib(&la->id, false); for (a = 0; a < MAX_MTEX; a++) { @@ -177,12 +177,12 @@ Lamp *BKE_lamp_localize(Lamp *la) memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex)); } } - + lan->curfalloff = curvemapping_copy(la->curfalloff); if (la->nodetree) lan->nodetree = ntreeLocalize(la->nodetree); - + lan->preview = NULL; return lan; @@ -200,7 +200,7 @@ void BKE_lamp_free(Lamp *la) for (a = 0; a < MAX_MTEX; a++) { MEM_SAFE_FREE(la->mtex[a]); } - + BKE_animdata_free((ID *)la, false); curvemapping_free(la->curfalloff); @@ -211,7 +211,7 @@ void BKE_lamp_free(Lamp *la) MEM_freeN(la->nodetree); la->nodetree = NULL; } - + BKE_previewimg_free(&la->preview); BKE_icon_id_delete(&la->id); la->id.icon_id = 0; @@ -226,7 +226,7 @@ static void lamp_node_drivers_update(Scene *scene, bNodeTree *ntree, float ctime /* nodetree itself */ if (ntree->adt && ntree->adt->drivers.first) BKE_animsys_evaluate_animdata(scene, &ntree->id, ntree->adt, ctime, ADT_RECALC_DRIVERS); - + /* nodes */ for (node = ntree->nodes.first; node; node = node->next) if (node->id && node->type == NODE_GROUP) @@ -242,15 +242,14 @@ void lamp_drivers_update(Scene *scene, Lamp *la, float ctime) return; la->id.tag |= LIB_TAG_DOIT; - + /* lamp itself */ if (la->adt && la->adt->drivers.first) BKE_animsys_evaluate_animdata(scene, &la->id, la->adt, ctime, ADT_RECALC_DRIVERS); - + /* nodes */ if (la->nodetree) lamp_node_drivers_update(scene, la->nodetree, ctime); la->id.tag &= ~LIB_TAG_DOIT; } - diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index edca0257d201..582743acff47 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -156,13 +156,13 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) int i, u, v, w; float fu, fv, fw, uc, vc, wc, du = 0.0, dv = 0.0, dw = 0.0; float *co, (*vertexCos)[3] = NULL; - + /* vertex weight groups are just freed all for now */ if (lt->dvert) { BKE_defvert_array_free(lt->dvert, lt->pntsu * lt->pntsv * lt->pntsw); lt->dvert = NULL; } - + while (uNew * vNew * wNew > 32000) { if (uNew >= vNew && uNew >= wNew) uNew--; else if (vNew >= uNew && vNew >= wNew) vNew--; @@ -207,7 +207,7 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) } } } - + if (ltOb) { float mat[4][4]; int typeu = lt->typeu, typev = lt->typev, typew = lt->typew; @@ -242,9 +242,9 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) lt->actbp = LT_ACTBP_NONE; MEM_freeN(lt->def); lt->def = MEM_callocN(lt->pntsu * lt->pntsv * lt->pntsw * sizeof(BPoint), "lattice bp"); - + bp = lt->def; - + for (i = 0; i < lt->pntsu * lt->pntsv * lt->pntsw; i++, bp++) { copy_v3_v3(bp->vec, vertexCos[i]); } @@ -257,9 +257,9 @@ void BKE_lattice_init(Lattice *lt) BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(lt, id)); lt->flag = LT_GRID; - + lt->typeu = lt->typev = lt->typew = KEY_BSPLINE; - + lt->def = MEM_callocN(sizeof(BPoint), "lattvert"); /* temporary */ BKE_lattice_resize(lt, 2, 2, 2, NULL); /* creates a uniform lattice */ lt->actbp = LT_ACTBP_NONE; @@ -360,14 +360,14 @@ LatticeDeformData *init_latt_deform(Object *oblatt, Object *ob) if (lt->editlatt) lt = lt->editlatt->latt; bp = lt->def; - + fp = latticedata = MEM_mallocN(sizeof(float) * 3 * lt->pntsu * lt->pntsv * lt->pntsw, "latticedata"); - + /* for example with a particle system: (ob == NULL) */ if (ob == NULL) { /* in deformspace, calc matrix */ invert_m4_m4(latmat, oblatt->obmat); - + /* back: put in deform array */ invert_m4_m4(imat, latmat); } @@ -375,11 +375,11 @@ LatticeDeformData *init_latt_deform(Object *oblatt, Object *ob) /* in deformspace, calc matrix */ invert_m4_m4(imat, oblatt->obmat); mul_m4_m4m4(latmat, imat, ob->obmat); - + /* back: put in deform array */ invert_m4_m4(imat, latmat); } - + for (w = 0, fw = lt->fw; w < lt->pntsw; w++, fw += lt->dw) { for (v = 0, fv = lt->fv; v < lt->pntsv; v++, fv += lt->dv) { for (u = 0, fu = lt->fu; u < lt->pntsu; u++, bp++, co += 3, fp += 3, fu += lt->du) { @@ -555,7 +555,7 @@ static bool where_on_path_deform(Object *ob, float ctime, float vec[4], float di BevList *bl; float ctime1; int cycl = 0; - + /* test for cyclic */ bl = ob->curve_cache->bev.first; if (!bl->nr) return false; @@ -567,14 +567,14 @@ static bool where_on_path_deform(Object *ob, float ctime, float vec[4], float di else { ctime1 = ctime; } - + /* vec needs 4 items */ if (where_on_path(ob, ctime1, vec, dir, quat, radius, NULL)) { - + if (cycl == 0) { Path *path = ob->curve_cache->path; float dvec[3]; - + if (ctime < 0.0f) { sub_v3_v3v3(dvec, path->data[1].vec, path->data[0].vec); mul_v3_fl(dvec, ctime * (float)path->len); @@ -624,7 +624,7 @@ static bool calc_curve_deform(Scene *scene, Object *par, float co[3], if (is_neg_axis) { index = axis - 3; if (cu->flag & CU_STRETCH) - fac = (-co[index] - cd->dmax[index]) / (cd->dmax[index] - cd->dmin[index]); + fac = -(co[index] - cd->dmax[index]) / (cd->dmax[index] - cd->dmin[index]); else fac = -(co[index] - cd->dmax[index]) / (par->curve_cache->path->totdist); } @@ -642,7 +642,7 @@ static bool calc_curve_deform(Scene *scene, Object *par, float co[3], } } } - + if (where_on_path_deform(par, fac, loc, dir, new_quat, &radius)) { /* returns OK */ float quat[4], cent[3]; @@ -688,7 +688,7 @@ static bool calc_curve_deform(Scene *scene, Object *par, float co[3], /* scale if enabled */ if (cu->flag & CU_PATH_RADIUS) mul_v3_fl(cent, radius); - + /* local rotation */ normalize_qt(quat); mul_qt_v3(quat, cent); @@ -732,7 +732,7 @@ void curve_deform_verts( cd.dmin[0] = cd.dmin[1] = cd.dmin[2] = -1.0f; cd.dmax[0] = cd.dmax[1] = cd.dmax[2] = 0.0f; } - + /* Check whether to use vertex groups (only possible if target is a Mesh or Lattice). * We want either a Mesh/Lattice with no derived data, or derived data with deformverts. */ @@ -805,12 +805,12 @@ void curve_deform_verts( else { /* set mesh min max bounds */ INIT_MINMAX(cd.dmin, cd.dmax); - + for (a = 0; a < numVerts; a++) { mul_m4_v3(cd.curvespace, vertexCos[a]); minmax_v3v3_v3(cd.dmin, cd.dmax, vertexCos[a]); } - + for (a = 0; a < numVerts; a++) { /* already in 'cd.curvespace', prev for loop */ calc_curve_deform(scene, cuOb, vertexCos[a], defaxis, &cd, NULL); @@ -828,7 +828,7 @@ void curve_deform_vector(Scene *scene, Object *cuOb, Object *target, { CurveDeform cd; float quat[4]; - + if (cuOb->type != OB_CURVE) { unit_m3(mat); return; @@ -836,21 +836,21 @@ void curve_deform_vector(Scene *scene, Object *cuOb, Object *target, init_curve_deform(cuOb, target, &cd); cd.no_rot_axis = no_rot_axis; /* option to only rotate for XY, for example */ - + copy_v3_v3(cd.dmin, orco); copy_v3_v3(cd.dmax, orco); mul_m4_v3(cd.curvespace, vec); - + if (calc_curve_deform(scene, cuOb, vec, target->trackflag, &cd, quat)) { float qmat[3][3]; - + quat_to_mat3(qmat, quat); mul_m3_m3m3(mat, qmat, cd.objectspace3); } else unit_m3(mat); - + mul_m4_v3(cd.objectspace, vec); } @@ -938,11 +938,11 @@ void outside_lattice(Lattice *lt) if (lt->pntsu > 1) du = 1.0f / ((float)lt->pntsu - 1); if (lt->pntsv > 1) dv = 1.0f / ((float)lt->pntsv - 1); if (lt->pntsw > 1) dw = 1.0f / ((float)lt->pntsw - 1); - + for (w = 0; w < lt->pntsw; w++) { - + for (v = 0; v < lt->pntsv; v++) { - + for (u = 0; u < lt->pntsu; u++, bp++) { if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) { /* pass */ @@ -950,41 +950,41 @@ void outside_lattice(Lattice *lt) else { bp->hide = 1; bp->f1 &= ~SELECT; - + /* u extrema */ bp1 = latt_bp(lt, 0, v, w); bp2 = latt_bp(lt, lt->pntsu - 1, v, w); - + fac1 = du * u; bp->vec[0] = (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] = (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] = (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + /* v extrema */ bp1 = latt_bp(lt, u, 0, w); bp2 = latt_bp(lt, u, lt->pntsv - 1, w); - + fac1 = dv * v; bp->vec[0] += (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] += (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] += (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + /* w extrema */ bp1 = latt_bp(lt, u, v, 0); bp2 = latt_bp(lt, u, v, lt->pntsw - 1); - + fac1 = dw * w; bp->vec[0] += (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] += (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] += (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + mul_v3_fl(bp->vec, 1.0f / 3.0f); - + } } - + } - + } } else { @@ -1005,9 +1005,9 @@ float (*BKE_lattice_vertexcos_get(struct Object *ob, int *r_numVerts))[3] if (lt->editlatt) lt = lt->editlatt->latt; numVerts = *r_numVerts = lt->pntsu * lt->pntsv * lt->pntsw; - + vertexCos = MEM_mallocN(sizeof(*vertexCos) * numVerts, "lt_vcos"); - + for (i = 0; i < numVerts; i++) { copy_v3_v3(vertexCos[i], lt->def[i].vec); } @@ -1044,7 +1044,7 @@ void BKE_lattice_modifiers_calc(Scene *scene, Object *ob) const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!(mti->flags & eModifierTypeFlag_AcceptsLattice)) continue; if (!(md->mode & eModifierMode_Realtime)) continue; if (editmode && !(md->mode & eModifierMode_Editmode)) continue; @@ -1057,14 +1057,14 @@ void BKE_lattice_modifiers_calc(Scene *scene, Object *ob) /* always displist to make this work like derivedmesh */ if (!vertexCos) vertexCos = BKE_lattice_vertexcos_get(ob, &numVerts); - + { DispList *dl = MEM_callocN(sizeof(*dl), "lt_dl"); dl->type = DL_VERTS; dl->parts = 1; dl->nr = numVerts; dl->verts = (float *) vertexCos; - + BLI_addtail(&ob->curve_cache->disp, dl); } } @@ -1146,7 +1146,7 @@ void BKE_lattice_minmax_dl(Object *ob, Lattice *lt, float min[3], float max[3]) } else { int i, numVerts; - + if (lt->editlatt) lt = lt->editlatt->latt; numVerts = lt->pntsu * lt->pntsv * lt->pntsw; @@ -1230,4 +1230,3 @@ void BKE_lattice_eval_geometry(EvaluationContext *UNUSED(eval_ctx), Lattice *UNUSED(latt)) { } - diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index df90c365dbc4..0eb943cc15b9 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -139,7 +139,7 @@ # include "PIL_time_utildefines.h" #endif -/* GS reads the memory pointed at in a specific ordering. +/* GS reads the memory pointed at in a specific ordering. * only use this definition, makes little and big endian systems * work fine, in conjunction with MAKE_ID */ @@ -685,7 +685,7 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) { ID *newid = NULL; PointerRNA idptr; - + if (id) { /* if property isn't editable, we're going to have an extra block hanging around until we save */ if (RNA_property_editable(ptr, prop)) { @@ -701,12 +701,12 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) RNA_id_pointer_create(newid, &idptr); RNA_property_pointer_set(ptr, prop, idptr); RNA_property_update(C, ptr, prop); - + return true; } } } - + return false; } @@ -992,9 +992,9 @@ int set_listbasepointers(Main *main, ListBase **lb) lb[INDEX_ID_TE] = &(main->tex); lb[INDEX_ID_MA] = &(main->mat); lb[INDEX_ID_VF] = &(main->vfont); - + /* Important!: When adding a new object type, - * the specific data should be inserted here + * the specific data should be inserted here */ lb[INDEX_ID_AR] = &(main->armature); @@ -1025,7 +1025,7 @@ int set_listbasepointers(Main *main, ListBase **lb) lb[INDEX_ID_SCE] = &(main->scene); lb[INDEX_ID_WM] = &(main->wm); lb[INDEX_ID_MSK] = &(main->mask); - + lb[INDEX_ID_NULL] = NULL; return (MAX_LIBARRAY - 1); @@ -1280,7 +1280,7 @@ void BKE_libblock_init_empty(ID *id) static void id_copy_animdata(Main *bmain, ID *id, const bool do_action) { AnimData *adt = BKE_animdata_from_id(id); - + if (adt) { IdAdtTemplate *iat = (IdAdtTemplate *)id; iat->adt = BKE_animdata_copy(bmain, iat->adt, do_action); /* could be set to false, need to investigate */ @@ -1383,7 +1383,7 @@ void BKE_main_free(Main *mainvar) while (a--) { ListBase *lb = lbarray[a]; ID *id; - + while ( (id = lb->first) ) { #if 1 BKE_libblock_free_ex(mainvar, id, false, false); @@ -1623,11 +1623,11 @@ ID *BKE_libblock_find_name(struct Main *bmain, const short type, const char *nam void id_sort_by_name(ListBase *lb, ID *id) { ID *idtest; - + /* insert alphabetically */ if (lb->first != lb->last) { BLI_remlink(lb, id); - + idtest = lb->first; while (idtest) { if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) { @@ -1641,7 +1641,7 @@ void id_sort_by_name(ListBase *lb, ID *id) BLI_addtail(lb, id); } } - + } /** @@ -1651,9 +1651,9 @@ void id_sort_by_name(ListBase *lb, ID *id) static ID *is_dupid(ListBase *lb, ID *id, const char *name) { ID *idtest = NULL; - + for (idtest = lb->first; idtest; idtest = idtest->next) { - /* if idtest is not a lib */ + /* if idtest is not a lib */ if (id != idtest && !ID_IS_LINKED(idtest)) { /* do not test alphabetic! */ /* optimized */ @@ -1662,7 +1662,7 @@ static ID *is_dupid(ListBase *lb, ID *id, const char *name) } } } - + return idtest; } @@ -1751,8 +1751,8 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) * or 1 greater than the largest used number if all those low ones are taken. * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */ - /* If the original name has no numeric suffix, - * rather than just chopping and adding numbers, + /* If the original name has no numeric suffix, + * rather than just chopping and adding numbers, * shave off the end chars until we have a unique name. * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */ if (nr == 0 && name[left_len] == '\0') { @@ -1763,7 +1763,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) len = left_len - 1; idtest = is_dupid(lb, id, name); - + while (idtest && len > 1) { name[len--] = '\0'; idtest = is_dupid(lb, id, name); @@ -1771,7 +1771,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) if (idtest == NULL) return true; /* otherwise just continue and use a number suffix */ } - + if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* this would overflow name buffer */ left[MAX_ID_NAME - 8] = 0; @@ -1834,7 +1834,7 @@ bool new_id(ListBase *lb, ID *id, const char *tname) #endif id_sort_by_name(lb, id); - + return result; } @@ -2349,7 +2349,7 @@ void BLI_libblock_ensure_unique_name(Main *bmain, const char *name) lb = which_libbase(bmain, GS(name)); if (lb == NULL) return; - + /* search for id */ idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2); @@ -2414,3 +2414,11 @@ void BKE_id_tag_clear_atomic(ID *id, int tag) { atomic_fetch_and_and_int32(&id->tag, ~tag); } + +/** Check that given ID pointer actually is in G_MAIN. + * Main intended use is for debug asserts in places we cannot easily get rid of G_Main... */ +bool BKE_id_is_in_gobal_main(ID *id) +{ + /* We do not want to fail when id is NULL here, even though this is a bit strange behavior... */ + return (id == NULL || BLI_findindex(which_libbase(G_MAIN, GS(id->name)), id) != -1); +} diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index 2a70e53be92f..2819b0312aa8 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -1004,7 +1004,7 @@ void BKE_libblock_free(Main *bmain, void *idv) void BKE_libblock_free_us(Main *bmain, void *idv) /* test users */ { ID *id = idv; - + id_us_min(id); /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object. @@ -1020,7 +1020,7 @@ void BKE_libblock_free_us(Main *bmain, void *idv) /* test users */ if (id->us == 0) { BKE_libblock_unlink(bmain, id, false, false); - + BKE_libblock_free(bmain, id); } } diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index b64cfd43bdf6..6aa370b8d1e8 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -49,8 +49,8 @@ #include "DNA_object_types.h" #include "DNA_scene_types.h" -#include "BLI_math.h" -#include "BLI_listbase.h" +#include "BLI_math.h" +#include "BLI_listbase.h" #include "BLI_utildefines.h" #include "BLI_string.h" #include "BLI_array_utils.h" @@ -90,14 +90,14 @@ void BKE_material_free(Material *ma) int a; BKE_animdata_free((ID *)ma, false); - + for (a = 0; a < MAX_MTEX; a++) { MEM_SAFE_FREE(ma->mtex[a]); } - + MEM_SAFE_FREE(ma->ramp_col); MEM_SAFE_FREE(ma->ramp_spec); - + /* is no lib link block, but material extension */ if (ma->nodetree) { ntreeFreeTree(ma->nodetree); @@ -154,13 +154,13 @@ void BKE_material_init(Material *ma) 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; ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005; ma->dist_mir = 0.0; ma->fadeto_mir = MA_RAYMIR_FADETOSKY; - + ma->rampfac_col = 1.0; ma->rampfac_spec = 1.0; ma->pr_lamp = 3; /* two lamps, is bits */ @@ -197,7 +197,7 @@ void BKE_material_init(Material *ma) ma->vol.ms_spread = 0.2f; ma->vol.ms_diff = 1.f; ma->vol.ms_intensity = 1.f; - + ma->game.flag = GEMAT_BACKCULL; ma->game.alpha_blend = 0; ma->game.face_orientation = 0; @@ -217,9 +217,9 @@ Material *BKE_material_add(Main *bmain, const char *name) Material *ma; ma = BKE_libblock_alloc(bmain, ID_MA, name, 0); - + BKE_material_init(ma); - + return ma; } @@ -287,7 +287,7 @@ Material *BKE_material_localize(Material *ma) Material *man; int a; - + man = BKE_libblock_copy_nolib(&ma->id, false); /* no increment for texture ID users, in previewrender.c it prevents decrement */ @@ -297,16 +297,16 @@ Material *BKE_material_localize(Material *ma) memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex)); } } - + if (ma->ramp_col) man->ramp_col = MEM_dupallocN(ma->ramp_col); if (ma->ramp_spec) man->ramp_spec = MEM_dupallocN(ma->ramp_spec); man->texpaintslot = NULL; man->preview = NULL; - + if (ma->nodetree) man->nodetree = ntreeLocalize(ma->nodetree); - + BLI_listbase_clear(&man->gpumaterial); BLI_listbase_clear(&man->gpumaterialinstancing); @@ -323,7 +323,7 @@ Material ***give_matarar(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->mat); @@ -344,7 +344,7 @@ short *give_totcolp(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->totcol); @@ -518,7 +518,7 @@ Material *BKE_material_pop_id(Main *bmain, ID *id, int index_i, bool update_data DAG_relations_tag_update(bmain); } } - + return ret; } @@ -552,7 +552,7 @@ Material *give_current_material(Object *ob, short act) const short *totcolp; if (ob == NULL) return NULL; - + /* if object cannot have material, (totcolp == NULL) */ totcolp = give_totcolp(ob); if (totcolp == NULL || ob->totcol == 0) return NULL; @@ -578,12 +578,12 @@ Material *give_current_material(Object *ob, short act) if (act > ob->totcol) act = ob->totcol; matarar = give_matarar(ob); - + if (matarar && *matarar) ma = (*matarar)[act - 1]; else ma = NULL; - + } - + return ma; } @@ -726,18 +726,18 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig if (act > MAXMAT) return; if (act < 1) act = 1; - + /* prevent crashing when using accidentally */ BLI_assert(!ID_IS_LINKED(ob)); if (ID_IS_LINKED(ob)) return; - + /* test arraylens */ - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); - + if (totcolp == NULL || matarar == NULL) return; - + if (act > *totcolp) { matar = MEM_callocN(sizeof(void *) * act, "matarray1"); @@ -781,7 +781,7 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig break; } } - + /* do it */ ob->matbits[act - 1] = bit; @@ -916,14 +916,14 @@ short BKE_object_material_slot_find_index(Object *ob, Material *ma) { Material ***matarar; short a, *totcolp; - + if (ma == NULL) return 0; - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); - + if (totcolp == NULL || matarar == NULL) return 0; - + for (a = 0; a < *totcolp; a++) if ((*matarar)[a] == ma) break; @@ -936,7 +936,7 @@ bool BKE_object_material_slot_add(Main *bmain, Object *ob) { if (ob == NULL) return false; if (ob->totcol >= MAXMAT) return false; - + assign_material(bmain, ob, NULL, ob->totcol + 1, BKE_MAT_ASSIGN_USERPREF); ob->actcol = ob->totcol; return true; @@ -946,25 +946,25 @@ static void do_init_render_material(Main *bmain, Material *ma, int r_mode, float { MTex *mtex; int a, needuv = 0, needtang = 0; - + if (ma->flarec == 0) ma->flarec = 1; /* add all texcoflags from mtex, texco and mapto were cleared in advance */ for (a = 0; a < MAX_MTEX; a++) { - + /* separate tex switching */ if (ma->septex & (1 << a)) continue; mtex = ma->mtex[a]; if (mtex && mtex->tex && (mtex->tex->type | (mtex->tex->use_nodes && mtex->tex->nodetree) )) { - + ma->texco |= mtex->texco; ma->mapto |= mtex->mapto; /* always get derivatives for these textures */ if (ELEM(mtex->tex->type, TEX_IMAGE, TEX_ENVMAP)) ma->texco |= TEXCO_OSA; else if (mtex->texflag & (MTEX_COMPAT_BUMP | MTEX_3TAP_BUMP | MTEX_5TAP_BUMP | MTEX_BICUBIC_BUMP)) ma->texco |= TEXCO_OSA; - + if (ma->texco & (TEXCO_ORCO | TEXCO_REFL | TEXCO_NORM | TEXCO_STRAND | TEXCO_STRESS)) needuv = 1; else if (ma->texco & (TEXCO_GLOB | TEXCO_UV | TEXCO_OBJECT | TEXCO_SPEED)) needuv = 1; else if (ma->texco & (TEXCO_LAVECTOR | TEXCO_VIEW)) needuv = 1; @@ -976,13 +976,13 @@ static void do_init_render_material(Main *bmain, Material *ma, int r_mode, float if (needtang) ma->mode |= MA_NORMAP_TANG; else ma->mode &= ~MA_NORMAP_TANG; - + if (ma->mode & (MA_VERTEXCOL | MA_VERTEXCOLP | MA_FACETEXTURE)) { needuv = 1; if (r_mode & R_OSA) ma->texco |= TEXCO_OSA; /* for texfaces */ } if (needuv) ma->texco |= NEED_UV; - + /* since the raytracer doesnt recalc O structs for each ray, we have to preset them all */ if (r_mode & R_RAYTRACE) { if ((ma->mode & (MA_RAYMIRROR | MA_SHADOW_TRA)) || ((ma->mode & MA_TRANSP) && (ma->mode & MA_RAYTRANSP))) { @@ -990,7 +990,7 @@ static void do_init_render_material(Main *bmain, Material *ma, int r_mode, float if (r_mode & R_OSA) ma->texco |= TEXCO_OSA; } } - + if (amb) { ma->ambr = ma->amb * amb[0]; ma->ambg = ma->amb * amb[1]; @@ -1056,9 +1056,9 @@ static void init_render_nodetree(Main *bmain, bNodeTree *ntree, Material *basema void init_render_material(Main *bmain, Material *mat, int r_mode, float *amb) { - + do_init_render_material(bmain, mat, r_mode, amb); - + if (mat->nodetree && mat->use_nodes) { /* mode_l will take the pipeline options from the main material, and the or-ed * result of non-pipeline options from the nodes. shadeless is an exception, @@ -1067,7 +1067,7 @@ void init_render_material(Main *bmain, Material *mat, int r_mode, float *amb) mat->mode2_l = mat->mode2 & MA_MODE2_PIPELINE; mat->nmap_tangent_names_count = 0; init_render_nodetree(bmain, mat->nodetree, mat, r_mode, amb); - + if (!mat->nodetree->execdata) mat->nodetree->execdata = ntreeShaderBeginExecTree(mat->nodetree); } @@ -1083,7 +1083,7 @@ void init_render_material(Main *bmain, Material *mat, int r_mode, float *amb) void init_render_materials(Main *bmain, int r_mode, float *amb, bool do_default_material) { Material *ma; - + /* clear these flags before going over materials, to make sure they * are cleared only once, otherwise node materials contained in other * node materials can go wrong */ @@ -1098,7 +1098,7 @@ void init_render_materials(Main *bmain, int r_mode, float *amb, bool do_default_ for (ma = bmain->mat.first; ma; ma = ma->id.next) { /* is_used flag comes back in convertblender.c */ ma->flag &= ~MA_IS_USED; - if (ma->id.us) + if (ma->id.us) init_render_material(bmain, ma, r_mode, amb); } @@ -1120,7 +1120,7 @@ void end_render_materials(Main *bmain) { Material *ma; for (ma = bmain->mat.first; ma; ma = ma->id.next) - if (ma->id.us) + if (ma->id.us) end_render_material(ma); } @@ -1168,7 +1168,7 @@ static void material_node_drivers_update(Scene *scene, bNodeTree *ntree, float c if (ntree->adt && ntree->adt->drivers.first) { BKE_animsys_evaluate_animdata(scene, &ntree->id, ntree->adt, ctime, ADT_RECALC_DRIVERS); } - + /* nodes */ for (node = ntree->nodes.first; node; node = node->next) { if (node->id) { @@ -1182,7 +1182,7 @@ static void material_node_drivers_update(Scene *scene, bNodeTree *ntree, float c } } -/* Calculate all drivers for materials +/* Calculate all drivers for materials * FIXME: this is really a terrible method which may result in some things being calculated * multiple times. However, without proper despgraph support for these things, we are forced * into this sort of thing... @@ -1191,7 +1191,7 @@ void material_drivers_update(Scene *scene, Material *ma, float ctime) { //if (G.f & G_DEBUG) // printf("material_drivers_update(%s, %s)\n", scene->id.name, ma->id.name); - + /* Prevent infinite recursion by checking (and tagging the material) as having been visited already * (see BKE_scene_update_tagged()). This assumes ma->id.tag & LIB_TAG_DOIT isn't set by anything else * in the meantime... [#32017] @@ -1200,12 +1200,12 @@ void material_drivers_update(Scene *scene, Material *ma, float ctime) return; ma->id.tag |= LIB_TAG_DOIT; - + /* material itself */ if (ma->adt && ma->adt->drivers.first) { BKE_animsys_evaluate_animdata(scene, &ma->id, ma->adt, ctime, ADT_RECALC_DRIVERS); } - + /* nodes */ if (ma->nodetree) { material_node_drivers_update(scene, ma->nodetree, ctime); @@ -1219,7 +1219,7 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) Material *mao, ***matarar; short *totcolp; short a, actcol; - + if (ob == NULL || ob->totcol == 0) { return false; } @@ -1233,10 +1233,10 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) /* take a mesh/curve/mball as starting point, remove 1 index, * AND with all objects that share the ob->data - * + * * after that check indices in mesh/curve/mball!!! */ - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); @@ -1248,21 +1248,21 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) if (ob->actcol > ob->totcol) { ob->actcol = ob->totcol; } - + /* we delete the actcol */ mao = (*matarar)[ob->actcol - 1]; if (mao) id_us_min(&mao->id); - + for (a = ob->actcol; a < ob->totcol; a++) (*matarar)[a - 1] = (*matarar)[a]; (*totcolp)--; - + if (*totcolp == 0) { MEM_freeN(*matarar); *matarar = NULL; } - + actcol = ob->actcol; for (Object *obt = bmain->object.first; obt; obt = obt->id.next) { @@ -1275,14 +1275,14 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) mao = obt->mat[actcol - 1]; if (mao) id_us_min(&mao->id); - + for (a = actcol; a < obt->totcol; a++) { obt->mat[a - 1] = obt->mat[a]; obt->matbits[a - 1] = obt->matbits[a]; } obt->totcol--; if (obt->actcol > obt->totcol) obt->actcol = obt->totcol; - + if (obt->totcol == 0) { MEM_freeN(obt->mat); MEM_freeN(obt->matbits); @@ -1314,7 +1314,7 @@ static bNode *nodetree_uv_node_recursive(bNode *node) { bNode *inode; bNodeSocket *sock; - + for (sock = node->inputs.first; sock; sock = sock->next) { if (sock->link) { inode = sock->link->fromnode; @@ -1326,7 +1326,7 @@ static bNode *nodetree_uv_node_recursive(bNode *node) } } } - + return NULL; } @@ -1338,7 +1338,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) bool use_nodes = BKE_scene_use_new_shading_nodes(scene); bool is_bi = BKE_scene_uses_blender_internal(scene) || BKE_scene_uses_blender_game(scene); - + if (!ma) return; @@ -1353,7 +1353,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) ma->paint_clone_slot = 0; return; } - + if (use_nodes || ma->use_nodes) { bNode *node, *active_node; @@ -1382,11 +1382,11 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) if (active_node == node) ma->paint_active_slot = index; ma->texpaintslot[index].ima = (Image *)node->id; - + /* for new renderer, we need to traverse the treeback in search of a UV node */ if (use_nodes) { bNode *uvnode = nodetree_uv_node_recursive(node); - + if (uvnode) { NodeShaderUVMap *storage = (NodeShaderUVMap *)uvnode->storage; ma->texpaintslot[index].uvname = storage->uv_map; @@ -1425,7 +1425,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) ma->texpaintslot[index].ima = (*mtex)->tex->ima; ma->texpaintslot[index].uvname = (*mtex)->uvname; ma->texpaintslot[index].index = i; - + index++; } } @@ -1434,12 +1434,12 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) ma->paint_active_slot = 0; ma->paint_clone_slot = 0; return; - } + } ma->tot_slots = count; - - + + if (ma->paint_active_slot >= count) { ma->paint_active_slot = count - 1; } @@ -1466,7 +1466,7 @@ void BKE_texpaint_slots_refresh_object(Scene *scene, struct Object *ob) 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_col[0] = facm * (r_col[0]) + fac * col[0]; @@ -1812,10 +1812,10 @@ static int encode_tfaceflag(MTFace *tf, int convertall) /* light tface flag is ignored in GLSL mode */ flag &= ~TF_LIGHT; - + /* 15 is how big the flag can be - hardcoded here and in decode_tfaceflag() */ flag |= tf->transp << 15; - + /* increase 1 so flag 0 is different than no flag yet */ return flag + 1; } @@ -1831,15 +1831,15 @@ static void decode_tfaceflag(Material *ma, int flag, int convertall) alphablend = flag >> 15; /* encoded in the encode_tfaceflag function */ (*game).flag = 0; - + /* General Material Options */ if ((flag & TF_DYNAMIC) == 0) (*game).flag |= GEMAT_NOPHYSICS; - + /* Material Offline Rendering Properties */ if (convertall) { if (flag & TF_OBCOL) ma->shade_flag |= MA_OBCOLOR; } - + /* Special Face Properties */ if ((flag & TF_TWOSIDE) == 0) (*game).flag |= GEMAT_BACKCULL; if (flag & TF_INVISIBLE) (*game).flag |= GEMAT_INVISIBLE; @@ -1848,7 +1848,7 @@ static void decode_tfaceflag(Material *ma, int flag, int convertall) if (flag & TF_BILLBOARD) (*game).face_orientation |= GEMAT_HALO; else if (flag & TF_BILLBOARD2) (*game).face_orientation |= GEMAT_BILLBOARD; else if (flag & TF_SHADOW) (*game).face_orientation |= GEMAT_SHADOW; - + /* Alpha Blend */ if (flag & TF_ALPHASORT && ELEM(alphablend, TF_ALPHA, TF_ADD)) (*game).alpha_blend = GEMAT_ALPHA_SORT; else if (alphablend & TF_ALPHA) (*game).alpha_blend = GEMAT_ALPHA; @@ -1872,7 +1872,7 @@ static int check_tfaceneedmaterial(int flag) /* light tface flag is ignored in GLSL mode */ flag &= ~TF_LIGHT; - + /* automatic detected if tex image has alpha */ flag &= ~(TF_ALPHA << 15); /* automatic detected if using texture */ @@ -1953,7 +1953,7 @@ static short convert_tfacenomaterial(Main *bmain, Mesh *me, MTFace *tf, int flag Material *ma; char idname[MAX_ID_NAME]; short mat_nr = -1; - + /* new material, the name uses the flag*/ BLI_snprintf(idname, sizeof(idname), "MAMaterial.TF.%0*d", integer_getdigits(flag), flag); @@ -1972,7 +1972,7 @@ static short convert_tfacenomaterial(Main *bmain, Mesh *me, MTFace *tf, int flag if (ma) { printf("TexFace Convert: Material \"%s\" created.\n", idname + 2); mat_nr = mesh_addmaterial(bmain, me, ma); - + /* if needed set "Face Textures [Alpha]" Material options */ set_facetexture_flags(ma, tf->tpage); @@ -2010,7 +2010,7 @@ static void convert_tfacematerial(Main *bmain, Material *ma) /* check if this mesh uses this material */ for (a = 0; a < me->totcol; a++) if (me->mat[a] == ma) break; - + /* no material found */ if (a == me->totcol) continue; @@ -2053,9 +2053,9 @@ static void convert_tfacematerial(Main *bmain, Material *ma) continue; } } - + /* if the material has a texture but no texture channel - * set "Face Textures [Alpha]" Material options + * set "Face Textures [Alpha]" Material options * actually we need to run it always, because of old behavior * of using face texture if any texture channel was present (multitex) */ //if ((!mat_new->mtex[0]) && (!mat_new->mtex[0]->tex)) @@ -2089,7 +2089,7 @@ int do_version_tface(Main *main) int a; int flag; int index; - + /* Operator in help menu has been removed for 2.7x */ int fileload = 1; @@ -2105,9 +2105,9 @@ int do_version_tface(Main *main) /* mark all the materials to conversion with a flag * if there is tface create a complete flag for that storing in flag * if there is tface and flag > 0: creates a new flag based on this face - * if flags are different set flag to -1 + * if flags are different set flag to -1 */ - + /* 1st part: marking mesh materials to update */ for (me = main->mesh.first; me; me = me->id.next) { if (ID_IS_LINKED(me)) continue; @@ -2118,7 +2118,7 @@ int do_version_tface(Main *main) if (!cdl) continue; nomaterialslots = (me->totcol == 0 ? 1 : 0); - + /* loop over all the faces*/ for (a = 0, mf = me->mface; a < me->totface; a++, mf++) { /* texface data for this face */ @@ -2131,11 +2131,11 @@ int do_version_tface(Main *main) if ((tf->mode & TF_CONVERTED)) continue; else tf->mode |= TF_CONVERTED; } - + /* no material slots */ if (nomaterialslots) { flag = encode_tfaceflag(tf, 1); - + /* create/find a new material and assign to the face */ if (check_tfaceneedmaterial(flag)) { mf->mat_nr = convert_tfacenomaterial(main, me, tf, flag); @@ -2147,7 +2147,7 @@ int do_version_tface(Main *main) } else if (mf->mat_nr < me->totcol) { ma = me->mat[mf->mat_nr]; - + /* no material create one if necessary */ if (!ma) { /* find a new material and assign to the face */ @@ -2166,7 +2166,7 @@ int do_version_tface(Main *main) * later we could, but it's better not */ else if (ID_IS_LINKED(ma)) continue; - + /* material already marked as disputed */ else if (ma->game.flag == MAT_BGE_DISPUTED) continue; @@ -2178,17 +2178,17 @@ int do_version_tface(Main *main) /* first time changing this material */ if (ma->game.flag == 0) ma->game.flag = -flag; - + /* mark material as disputed */ else if (ma->game.flag != -flag) { ma->game.flag = MAT_BGE_DISPUTED; continue; } - + /* material ok so far */ else { ma->game.flag = -flag; - + /* some people uses multitexture with TexFace by creating a texture * channel which not necessarily the tf->tpage image. But the game engine * was enabling it. Now it's required to set "Face Texture [Alpha] in the @@ -2223,7 +2223,7 @@ int do_version_tface(Main *main) } } - + /* 2nd part - conversion */ /* skip library files */ @@ -2243,7 +2243,7 @@ int do_version_tface(Main *main) } continue; } - + /* no conflicts in this material - 90% of cases * convert from tface system to material */ else if (ma->game.flag < 0) { @@ -2256,15 +2256,15 @@ int do_version_tface(Main *main) /* check if this mesh uses this material */ for (a = 0; a < me->totcol; a++) if (me->mat[a] == ma) break; - + /* no material found */ if (a == me->totcol) continue; - + /* get the active tface layer */ index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE); cdl = (index == -1) ? NULL : &me->fdata.layers[index]; if (!cdl) continue; - + /* loop over all the faces and stop at the ones that use the material*/ for (a = 0, mf = me->mface; a < me->totface; a++, mf++) { if (me->mat[mf->mat_nr] == ma) { @@ -2287,4 +2287,3 @@ int do_version_tface(Main *main) return nowarning; } - diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 8438957b0efd..9e926e5ef538 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -86,7 +86,7 @@ void BKE_mball_init(MetaBall *mb) mb->size[0] = mb->size[1] = mb->size[2] = 1.0; mb->texflag = MB_AUTOSPACE; - + mb->wiresize = 0.4f; mb->rendersize = 0.2f; mb->thresh = 0.6f; @@ -197,7 +197,7 @@ void BKE_mball_texspace_calc(Object *ob) if (ob->bb == NULL) ob->bb = MEM_callocN(sizeof(BoundBox), "mb boundbox"); bb = ob->bb; - + /* Weird one, this. */ /* INIT_MINMAX(min, max); */ (min)[0] = (min)[1] = (min)[2] = 1.0e30f; diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index 770d482b33b2..6d4814720741 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -106,7 +106,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 const float thresh_sq = thresh * thresh; CustomDataLayer *l1, *l2; int i, i1 = 0, i2 = 0, tot, j; - + for (i = 0; i < c1->totlayer; i++) { if (ELEM(c1->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY, CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT)) @@ -125,7 +125,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 if (i1 != i2) return MESHCMP_CDLAYERS_MISMATCH; - + l1 = c1->layers; l2 = c2->layers; tot = i1; i1 = 0; i2 = 0; @@ -143,52 +143,52 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 i2++; l2++; } - + if (l1->type == CD_MVERT) { MVert *v1 = l1->data; MVert *v2 = l2->data; int vtot = m1->totvert; - + for (j = 0; j < vtot; j++, v1++, v2++) { if (len_squared_v3v3(v1->co, v2->co) > thresh_sq) return MESHCMP_VERTCOMISMATCH; /* I don't care about normals, let's just do coodinates */ } } - + /*we're order-agnostic for edges here*/ if (l1->type == CD_MEDGE) { MEdge *e1 = l1->data; MEdge *e2 = l2->data; int etot = m1->totedge; EdgeHash *eh = BLI_edgehash_new_ex(__func__, etot); - + for (j = 0; j < etot; j++, e1++) { BLI_edgehash_insert(eh, e1->v1, e1->v2, e1); } - + for (j = 0; j < etot; j++, e2++) { if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2)) return MESHCMP_EDGEUNKNOWN; } BLI_edgehash_free(eh, NULL); } - + if (l1->type == CD_MPOLY) { MPoly *p1 = l1->data; MPoly *p2 = l2->data; int ptot = m1->totpoly; - + for (j = 0; j < ptot; j++, p1++, p2++) { MLoop *lp1, *lp2; int k; - + if (p1->totloop != p2->totloop) return MESHCMP_POLYMISMATCH; - + lp1 = m1->mloop + p1->loopstart; lp2 = m2->mloop + p2->loopstart; - + for (k = 0; k < p1->totloop; k++, lp1++, lp2++) { if (lp1->v != lp2->v) return MESHCMP_POLYVERTMISMATCH; @@ -199,7 +199,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MLoop *lp1 = l1->data; MLoop *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { if (lp1->v != lp2->v) return MESHCMP_LOOPMISMATCH; @@ -209,22 +209,22 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MLoopUV *lp1 = l1->data; MLoopUV *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq) return MESHCMP_LOOPUVMISMATCH; } } - + if (l1->type == CD_MLOOPCOL) { MLoopCol *lp1 = l1->data; MLoopCol *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { - if (ABS(lp1->r - lp2->r) > thresh || - ABS(lp1->g - lp2->g) > thresh || - ABS(lp1->b - lp2->b) > thresh || + if (ABS(lp1->r - lp2->r) > thresh || + ABS(lp1->g - lp2->g) > thresh || + ABS(lp1->b - lp2->b) > thresh || ABS(lp1->a - lp2->a) > thresh) { return MESHCMP_LOOPCOLMISMATCH; @@ -236,14 +236,14 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MDeformVert *dv1 = l1->data; MDeformVert *dv2 = l2->data; int dvtot = m1->totvert; - + for (j = 0; j < dvtot; j++, dv1++, dv2++) { int k; MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw; - + if (dv1->totweight != dv2->totweight) return MESHCMP_DVERT_TOTGROUPMISMATCH; - + for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) { if (dw1->def_nr != dw2->def_nr) return MESHCMP_DVERT_GROUPMISMATCH; @@ -253,7 +253,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 } } } - + return 0; } @@ -266,22 +266,22 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh) { int c; - + if (!me1 || !me2) return "Requires two input meshes"; - - if (me1->totvert != me2->totvert) + + if (me1->totvert != me2->totvert) return "Number of verts don't match"; - + if (me1->totedge != me2->totedge) return "Number of edges don't match"; - + if (me1->totpoly != me2->totpoly) return "Number of faces don't match"; - + if (me1->totloop != me2->totloop) return "Number of loops don't match"; - + if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh))) return cmpcode_to_str(c); @@ -293,7 +293,7 @@ const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh) if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh))) return cmpcode_to_str(c); - + return NULL; } @@ -347,8 +347,9 @@ void BKE_mesh_ensure_skin_customdata(Mesh *me) /* Mark an arbitrary vertex as root */ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) { - vs = CustomData_bmesh_get(&bm->vdata, v->head.data, - CD_MVERT_SKIN); + vs = CustomData_bmesh_get( + &bm->vdata, v->head.data, + CD_MVERT_SKIN); vs->flag |= MVERT_SKIN_ROOT; break; } @@ -356,11 +357,12 @@ void BKE_mesh_ensure_skin_customdata(Mesh *me) } else { if (!CustomData_has_layer(&me->vdata, CD_MVERT_SKIN)) { - vs = CustomData_add_layer(&me->vdata, - CD_MVERT_SKIN, - CD_DEFAULT, - NULL, - me->totvert); + vs = CustomData_add_layer( + &me->vdata, + CD_MVERT_SKIN, + CD_DEFAULT, + NULL, + me->totvert); /* Mark an arbitrary vertex as root */ if (vs) { @@ -400,7 +402,7 @@ void BKE_mesh_update_customdata_pointers(Mesh *me, const bool do_ensure_tess_cd) me->mface = CustomData_get_layer(&me->fdata, CD_MFACE); me->mcol = CustomData_get_layer(&me->fdata, CD_MCOL); me->mtface = CustomData_get_layer(&me->fdata, CD_MTFACE); - + me->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY); me->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP); @@ -550,8 +552,9 @@ void BKE_mesh_make_local(Main *bmain, Mesh *me, const bool lib_local) BKE_id_make_local_generic(bmain, &me->id, true, lib_local); } -bool BKE_mesh_uv_cdlayer_rename_index(Mesh *me, const int poly_index, const int loop_index, const int face_index, - const char *new_name, const bool do_tessface) +bool BKE_mesh_uv_cdlayer_rename_index( + Mesh *me, const int poly_index, const int loop_index, const int face_index, + const char *new_name, const bool do_tessface) { CustomData *pdata, *ldata, *fdata; CustomDataLayer *cdlp, *cdlu, *cdlf; @@ -673,13 +676,13 @@ void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3]) BoundBox *bb; float min[3], max[3]; float mloc[3], msize[3]; - + if (me->bb == NULL) me->bb = MEM_callocN(sizeof(BoundBox), "boundbox"); bb = me->bb; if (!r_loc) r_loc = mloc; if (!r_size) r_size = msize; - + INIT_MINMAX(min, max); if (!BKE_mesh_minmax(me, min, max)) { min[0] = min[1] = min[2] = -1.0f; @@ -687,11 +690,11 @@ void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3]) } mid_v3_v3v3(r_loc, min, max); - + r_size[0] = (max[0] - min[0]) / 2.0f; r_size[1] = (max[1] - min[1]) / 2.0f; r_size[2] = (max[2] - min[2]) / 2.0f; - + BKE_boundbox_init_from_minmax(bb, min, max); bb->flag &= ~BOUNDBOX_DIRTY; @@ -874,7 +877,7 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) Mesh *BKE_mesh_from_object(Object *ob) { - + if (ob == NULL) return NULL; if (ob->type == OB_MESH) return ob->data; else return NULL; @@ -885,9 +888,9 @@ void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) Mesh *old = NULL; multires_force_update(ob); - + if (ob == NULL) return; - + if (ob->type == OB_MESH) { old = ob->data; if (old) @@ -895,7 +898,7 @@ void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) ob->data = me; id_us_plus((ID *)me); } - + test_object_materials(bmain, ob, (ID *)me); test_object_modifiers(ob); @@ -966,7 +969,7 @@ void BKE_mesh_material_remap(Mesh *me, const unsigned int *remap, unsigned int r } -void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) +void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) { Mesh *me = meshOb->data; int i; @@ -981,7 +984,7 @@ void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) mp->flag &= ~ME_SMOOTH; } } - + for (i = 0; i < me->totface; i++) { MFace *mf = &me->mface[i]; @@ -1023,7 +1026,7 @@ int poly_find_loop_from_vert( if (loopstart->v == vert) return j; } - + return -1; } @@ -1037,10 +1040,11 @@ int poly_get_adj_loops_from_vert( const MLoop *mloop, unsigned int vert, unsigned int r_adj[2]) { - int corner = poly_find_loop_from_vert(poly, - &mloop[poly->loopstart], - vert); - + int corner = poly_find_loop_from_vert( + poly, + &mloop[poly->loopstart], + vert); + if (corner != -1) { #if 0 /* unused - this loop */ const MLoop *ml = &mloop[poly->loopstart + corner]; @@ -1076,7 +1080,7 @@ bool BKE_mesh_minmax(const Mesh *me, float r_min[3], float r_max[3]) for (mvert = me->mvert; i--; mvert++) { minmax_v3v3_v3(r_min, r_max, mvert->co); } - + return (me->totvert != 0); } @@ -1119,7 +1123,7 @@ void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys) for (mvert = me->mvert; i--; mvert++) { add_v3_v3(mvert->co, offset); } - + if (do_keys && me->key) { KeyBlock *kb; for (kb = me->key->block.first; kb; kb = kb->next) { @@ -1147,11 +1151,12 @@ void BKE_mesh_ensure_navmesh(Mesh *me) void BKE_mesh_tessface_calc(Mesh *mesh) { - mesh->totface = BKE_mesh_recalc_tessellation(&mesh->fdata, &mesh->ldata, &mesh->pdata, - mesh->mvert, - mesh->totface, mesh->totloop, mesh->totpoly, - /* calc normals right after, don't copy from polys here */ - false); + mesh->totface = BKE_mesh_recalc_tessellation( + &mesh->fdata, &mesh->ldata, &mesh->pdata, + mesh->mvert, + mesh->totface, mesh->totloop, mesh->totpoly, + /* calc normals right after, don't copy from polys here */ + false); BKE_mesh_update_customdata_pointers(mesh, true); } @@ -1370,8 +1375,8 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac else { polynors = MEM_malloc_arrayN(mesh->totpoly, sizeof(float[3]), __func__); BKE_mesh_calc_normals_poly( - mesh->mvert, NULL, mesh->totvert, - mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false); + mesh->mvert, NULL, mesh->totvert, + mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false); free_polynors = true; } @@ -1650,8 +1655,9 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) /* **** Depsgraph evaluation **** */ -void BKE_mesh_eval_geometry(EvaluationContext *UNUSED(eval_ctx), - Mesh *mesh) +void BKE_mesh_eval_geometry( + EvaluationContext *UNUSED(eval_ctx), + Mesh *mesh) { DEG_debug_print_eval(__func__, mesh->id.name, mesh); if (mesh->bb == NULL || (mesh->bb->flag & BOUNDBOX_DIRTY)) { diff --git a/source/blender/blenkernel/intern/mesh_convert.c b/source/blender/blenkernel/intern/mesh_convert.c index d376c90f1c2c..c801c5dcb016 100644 --- a/source/blender/blenkernel/intern/mesh_convert.c +++ b/source/blender/blenkernel/intern/mesh_convert.c @@ -123,9 +123,10 @@ void BKE_mesh_from_metaball(ListBase *lb, Mesh *me) /** * Specialized function to use when we _know_ existing edges don't overlap with poly edges. */ -static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge, - const MPoly *mpoly, MLoop *mloop, - const int totpoly) +static void make_edges_mdata_extend( + MEdge **r_alledge, int *r_totedge, + const MPoly *mpoly, MLoop *mloop, + const int totpoly) { int totedge = *r_totedge; int totedge_new; @@ -498,10 +499,11 @@ void BKE_mesh_from_nurbs_displist( cu = ob->data; if (dm == NULL) { - if (BKE_mesh_nurbs_displist_to_mdata(ob, dispbase, &allvert, &totvert, - &alledge, &totedge, &allloop, - &allpoly, (use_orco_uv) ? &alluv : NULL, - &totloop, &totpoly) != 0) + if (BKE_mesh_nurbs_displist_to_mdata( + ob, dispbase, &allvert, &totvert, + &alledge, &totedge, &allloop, + &allpoly, (use_orco_uv) ? &alluv : NULL, + &totloop, &totpoly) != 0) { /* Error initializing */ return; diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index a67c9de6deba..279ab7775292 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -165,7 +165,7 @@ void BKE_mesh_calc_normals_mapping_ex( /* if (fnors != r_faceNors) MEM_freeN(fnors); */ /* NO NEED TO ALLOC YET */ fnors = pnors = NULL; - + } typedef struct MeshCalcNormalsData { @@ -178,7 +178,7 @@ typedef struct MeshCalcNormalsData { } MeshCalcNormalsData; static void mesh_calc_normals_poly_cb( - void *__restrict userdata, + void *__restrict userdata, const int pidx, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -189,7 +189,7 @@ static void mesh_calc_normals_poly_cb( } static void mesh_calc_normals_poly_prepare_cb( - void *__restrict userdata, + void *__restrict userdata, const int pidx, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -337,9 +337,10 @@ void BKE_mesh_calc_normals(Mesh *mesh) #ifdef DEBUG_TIME TIMEIT_START_AVERAGED(BKE_mesh_calc_normals); #endif - BKE_mesh_calc_normals_poly(mesh->mvert, NULL, mesh->totvert, - mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, - NULL, false); + BKE_mesh_calc_normals_poly( + mesh->mvert, NULL, mesh->totvert, + mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, + NULL, false); #ifdef DEBUG_TIME TIMEIT_END_AVERAGED(BKE_mesh_calc_normals); #endif @@ -378,14 +379,14 @@ void BKE_mesh_calc_normals_tessface( for (i = 0; i < numVerts; i++) { MVert *mv = &mverts[i]; float *no = tnorms[i]; - + if (UNLIKELY(normalize_v3(no) == 0.0f)) { normalize_v3_v3(no, mv->co); } normal_float_to_short_v3(mv->no, no); } - + cleanup: MEM_freeN(tnorms); @@ -487,8 +488,9 @@ MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr) * Beware, this modifies ref_vec and other_vec in place! * In case no valid space can be generated, ref_alpha and ref_beta are set to zero (which means 'use auto lnors'). */ -void BKE_lnor_space_define(MLoopNorSpace *lnor_space, const float lnor[3], - float vec_ref[3], float vec_other[3], BLI_Stack *edge_vectors) +void BKE_lnor_space_define( + MLoopNorSpace *lnor_space, const float lnor[3], + float vec_ref[3], float vec_other[3], BLI_Stack *edge_vectors) { const float pi2 = (float)M_PI * 2.0f; float tvec[3], dtp; @@ -770,8 +772,9 @@ static void mesh_edges_sharp_tag( e2l[1] = (mp->flag & ME_SMOOTH) ? INDEX_UNSET : INDEX_INVALID; } else if (e2l[1] == INDEX_UNSET) { - const bool is_angle_sharp = (check_angle && - dot_v3v3(polynors[loop_to_poly[e2l[0]]], polynors[mp_index]) < split_angle_cos); + const bool is_angle_sharp = ( + check_angle && + dot_v3v3(polynors[loop_to_poly[e2l[0]]], polynors[mp_index]) < split_angle_cos); /* Second loop using this edge, time to test its sharpness. * An edge is sharp if it is tagged as such, or its face is not smooth, @@ -1104,8 +1107,8 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli /* Find next loop of the smooth fan. */ BKE_mesh_loop_manifold_fan_around_vert_next( - mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index, - &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index); + mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index, + &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index); e2lfan_curr = edge_to_loops[mlfan_curr->e]; } @@ -1241,8 +1244,8 @@ static bool loop_split_generator_check_cyclic_smooth_fan( while (true) { /* Find next loop of the smooth fan. */ BKE_mesh_loop_manifold_fan_around_vert_next( - mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index, - &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index); + mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index, + &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index); e2lfan_curr = edge_to_loops[mlfan_curr->e]; @@ -1591,9 +1594,10 @@ static void mesh_normals_loop_custom_set( BLI_SMALLSTACK_DECLARE(clnors_data, short *); /* Compute current lnor spacearr. */ - BKE_mesh_normals_loop_split(mverts, numVerts, medges, numEdges, mloops, lnors, numLoops, - mpolys, polynors, numPolys, use_split_normals, split_angle, - &lnors_spacearr, NULL, loop_to_poly); + BKE_mesh_normals_loop_split( + mverts, numVerts, medges, numEdges, mloops, lnors, numLoops, + mpolys, polynors, numPolys, use_split_normals, split_angle, + &lnors_spacearr, NULL, loop_to_poly); /* Set all given zero vectors to their default value. */ if (use_vertices) { @@ -1701,9 +1705,10 @@ static void mesh_normals_loop_custom_set( /* And now, recompute our new auto lnors and lnor spacearr! */ BKE_lnor_spacearr_clear(&lnors_spacearr); - BKE_mesh_normals_loop_split(mverts, numVerts, medges, numEdges, mloops, lnors, numLoops, - mpolys, polynors, numPolys, use_split_normals, split_angle, - &lnors_spacearr, NULL, loop_to_poly); + BKE_mesh_normals_loop_split( + mverts, numVerts, medges, numEdges, mloops, lnors, numLoops, + mpolys, polynors, numPolys, use_split_normals, split_angle, + &lnors_spacearr, NULL, loop_to_poly); } else { BLI_BITMAP_SET_ALL(done_loops, true, (size_t)numLoops); @@ -1775,8 +1780,9 @@ void BKE_mesh_normals_loop_custom_set( MPoly *mpolys, const float (*polynors)[3], const int numPolys, short (*r_clnors_data)[2]) { - mesh_normals_loop_custom_set(mverts, numVerts, medges, numEdges, mloops, r_custom_loopnors, numLoops, - mpolys, polynors, numPolys, r_clnors_data, false); + mesh_normals_loop_custom_set( + mverts, numVerts, medges, numEdges, mloops, r_custom_loopnors, numLoops, + mpolys, polynors, numPolys, r_clnors_data, false); } void BKE_mesh_normals_loop_custom_from_vertices_set( @@ -1785,8 +1791,9 @@ void BKE_mesh_normals_loop_custom_from_vertices_set( MPoly *mpolys, const float (*polynors)[3], const int numPolys, short (*r_clnors_data)[2]) { - mesh_normals_loop_custom_set(mverts, numVerts, medges, numEdges, mloops, r_custom_vertnors, numLoops, - mpolys, polynors, numPolys, r_clnors_data, true); + mesh_normals_loop_custom_set( + mverts, numVerts, medges, numEdges, mloops, r_custom_vertnors, numLoops, + mpolys, polynors, numPolys, r_clnors_data, true); } /** @@ -1864,8 +1871,9 @@ static void get_position(const SMikkTSpaceContext *pContext, float r_co[3], cons copy_v3_v3(r_co, p_mesh->mverts[p_mesh->mloops[loop_idx].v].co); } -static void get_texture_coordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_idx, - const int vert_idx) +static void get_texture_coordinate( + const SMikkTSpaceContext *pContext, float r_uv[2], const int face_idx, + const int vert_idx) { BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData; copy_v2_v2(r_uv, p_mesh->luvs[p_mesh->mpolys[face_idx].loopstart + vert_idx].uv); @@ -1877,8 +1885,9 @@ static void get_normal(const SMikkTSpaceContext *pContext, float r_no[3], const copy_v3_v3(r_no, p_mesh->lnors[p_mesh->mpolys[face_idx].loopstart + vert_idx]); } -static void set_tspace(const SMikkTSpaceContext *pContext, const float fv_tangent[3], const float face_sign, - const int face_idx, const int vert_idx) +static void set_tspace( + const SMikkTSpaceContext *pContext, const float fv_tangent[3], const float face_sign, + const int face_idx, const int vert_idx) { BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData; float *p_res = p_mesh->tangents[p_mesh->mpolys[face_idx].loopstart + vert_idx]; @@ -1965,8 +1974,9 @@ void BKE_mesh_loop_tangents(Mesh *mesh, const char *uvmap, float (*r_looptangent return; } - BKE_mesh_loop_tangents_ex(mesh->mvert, mesh->totvert, mesh->mloop, r_looptangents, - loopnors, loopuvs, mesh->totloop, mesh->mpoly, mesh->totpoly, reports); + BKE_mesh_loop_tangents_ex( + mesh->mvert, mesh->totvert, mesh->mloop, r_looptangents, + loopnors, loopuvs, mesh->totloop, mesh->mpoly, mesh->totpoly, reports); } /** \} */ @@ -2016,19 +2026,19 @@ void BKE_mesh_calc_poly_normal( mesh_calc_ngon_normal(mpoly, loopstart, mvarray, r_no); } else if (mpoly->totloop == 3) { - normal_tri_v3(r_no, - mvarray[loopstart[0].v].co, - mvarray[loopstart[1].v].co, - mvarray[loopstart[2].v].co - ); + normal_tri_v3( + r_no, + mvarray[loopstart[0].v].co, + mvarray[loopstart[1].v].co, + mvarray[loopstart[2].v].co); } else if (mpoly->totloop == 4) { - normal_quad_v3(r_no, - mvarray[loopstart[0].v].co, - mvarray[loopstart[1].v].co, - mvarray[loopstart[2].v].co, - mvarray[loopstart[3].v].co - ); + normal_quad_v3( + r_no, + mvarray[loopstart[0].v].co, + mvarray[loopstart[1].v].co, + mvarray[loopstart[2].v].co, + mvarray[loopstart[3].v].co); } else { /* horrible, two sided face! */ r_no[0] = 0.0; @@ -2068,19 +2078,19 @@ void BKE_mesh_calc_poly_normal_coords( mesh_calc_ngon_normal_coords(mpoly, loopstart, vertex_coords, r_no); } else if (mpoly->totloop == 3) { - normal_tri_v3(r_no, - vertex_coords[loopstart[0].v], - vertex_coords[loopstart[1].v], - vertex_coords[loopstart[2].v] - ); + normal_tri_v3( + r_no, + vertex_coords[loopstart[0].v], + vertex_coords[loopstart[1].v], + vertex_coords[loopstart[2].v]); } else if (mpoly->totloop == 4) { - normal_quad_v3(r_no, - vertex_coords[loopstart[0].v], - vertex_coords[loopstart[1].v], - vertex_coords[loopstart[2].v], - vertex_coords[loopstart[3].v] - ); + normal_quad_v3( + r_no, + vertex_coords[loopstart[0].v], + vertex_coords[loopstart[1].v], + vertex_coords[loopstart[2].v], + vertex_coords[loopstart[3].v]); } else { /* horrible, two sided face! */ r_no[0] = 0.0; @@ -2108,19 +2118,19 @@ void BKE_mesh_calc_poly_center( const MVert *mvarray, float r_cent[3]) { if (mpoly->totloop == 3) { - mid_v3_v3v3v3(r_cent, - mvarray[loopstart[0].v].co, - mvarray[loopstart[1].v].co, - mvarray[loopstart[2].v].co - ); + mid_v3_v3v3v3( + r_cent, + mvarray[loopstart[0].v].co, + mvarray[loopstart[1].v].co, + mvarray[loopstart[2].v].co); } else if (mpoly->totloop == 4) { - mid_v3_v3v3v3v3(r_cent, - mvarray[loopstart[0].v].co, - mvarray[loopstart[1].v].co, - mvarray[loopstart[2].v].co, - mvarray[loopstart[3].v].co - ); + mid_v3_v3v3v3v3( + r_cent, + mvarray[loopstart[0].v].co, + mvarray[loopstart[1].v].co, + mvarray[loopstart[2].v].co, + mvarray[loopstart[3].v].co); } else { mesh_calc_ngon_center(mpoly, loopstart, mvarray, r_cent); @@ -2133,10 +2143,10 @@ float BKE_mesh_calc_poly_area( const MVert *mvarray) { if (mpoly->totloop == 3) { - return area_tri_v3(mvarray[loopstart[0].v].co, - mvarray[loopstart[1].v].co, - mvarray[loopstart[2].v].co - ); + return area_tri_v3( + mvarray[loopstart[0].v].co, + mvarray[loopstart[1].v].co, + mvarray[loopstart[2].v].co); } else { int i; @@ -2247,8 +2257,9 @@ static float mesh_calc_poly_area_centroid( } #if 0 /* slow version of the function below */ -void BKE_mesh_calc_poly_angles(MPoly *mpoly, MLoop *loopstart, - MVert *mvarray, float angles[]) +void BKE_mesh_calc_poly_angles( + MPoly *mpoly, MLoop *loopstart, + MVert *mvarray, float angles[]) { MLoop *ml; MLoop *mloop = &loopstart[-mpoly->loopstart]; @@ -2442,19 +2453,19 @@ static bool mesh_calc_center_centroid_ex( const MLoopTri *lt; float totweight; int i; - + zero_v3(r_center); - + if (looptri_num == 0) return false; - + totweight = 0.0f; for (i = 0, lt = looptri; i < looptri_num; i++, lt++) { const MVert *v1 = &mverts[mloop[lt->tri[0]].v]; const MVert *v2 = &mverts[mloop[lt->tri[1]].v]; const MVert *v3 = &mverts[mloop[lt->tri[2]].v]; float area; - + area = area_tri_v3(v1->co, v2->co, v3->co); madd_v3_v3fl(r_center, v1->co, area); madd_v3_v3fl(r_center, v2->co, area); @@ -2463,9 +2474,9 @@ static bool mesh_calc_center_centroid_ex( } if (totweight == 0.0f) return false; - + mul_v3_fl(r_center, 1.0f / (3.0f * totweight)); - + return true; } @@ -2485,18 +2496,18 @@ void BKE_mesh_calc_volume( float center[3]; float totvol; int i; - + if (r_volume) *r_volume = 0.0f; if (r_center) zero_v3(r_center); - + if (looptri_num == 0) return; - + if (!mesh_calc_center_centroid_ex(mverts, mverts_num, looptri, looptri_num, mloop, center)) return; - + totvol = 0.0f; for (i = 0, lt = looptri; i < looptri_num; i++, lt++) { @@ -2504,7 +2515,7 @@ void BKE_mesh_calc_volume( const MVert *v2 = &mverts[mloop[lt->tri[1]].v]; const MVert *v3 = &mverts[mloop[lt->tri[2]].v]; float vol; - + vol = volume_tetrahedron_signed_v3(center, v1->co, v2->co, v3->co); if (r_volume) { totvol += vol; @@ -2516,7 +2527,7 @@ void BKE_mesh_calc_volume( madd_v3_v3fl(r_center, v3->co, vol); } } - + /* Note: Depending on arbitrary centroid position, * totvol can become negative even for a valid mesh. * The true value is always the positive value. @@ -2620,8 +2631,9 @@ void BKE_mesh_loops_to_mface_corners( * * \note when mface is not NULL, mface[face_index].v4 is used to test quads, else, loopindices[face_index][3] is used. */ -void BKE_mesh_loops_to_tessdata(CustomData *fdata, CustomData *ldata, CustomData *pdata, MFace *mface, - int *polyindices, unsigned int (*loopindices)[4], const int num_faces) +void BKE_mesh_loops_to_tessdata( + CustomData *fdata, CustomData *ldata, CustomData *pdata, MFace *mface, + int *polyindices, unsigned int (*loopindices)[4], const int num_faces) { /* Note: performances are sub-optimal when we get a NULL mface, we could be ~25% quicker with dedicated code... * Issue is, unless having two different functions with nearly the same code, there's not much ways to solve @@ -3160,130 +3172,9 @@ void BKE_mesh_recalc_looptri( #undef ML_TO_MLT } -/* -------------------------------------------------------------------- */ - - -#ifdef USE_BMESH_SAVE_AS_COMPAT - -/** - * This function recreates a tessellation. - * returns number of tessellation faces. - * - * for forwards compat only quad->tri polys to mface, skip ngons. - */ -int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata, - struct CustomData *pdata, int totface, int UNUSED(totloop), int totpoly) -{ - MLoop *mloop; - - unsigned int lindex[4]; - int i; - int k; - - MPoly *mp, *mpoly; - MFace *mface, *mf; - - const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY); - const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL); - const bool hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL); - const bool hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP); - const bool hasLNor = CustomData_has_layer(ldata, CD_NORMAL); - - /* over-alloc, ngons will be skipped */ - mface = MEM_malloc_arrayN((size_t)totpoly, sizeof(*mface), __func__); - - mpoly = CustomData_get_layer(pdata, CD_MPOLY); - mloop = CustomData_get_layer(ldata, CD_MLOOP); - - mp = mpoly; - k = 0; - for (i = 0; i < totpoly; i++, mp++) { - if (ELEM(mp->totloop, 3, 4)) { - const unsigned int mp_loopstart = (unsigned int)mp->loopstart; - mf = &mface[k]; - - mf->mat_nr = mp->mat_nr; - mf->flag = mp->flag; - - mf->v1 = mp_loopstart + 0; - mf->v2 = mp_loopstart + 1; - mf->v3 = mp_loopstart + 2; - mf->v4 = (mp->totloop == 4) ? (mp_loopstart + 3) : 0; - - /* abuse edcode for temp storage and clear next loop */ - mf->edcode = (char)mp->totloop; /* only ever 3 or 4 */ - - k++; - } - } - - CustomData_free(fdata, totface); - - totface = k; - - CustomData_add_layer(fdata, CD_MFACE, CD_ASSIGN, mface, totface); - - CustomData_from_bmeshpoly(fdata, pdata, ldata, totface); - - mp = mpoly; - k = 0; - for (i = 0; i < totpoly; i++, mp++) { - if (ELEM(mp->totloop, 3, 4)) { - mf = &mface[k]; - - if (mf->edcode == 3) { - /* sort loop indices to ensure winding is correct */ - /* NO SORT - looks like we can skip this */ - - lindex[0] = mf->v1; - lindex[1] = mf->v2; - lindex[2] = mf->v3; - lindex[3] = 0; /* unused */ - - /* transform loop indices to vert indices */ - mf->v1 = mloop[mf->v1].v; - mf->v2 = mloop[mf->v2].v; - mf->v3 = mloop[mf->v3].v; - - BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata, - lindex, k, i, 3, - numTex, numCol, hasPCol, hasOrigSpace, hasLNor); - test_index_face(mf, fdata, k, 3); - } - else { - /* sort loop indices to ensure winding is correct */ - /* NO SORT - looks like we can skip this */ - - lindex[0] = mf->v1; - lindex[1] = mf->v2; - lindex[2] = mf->v3; - lindex[3] = mf->v4; - - /* transform loop indices to vert indices */ - mf->v1 = mloop[mf->v1].v; - mf->v2 = mloop[mf->v2].v; - mf->v3 = mloop[mf->v3].v; - mf->v4 = mloop[mf->v4].v; - - BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata, - lindex, k, i, 4, - numTex, numCol, hasPCol, hasOrigSpace, hasLNor); - test_index_face(mf, fdata, k, 4); - } - - mf->edcode = 0; - - k++; - } - } - - return k; -} -#endif /* USE_BMESH_SAVE_AS_COMPAT */ - - -static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata, - MFace *mface, int totloop, int findex, int loopstart, int numTex, int numCol) +static void bm_corners_to_loops_ex( + ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata, + MFace *mface, int totloop, int findex, int loopstart, int numTex, int numCol) { MTFace *texface; MTexPoly *texpoly; @@ -3342,8 +3233,9 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata, if (CustomData_external_test(fdata, CD_MDISPS)) { if (id && fdata->external) { - CustomData_external_add(ldata, id, CD_MDISPS, - totloop, fdata->external->filename); + CustomData_external_add( + ldata, id, CD_MDISPS, + totloop, fdata->external->filename); } } @@ -3381,10 +3273,11 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata, void BKE_mesh_convert_mfaces_to_mpolys(Mesh *mesh) { - BKE_mesh_convert_mfaces_to_mpolys_ex(&mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata, - mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly, - mesh->medge, mesh->mface, - &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly); + BKE_mesh_convert_mfaces_to_mpolys_ex( + &mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata, + mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly, + mesh->medge, mesh->mface, + &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly); BKE_mesh_update_customdata_pointers(mesh, true); } @@ -3401,21 +3294,23 @@ void BKE_mesh_convert_mfaces_to_mpolys(Mesh *mesh) */ void BKE_mesh_do_versions_convert_mfaces_to_mpolys(Mesh *mesh) { - BKE_mesh_convert_mfaces_to_mpolys_ex(&mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata, - mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly, - mesh->medge, mesh->mface, - &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly); + BKE_mesh_convert_mfaces_to_mpolys_ex( + &mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata, + mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly, + mesh->medge, mesh->mface, + &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly); CustomData_bmesh_do_versions_update_active_layers(&mesh->fdata, &mesh->pdata, &mesh->ldata); BKE_mesh_update_customdata_pointers(mesh, true); } -void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata, - int totedge_i, int totface_i, int totloop_i, int totpoly_i, - MEdge *medge, MFace *mface, - int *r_totloop, int *r_totpoly, - MLoop **r_mloop, MPoly **r_mpoly) +void BKE_mesh_convert_mfaces_to_mpolys_ex( + ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata, + int totedge_i, int totface_i, int totloop_i, int totpoly_i, + MEdge *medge, MFace *mface, + int *r_totloop, int *r_totpoly, + MLoop **r_mloop, MPoly **r_mpoly) { MFace *mf; MLoop *ml, *mloop; @@ -3639,10 +3534,11 @@ void BKE_mesh_polygons_flip( /* update the hide flag for edges and faces from the corresponding * flag in verts */ -void BKE_mesh_flush_hidden_from_verts_ex(const MVert *mvert, - const MLoop *mloop, - MEdge *medge, const int totedge, - MPoly *mpoly, const int totpoly) +void BKE_mesh_flush_hidden_from_verts_ex( + const MVert *mvert, + const MLoop *mloop, + MEdge *medge, const int totedge, + MPoly *mpoly, const int totpoly) { int i, j; @@ -3668,15 +3564,17 @@ void BKE_mesh_flush_hidden_from_verts_ex(const MVert *mvert, } void BKE_mesh_flush_hidden_from_verts(Mesh *me) { - BKE_mesh_flush_hidden_from_verts_ex(me->mvert, me->mloop, - me->medge, me->totedge, - me->mpoly, me->totpoly); + BKE_mesh_flush_hidden_from_verts_ex( + me->mvert, me->mloop, + me->medge, me->totedge, + me->mpoly, me->totpoly); } -void BKE_mesh_flush_hidden_from_polys_ex(MVert *mvert, - const MLoop *mloop, - MEdge *medge, const int UNUSED(totedge), - const MPoly *mpoly, const int totpoly) +void BKE_mesh_flush_hidden_from_polys_ex( + MVert *mvert, + const MLoop *mloop, + MEdge *medge, const int UNUSED(totedge), + const MPoly *mpoly, const int totpoly) { const MPoly *mp; int i; @@ -3709,18 +3607,20 @@ void BKE_mesh_flush_hidden_from_polys_ex(MVert *mvert, } void BKE_mesh_flush_hidden_from_polys(Mesh *me) { - BKE_mesh_flush_hidden_from_polys_ex(me->mvert, me->mloop, - me->medge, me->totedge, - me->mpoly, me->totpoly); + BKE_mesh_flush_hidden_from_polys_ex( + me->mvert, me->mloop, + me->medge, me->totedge, + me->mpoly, me->totpoly); } /** * simple poly -> vert/edge selection. */ -void BKE_mesh_flush_select_from_polys_ex(MVert *mvert, const int totvert, - const MLoop *mloop, - MEdge *medge, const int totedge, - const MPoly *mpoly, const int totpoly) +void BKE_mesh_flush_select_from_polys_ex( + MVert *mvert, const int totvert, + const MLoop *mloop, + MEdge *medge, const int totedge, + const MPoly *mpoly, const int totpoly) { MVert *mv; MEdge *med; @@ -3754,16 +3654,18 @@ void BKE_mesh_flush_select_from_polys_ex(MVert *mvert, const int totvert, } void BKE_mesh_flush_select_from_polys(Mesh *me) { - BKE_mesh_flush_select_from_polys_ex(me->mvert, me->totvert, - me->mloop, - me->medge, me->totedge, - me->mpoly, me->totpoly); + BKE_mesh_flush_select_from_polys_ex( + me->mvert, me->totvert, + me->mloop, + me->medge, me->totedge, + me->mpoly, me->totpoly); } -void BKE_mesh_flush_select_from_verts_ex(const MVert *mvert, const int UNUSED(totvert), - const MLoop *mloop, - MEdge *medge, const int totedge, - MPoly *mpoly, const int totpoly) +void BKE_mesh_flush_select_from_verts_ex( + const MVert *mvert, const int UNUSED(totvert), + const MLoop *mloop, + MEdge *medge, const int totedge, + MPoly *mpoly, const int totpoly) { MEdge *med; MPoly *mp; @@ -3808,10 +3710,11 @@ void BKE_mesh_flush_select_from_verts_ex(const MVert *mvert, const int UNUSED(to } void BKE_mesh_flush_select_from_verts(Mesh *me) { - BKE_mesh_flush_select_from_verts_ex(me->mvert, me->totvert, - me->mloop, - me->medge, me->totedge, - me->mpoly, me->totpoly); + BKE_mesh_flush_select_from_verts_ex( + me->mvert, me->totvert, + me->mloop, + me->medge, me->totedge, + me->mpoly, me->totpoly); } /** \} */ @@ -3839,7 +3742,7 @@ void BKE_mesh_calc_relative_deform( const float (*vert_cos_dst)[3], const float (*vert_cos_org)[3], - float (*vert_cos_new)[3]) + float (*vert_cos_new)[3]) { const MPoly *mp; int i; diff --git a/source/blender/blenkernel/intern/mesh_mapping.c b/source/blender/blenkernel/intern/mesh_mapping.c index 0143125490e2..5c9849f6b745 100644 --- a/source/blender/blenkernel/intern/mesh_mapping.c +++ b/source/blender/blenkernel/intern/mesh_mapping.c @@ -55,13 +55,13 @@ * but for now this replaces it because its unused. */ UvVertMap *BKE_mesh_uv_vert_map_create( - struct MPoly *mpoly, struct MLoop *mloop, struct MLoopUV *mloopuv, + const MPoly *mpoly, const MLoop *mloop, const MLoopUV *mloopuv, unsigned int totpoly, unsigned int totvert, const float limit[2], const bool selected, const bool use_winding) { UvVertMap *vmap; UvMapVert *buf; - MPoly *mp; + const MPoly *mp; unsigned int a; int i, totuv, nverts; @@ -103,8 +103,8 @@ UvVertMap *BKE_mesh_uv_vert_map_create( nverts = mp->totloop; for (i = 0; i < nverts; i++) { - buf->tfindex = (unsigned char)i; - buf->f = a; + buf->loop_of_poly_index = (unsigned short)i; + buf->poly_index = a; buf->separate = 0; buf->next = vmap->vert[mloop[mp->loopstart + i].v]; vmap->vert[mloop[mp->loopstart + i].v] = buf; @@ -126,7 +126,8 @@ UvVertMap *BKE_mesh_uv_vert_map_create( for (a = 0; a < totvert; a++) { UvMapVert *newvlist = NULL, *vlist = vmap->vert[a]; UvMapVert *iterv, *v, *lastv, *next; - float *uv, *uv2, uvdiff[2]; + const float *uv, *uv2; + float uvdiff[2]; while (vlist) { v = vlist; @@ -134,19 +135,19 @@ UvVertMap *BKE_mesh_uv_vert_map_create( v->next = newvlist; newvlist = v; - uv = mloopuv[mpoly[v->f].loopstart + v->tfindex].uv; + uv = mloopuv[mpoly[v->poly_index].loopstart + v->loop_of_poly_index].uv; lastv = NULL; iterv = vlist; while (iterv) { next = iterv->next; - uv2 = mloopuv[mpoly[iterv->f].loopstart + iterv->tfindex].uv; + uv2 = mloopuv[mpoly[iterv->poly_index].loopstart + iterv->loop_of_poly_index].uv; sub_v2_v2v2(uvdiff, uv2, uv); if (fabsf(uv[0] - uv2[0]) < limit[0] && fabsf(uv[1] - uv2[1]) < limit[1] && - (!use_winding || winding[iterv->f] == winding[v->f])) + (!use_winding || winding[iterv->poly_index] == winding[v->poly_index])) { if (lastv) lastv->next = next; else vlist = next; @@ -243,9 +244,10 @@ static void mesh_vert_poly_or_loop_map_create( * Generates a map where the key is the vertex and the value is a list of polys that use that vertex as a corner. * The lists are allocated from one memory pool. */ -void BKE_mesh_vert_poly_map_create(MeshElemMap **r_map, int **r_mem, - const MPoly *mpoly, const MLoop *mloop, - int totvert, int totpoly, int totloop) +void BKE_mesh_vert_poly_map_create( + MeshElemMap **r_map, int **r_mem, + const MPoly *mpoly, const MLoop *mloop, + int totvert, int totpoly, int totloop) { mesh_vert_poly_or_loop_map_create(r_map, r_mem, mpoly, mloop, totvert, totpoly, totloop, false); } @@ -254,9 +256,10 @@ void BKE_mesh_vert_poly_map_create(MeshElemMap **r_map, int **r_mem, * Generates a map where the key is the vertex and the value is a list of loops that use that vertex as a corner. * The lists are allocated from one memory pool. */ -void BKE_mesh_vert_loop_map_create(MeshElemMap **r_map, int **r_mem, - const MPoly *mpoly, const MLoop *mloop, - int totvert, int totpoly, int totloop) +void BKE_mesh_vert_loop_map_create( + MeshElemMap **r_map, int **r_mem, + const MPoly *mpoly, const MLoop *mloop, + int totvert, int totpoly, int totloop) { mesh_vert_poly_or_loop_map_create(r_map, r_mem, mpoly, mloop, totvert, totpoly, totloop, true); } @@ -310,8 +313,9 @@ void BKE_mesh_vert_looptri_map_create( * Generates a map where the key is the vertex and the value is a list of edges that use that vertex as an endpoint. * The lists are allocated from one memory pool. */ -void BKE_mesh_vert_edge_map_create(MeshElemMap **r_map, int **r_mem, - const MEdge *medge, int totvert, int totedge) +void BKE_mesh_vert_edge_map_create( + MeshElemMap **r_map, int **r_mem, + const MEdge *medge, int totvert, int totedge) { MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * (size_t)totvert, "vert-edge map"); int *indices = MEM_mallocN(sizeof(int[2]) * (size_t)totedge, "vert-edge map mem"); @@ -397,10 +401,11 @@ void BKE_mesh_vert_edge_vert_map_create( * Loops indices of a same poly are contiguous and in winding order. * The lists are allocated from one memory pool. */ -void BKE_mesh_edge_loop_map_create(MeshElemMap **r_map, int **r_mem, - const MEdge *UNUSED(medge), const int totedge, - const MPoly *mpoly, const int totpoly, - const MLoop *mloop, const int totloop) +void BKE_mesh_edge_loop_map_create( + MeshElemMap **r_map, int **r_mem, + const MEdge *UNUSED(medge), const int totedge, + const MPoly *mpoly, const int totpoly, + const MLoop *mloop, const int totloop) { MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * (size_t)totedge, "edge-poly map"); int *indices = MEM_mallocN(sizeof(int) * (size_t)totloop * 2, "edge-poly map mem"); @@ -450,10 +455,11 @@ void BKE_mesh_edge_loop_map_create(MeshElemMap **r_map, int **r_mem, * Generates a map where the key is the edge and the value is a list of polygons that use that edge. * The lists are allocated from one memory pool. */ -void BKE_mesh_edge_poly_map_create(MeshElemMap **r_map, int **r_mem, - const MEdge *UNUSED(medge), const int totedge, - const MPoly *mpoly, const int totpoly, - const MLoop *mloop, const int totloop) +void BKE_mesh_edge_poly_map_create( + MeshElemMap **r_map, int **r_mem, + const MEdge *UNUSED(medge), const int totedge, + const MPoly *mpoly, const int totpoly, + const MLoop *mloop, const int totloop) { MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * (size_t)totedge, "edge-poly map"); int *indices = MEM_mallocN(sizeof(int) * (size_t)totloop, "edge-poly map mem"); @@ -509,9 +515,10 @@ void BKE_mesh_edge_poly_map_create(MeshElemMap **r_map, int **r_mem, * ``totfinal`` could be ``tottessface`` and ``final_origindex`` its ORIGINDEX customdata. * This would allow an MPoly to loop over its tessfaces. */ -void BKE_mesh_origindex_map_create(MeshElemMap **r_map, int **r_mem, - const int totsource, - const int *final_origindex, const int totfinal) +void BKE_mesh_origindex_map_create( + MeshElemMap **r_map, int **r_mem, + const int totsource, + const int *final_origindex, const int totfinal) { MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * (size_t)totsource, "poly-tessface map"); int *indices = MEM_mallocN(sizeof(int) * (size_t)totfinal, "poly-tessface map mem"); @@ -632,8 +639,9 @@ static void poly_edge_loop_islands_calc( } if (!edge_poly_map) { - BKE_mesh_edge_poly_map_create(&edge_poly_map, &edge_poly_mem, - medge, totedge, mpoly, totpoly, mloop, totloop); + BKE_mesh_edge_poly_map_create( + &edge_poly_map, &edge_poly_mem, + medge, totedge, mpoly, totpoly, mloop, totloop); } poly_groups = MEM_callocN(sizeof(int) * (size_t)totpoly, __func__); @@ -786,10 +794,11 @@ static bool poly_is_island_boundary_smooth_cb( * (0 being used as 'invalid' flag). * Note it's callers's responsibility to MEM_freeN returned array. */ -int *BKE_mesh_calc_smoothgroups(const MEdge *medge, const int totedge, - const MPoly *mpoly, const int totpoly, - const MLoop *mloop, const int totloop, - int *r_totgroup, const bool use_bitflags) +int *BKE_mesh_calc_smoothgroups( + const MEdge *medge, const int totedge, + const MPoly *mpoly, const int totpoly, + const MLoop *mloop, const int totloop, + int *r_totgroup, const bool use_bitflags) { int *poly_groups = NULL; @@ -987,21 +996,23 @@ static bool mesh_calc_islands_loop_poly_uv( BKE_mesh_loop_islands_clear(r_island_store); BKE_mesh_loop_islands_init(r_island_store, MISLAND_TYPE_LOOP, totloop, MISLAND_TYPE_POLY, MISLAND_TYPE_EDGE); - BKE_mesh_edge_poly_map_create(&edge_poly_map, &edge_poly_mem, - edges, totedge, polys, totpoly, loops, totloop); + BKE_mesh_edge_poly_map_create( + &edge_poly_map, &edge_poly_mem, + edges, totedge, polys, totpoly, loops, totloop); if (luvs) { - BKE_mesh_edge_loop_map_create(&edge_loop_map, &edge_loop_mem, - edges, totedge, polys, totpoly, loops, totloop); + BKE_mesh_edge_loop_map_create( + &edge_loop_map, &edge_loop_mem, + edges, totedge, polys, totpoly, loops, totloop); edge_boundary_check_data.loops = loops; edge_boundary_check_data.luvs = luvs; edge_boundary_check_data.edge_loop_map = edge_loop_map; } poly_edge_loop_islands_calc( - edges, totedge, polys, totpoly, loops, totloop, edge_poly_map, false, - mesh_check_island_boundary_uv, luvs ? &edge_boundary_check_data : NULL, - &poly_groups, &num_poly_groups, &edge_borders, &num_edge_borders); + edges, totedge, polys, totpoly, loops, totloop, edge_poly_map, false, + mesh_check_island_boundary_uv, luvs ? &edge_boundary_check_data : NULL, + &poly_groups, &num_poly_groups, &edge_borders, &num_edge_borders); if (!num_poly_groups) { /* Should never happen... */ @@ -1051,8 +1062,9 @@ static bool mesh_calc_islands_loop_poly_uv( } } - BKE_mesh_loop_islands_add(r_island_store, num_lidx, loop_indices, num_pidx, poly_indices, - num_einnercuts, edge_innercut_indices); + BKE_mesh_loop_islands_add( + r_island_store, num_lidx, loop_indices, num_pidx, poly_indices, + num_einnercuts, edge_innercut_indices); } MEM_freeN(edge_poly_map); @@ -1089,7 +1101,7 @@ bool BKE_mesh_calc_islands_loop_poly_edgeseam( MeshIslandStore *r_island_store) { return mesh_calc_islands_loop_poly_uv( - verts, totvert, edges, totedge, polys, totpoly, loops, totloop, NULL, r_island_store); + verts, totvert, edges, totedge, polys, totpoly, loops, totloop, NULL, r_island_store); } /** @@ -1113,7 +1125,7 @@ bool BKE_mesh_calc_islands_loop_poly_uvmap( { BLI_assert(luvs != NULL); return mesh_calc_islands_loop_poly_uv( - verts, totvert, edges, totedge, polys, totpoly, loops, totloop, luvs, r_island_store); + verts, totvert, edges, totedge, polys, totpoly, loops, totloop, luvs, r_island_store); } /** \} */ diff --git a/source/blender/blenkernel/intern/mesh_remap.c b/source/blender/blenkernel/intern/mesh_remap.c index eef8657482f6..77aefc04f5ff 100644 --- a/source/blender/blenkernel/intern/mesh_remap.c +++ b/source/blender/blenkernel/intern/mesh_remap.c @@ -669,8 +669,9 @@ void BKE_mesh_remap_calc_edges_from_dm( v_dst_to_src_map[i].hit_dist = -1.0f; } - BKE_mesh_vert_edge_map_create(&vert_to_edge_src_map, &vert_to_edge_src_map_mem, - edges_src, num_verts_src, num_edges_src); + BKE_mesh_vert_edge_map_create( + &vert_to_edge_src_map, &vert_to_edge_src_map_mem, + edges_src, num_verts_src, num_edges_src); dm_src->getVertCos(dm_src, vcos_src); @@ -932,8 +933,9 @@ void BKE_mesh_remap_calc_edges_from_dm( indices[sources_num] = j; sources_num++; } - mesh_remap_item_define(r_map, i, hit_dist_accum / totweights, 0, - sources_num, indices, weights); + mesh_remap_item_define( + r_map, i, hit_dist_accum / totweights, 0, + sources_num, indices, weights); } else { /* No source for this dest edge! */ @@ -1147,8 +1149,9 @@ void BKE_mesh_remap_calc_loops_from_dm( BLI_AStarGraph *as_graphdata = NULL; BLI_AStarSolution as_solution = {0}; - const int isld_steps_src = islands_precision_src ? - max_ii((int)(ASTAR_STEPS_MAX * islands_precision_src + 0.499f), 1) : 0; + const int isld_steps_src = ( + islands_precision_src ? + max_ii((int)(ASTAR_STEPS_MAX * islands_precision_src + 0.499f), 1) : 0); float (*poly_nors_src)[3] = NULL; float (*loop_nors_src)[3] = NULL; @@ -1220,8 +1223,9 @@ void BKE_mesh_remap_calc_loops_from_dm( CustomData_set_layer_flag(pdata_dst, CD_NORMAL, CD_FLAG_TEMPORARY); } if (dirty_nors_dst) { - BKE_mesh_calc_normals_poly(verts_dst, NULL, numverts_dst, loops_dst, polys_dst, - numloops_dst, numpolys_dst, poly_nors_dst, true); + BKE_mesh_calc_normals_poly( + verts_dst, NULL, numverts_dst, loops_dst, polys_dst, + numloops_dst, numpolys_dst, poly_nors_dst, true); } } if (need_lnors_dst) { @@ -1234,10 +1238,11 @@ void BKE_mesh_remap_calc_loops_from_dm( loop_nors_dst = CustomData_add_layer(ldata_dst, CD_NORMAL, CD_CALLOC, NULL, numloops_dst); CustomData_set_layer_flag(ldata_dst, CD_NORMAL, CD_FLAG_TEMPORARY); } - BKE_mesh_normals_loop_split(verts_dst, numverts_dst, edges_dst, numedges_dst, - loops_dst, loop_nors_dst, numloops_dst, - polys_dst, (const float (*)[3])poly_nors_dst, numpolys_dst, - use_split_nors_dst, split_angle_dst, NULL, custom_nors_dst, NULL); + BKE_mesh_normals_loop_split( + verts_dst, numverts_dst, edges_dst, numedges_dst, + loops_dst, loop_nors_dst, numloops_dst, + polys_dst, (const float (*)[3])poly_nors_dst, numpolys_dst, + use_split_nors_dst, split_angle_dst, NULL, custom_nors_dst, NULL); } } if (need_pnors_src || need_lnors_src) { @@ -1254,17 +1259,20 @@ void BKE_mesh_remap_calc_loops_from_dm( } if (use_from_vert) { - BKE_mesh_vert_loop_map_create(&vert_to_loop_map_src, &vert_to_loop_map_src_buff, - polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src); + BKE_mesh_vert_loop_map_create( + &vert_to_loop_map_src, &vert_to_loop_map_src_buff, + polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src); if (mode & MREMAP_USE_POLY) { - BKE_mesh_vert_poly_map_create(&vert_to_poly_map_src, &vert_to_poly_map_src_buff, - polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src); + BKE_mesh_vert_poly_map_create( + &vert_to_poly_map_src, &vert_to_poly_map_src_buff, + polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src); } } /* Needed for islands (or plain mesh) to AStar graph conversion. */ - BKE_mesh_edge_poly_map_create(&edge_to_poly_map_src, &edge_to_poly_map_src_buff, - edges_src, num_edges_src, polys_src, num_polys_src, loops_src, num_loops_src); + BKE_mesh_edge_poly_map_create( + &edge_to_poly_map_src, &edge_to_poly_map_src_buff, + edges_src, num_edges_src, polys_src, num_polys_src, loops_src, num_loops_src); if (use_from_vert) { loop_to_poly_map_src = MEM_mallocN(sizeof(*loop_to_poly_map_src) * (size_t)num_loops_src, __func__); poly_cents_src = MEM_mallocN(sizeof(*poly_cents_src) * (size_t)num_polys_src, __func__); @@ -1345,8 +1353,9 @@ void BKE_mesh_remap_calc_loops_from_dm( } } /* verts 'ownership' is transfered to treedata here, which will handle its freeing. */ - bvhtree_from_mesh_verts_ex(&treedata[tindex], verts_src, num_verts_src, verts_allocated_src, - verts_active, num_verts_active, 0.0, 2, 6); + bvhtree_from_mesh_verts_ex( + &treedata[tindex], verts_src, num_verts_src, verts_allocated_src, + verts_active, num_verts_active, 0.0, 2, 6); if (verts_allocated_src) { verts_allocated_src = false; /* Only 'give' our verts once, to first tree! */ } @@ -1481,13 +1490,15 @@ void BKE_mesh_remap_calc_loops_from_dm( BLI_assert(index_src != -1); const float dot = dot_v3v3(nors_src[index_src], *nor_dst); - pidx_src = (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ? - loop_to_poly_map_src[index_src] : index_src; + pidx_src = ( + (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ? + loop_to_poly_map_src[index_src] : index_src); /* WARNING! This is not the *real* lidx_src in case of POLYNOR, we only use it * to check we stay on current island (all loops from a given poly are * on same island!). */ - lidx_src = (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ? - index_src : polys_src[pidx_src].loopstart; + lidx_src = ( + (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ? + index_src : polys_src[pidx_src].loopstart); /* A same vert may be at the boundary of several islands! Hence, we have to ensure * poly/loop we are currently considering *belongs* to current island! */ @@ -1506,7 +1517,7 @@ void BKE_mesh_remap_calc_loops_from_dm( if (!pcent_dst_valid) { BKE_mesh_calc_poly_center( - mp_dst, &loops_dst[mp_dst->loopstart], verts_dst, pcent_dst); + mp_dst, &loops_dst[mp_dst->loopstart], verts_dst, pcent_dst); pcent_dst_valid = true; } pcent_src = poly_cents_src[pidx_src]; @@ -1737,8 +1748,9 @@ void BKE_mesh_remap_calc_loops_from_dm( BLI_space_transform_apply(space_transform, tmp_co); } - pidx_src = use_islands ? best_island->indices[last_valid_pidx_isld_src] : - last_valid_pidx_isld_src; + pidx_src = ( + use_islands ? best_island->indices[last_valid_pidx_isld_src] : + last_valid_pidx_isld_src); mp_src = &polys_src[pidx_src]; ml_src = &loops_src[mp_src->loopstart]; for (j = 0; j < mp_src->totloop; j++, ml_src++) { @@ -1822,8 +1834,9 @@ void BKE_mesh_remap_calc_loops_from_dm( BLI_space_transform_apply(space_transform, tmp_co); } - pidx_src = use_islands ? best_island->indices[last_valid_pidx_isld_src] : - last_valid_pidx_isld_src; + pidx_src = ( + use_islands ? best_island->indices[last_valid_pidx_isld_src] : + last_valid_pidx_isld_src); mp_src = &polys_src[pidx_src]; /* Create that one on demand. */ @@ -1984,8 +1997,9 @@ void BKE_mesh_remap_calc_polys_from_dm( CustomData_set_layer_flag(pdata_dst, CD_NORMAL, CD_FLAG_TEMPORARY); } if (dirty_nors_dst) { - BKE_mesh_calc_normals_poly(verts_dst, NULL, numverts_dst, loops_dst, polys_dst, numloops_dst, numpolys_dst, - poly_nors_dst, true); + BKE_mesh_calc_normals_poly( + verts_dst, NULL, numverts_dst, loops_dst, polys_dst, numloops_dst, numpolys_dst, + poly_nors_dst, true); } } @@ -2168,8 +2182,9 @@ void BKE_mesh_remap_calc_polys_from_dm( tri_vidx_2d[1][2] = 3; } else { - BLI_polyfill_calc(poly_vcos_2d, (unsigned int)mp->totloop, -1, - (unsigned int (*)[3])tri_vidx_2d); + BLI_polyfill_calc( + poly_vcos_2d, (unsigned int)mp->totloop, -1, + (unsigned int (*)[3])tri_vidx_2d); } for (j = 0; j < tris_num; j++) { diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c index b0577fdd50db..5c835bbf0fa2 100644 --- a/source/blender/blenkernel/intern/mesh_validate.c +++ b/source/blender/blenkernel/intern/mesh_validate.c @@ -212,15 +212,16 @@ static int search_polyloop_cmp(const void *v1, const void *v2) * * \return false if no changes needed to be made. */ -bool BKE_mesh_validate_arrays(Mesh *mesh, - MVert *mverts, unsigned int totvert, - MEdge *medges, unsigned int totedge, - MFace *mfaces, unsigned int totface, - MLoop *mloops, unsigned int totloop, - MPoly *mpolys, unsigned int totpoly, - MDeformVert *dverts, /* assume totvert length */ - const bool do_verbose, const bool do_fixes, - bool *r_changed) +bool BKE_mesh_validate_arrays( + Mesh *mesh, + MVert *mverts, unsigned int totvert, + MEdge *medges, unsigned int totedge, + MFace *mfaces, unsigned int totface, + MLoop *mloops, unsigned int totloop, + MPoly *mpolys, unsigned int totpoly, + MDeformVert *dverts, /* assume totvert length */ + const bool do_verbose, const bool do_fixes, + bool *r_changed) { # define REMOVE_EDGE_TAG(_me) { _me->v2 = _me->v1; free_flag.edges = do_fixes; } (void)0 # define IS_REMOVED_EDGE(_me) (_me->v2 == _me->v1) @@ -875,9 +876,10 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, return is_valid; } -static bool mesh_validate_customdata(CustomData *data, CustomDataMask mask, - const bool do_verbose, const bool do_fixes, - bool *r_change) +static bool mesh_validate_customdata( + CustomData *data, CustomDataMask mask, + const bool do_verbose, const bool do_fixes, + bool *r_change) { bool is_valid = true; bool has_fixes = false; @@ -928,11 +930,12 @@ static bool mesh_validate_customdata(CustomData *data, CustomDataMask mask, /** * \returns is_valid. */ -bool BKE_mesh_validate_all_customdata(CustomData *vdata, CustomData *edata, - CustomData *ldata, CustomData *pdata, - const bool check_meshmask, - const bool do_verbose, const bool do_fixes, - bool *r_change) +bool BKE_mesh_validate_all_customdata( + CustomData *vdata, CustomData *edata, + CustomData *ldata, CustomData *pdata, + const bool check_meshmask, + const bool do_verbose, const bool do_fixes, + bool *r_change) { bool is_valid = true; bool is_change_v, is_change_e, is_change_l, is_change_p; @@ -992,7 +995,7 @@ bool BKE_mesh_validate_all_customdata(CustomData *vdata, CustomData *edata, * * \returns true if a change is made. */ -int BKE_mesh_validate(Mesh *me, const int do_verbose, const int cddata_check_mask) +bool BKE_mesh_validate(Mesh *me, const bool do_verbose, const bool cddata_check_mask) { bool is_valid = true; bool changed; @@ -1089,7 +1092,7 @@ void BKE_mesh_cd_validate(Mesh *me) * Check all material indices of polygons are valid, invalid ones are set to 0. * \returns is_valid. */ -int BKE_mesh_validate_material_indices(Mesh *me) +bool BKE_mesh_validate_material_indices(Mesh *me) { MPoly *mp; const int max_idx = max_ii(0, me->totcol - 1); @@ -1268,9 +1271,10 @@ struct EdgeSort { }; /* edges have to be added with lowest index first for sorting */ -static void to_edgesort(struct EdgeSort *ed, - unsigned int v1, unsigned int v2, - char is_loose, short is_draw) +static void to_edgesort( + struct EdgeSort *ed, + unsigned int v1, unsigned int v2, + char is_loose, short is_draw) { if (v1 < v2) { ed->v1 = v1; ed->v2 = v2; @@ -1419,9 +1423,10 @@ void BKE_mesh_calc_edges_legacy(Mesh *me, const bool use_old) MEdge *medge; int totedge = 0; - mesh_calc_edges_mdata(me->mvert, me->mface, me->mloop, me->mpoly, - me->totvert, me->totface, me->totloop, me->totpoly, - use_old, &medge, &totedge); + mesh_calc_edges_mdata( + me->mvert, me->mface, me->mloop, me->mpoly, + me->totvert, me->totface, me->totloop, me->totpoly, + use_old, &medge, &totedge); if (totedge == 0) { /* flag that mesh has edges */ diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 368a691e7789..9fc3fc4ba646 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -121,7 +121,7 @@ ModifierData *modifier_new(int type) { const ModifierTypeInfo *mti = modifierType_getInfo(type); ModifierData *md = MEM_callocN(mti->structSize, mti->structName); - + /* note, this name must be made unique later */ BLI_strncpy(md->name, DATA_(mti->name), sizeof(md->name)); @@ -478,7 +478,7 @@ bool modifier_isEnabled(struct Scene *scene, ModifierData *md, int required_mode if (scene != NULL && mti->isDisabled && mti->isDisabled(md, required_mode == eModifierMode_Render)) return false; if (md->mode & eModifierMode_DisableTemporary) return false; if ((required_mode & eModifierMode_Editmode) && !(mti->flags & eModifierTypeFlag_SupportsEditmode)) return false; - + return true; } @@ -494,7 +494,7 @@ CDMaskLink *modifiers_calcDataMasks(struct Scene *scene, Object *ob, ModifierDat const ModifierTypeInfo *mti = modifierType_getInfo(md->type); curr = MEM_callocN(sizeof(CDMaskLink), "CDMaskLink"); - + if (modifier_isEnabled(scene, md, required_mode)) { if (mti->requiredDataMask) curr->mask = mti->requiredDataMask(ob, md); @@ -603,7 +603,7 @@ Object *modifiers_isDeformedByArmature(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); ArmatureModifierData *amd = NULL; - + /* return the first selected armature, this lets us use multiple armatures */ for (; md; md = md->next) { if (md->type == eModifierType_Armature) { @@ -612,10 +612,10 @@ Object *modifiers_isDeformedByArmature(Object *ob) return amd->object; } } - + if (amd) /* if were still here then return the last armature */ return amd->object; - + return NULL; } @@ -627,7 +627,7 @@ Object *modifiers_isDeformedByLattice(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); LatticeModifierData *lmd = NULL; - + /* return the first selected lattice, this lets us use multiple lattices */ for (; md; md = md->next) { if (md->type == eModifierType_Lattice) { @@ -636,10 +636,10 @@ Object *modifiers_isDeformedByLattice(Object *ob) return lmd->object; } } - + if (lmd) /* if were still here then return the last lattice */ return lmd->object; - + return NULL; } @@ -651,7 +651,7 @@ Object *modifiers_isDeformedByCurve(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); CurveModifierData *cmd = NULL; - + /* return the first selected curve, this lets us use multiple curves */ for (; md; md = md->next) { if (md->type == eModifierType_Curve) { @@ -660,10 +660,10 @@ Object *modifiers_isDeformedByCurve(Object *ob) return cmd->object; } } - + if (cmd) /* if were still here then return the last curve */ return cmd->object; - + return NULL; } @@ -697,7 +697,7 @@ bool modifiers_isCorrectableDeformed(struct Scene *scene, Object *ob) if (ob->mode == OB_MODE_EDIT) required_mode |= eModifierMode_Editmode; - + for (; md; md = md->next) { if (!modifier_isEnabled(scene, md, required_mode)) { /* pass */ diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index 9c8fc9bfd0c0..636157b08dd9 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -189,7 +189,7 @@ static BLI_bitmap *multires_mdisps_downsample_hidden(BLI_bitmap *old_hidden, for (x = 0; x < new_gridsize; x++) { old_value = BLI_BITMAP_TEST(old_hidden, factor * y * old_gridsize + x * factor); - + BLI_BITMAP_SET(new_hidden, y * new_gridsize + x, old_value); } } @@ -204,7 +204,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, BLI_bitmap **grid_hidden = ccgdm->gridHidden; int *gridOffset; int i, j; - + gridOffset = ccgdm->dm.getGridOffset(&ccgdm->dm); for (i = 0; i < me->totpoly; i++) { @@ -212,7 +212,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, int g = gridOffset[i] + j; const MDisps *md = &mdisps[g]; BLI_bitmap *gh = md->hidden; - + if (gh) { grid_hidden[g] = multires_mdisps_downsample_hidden(gh, md->level, level); @@ -226,7 +226,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, static void multires_mdisps_subdivide_hidden(MDisps *md, int new_level) { BLI_bitmap *subd; - + BLI_assert(md->hidden); /* nothing to do if already subdivided enough */ @@ -237,7 +237,7 @@ static void multires_mdisps_subdivide_hidden(MDisps *md, int new_level) md->level, new_level, NULL); - + /* swap in the subdivided data */ MEM_freeN(md->hidden); md->hidden = subd; @@ -250,7 +250,7 @@ static MDisps *multires_mdisps_initialize_hidden(Mesh *me, int level) int gridsize = BKE_ccg_gridsize(level); int gridarea = SQUARE(gridsize); int i, j; - + for (i = 0; i < me->totpoly; i++) { bool hide = false; @@ -474,7 +474,7 @@ static int get_levels_from_disps(Object *ob) for (j = 0; j < me->mpoly[i].totloop; j++, md++) { if (md->totdisp == 0) continue; - + while (1) { int side = (1 << (totlvl - 1)) + 1; int lvl_totdisp = side * side; @@ -484,9 +484,9 @@ static int get_levels_from_disps(Object *ob) totlvl--; else totlvl++; - + } - + break; } } @@ -537,7 +537,7 @@ static void multires_reallocate_mdisps(int totloop, MDisps *mdisps, int lvl) if (mdisps[i].disps) MEM_freeN(mdisps[i].disps); - + if (mdisps[i].level && mdisps[i].hidden) multires_mdisps_subdivide_hidden(&mdisps[i], lvl); @@ -735,7 +735,7 @@ static DerivedMesh *subsurf_dm_create_local(Object *ob, DerivedMesh *dm, int lvl if (alloc_paint_mask) flags |= SUBSURF_ALLOC_PAINT_MASK; - + return subsurf_make_derived_from_derived(dm, &smd, NULL, flags); } @@ -801,7 +801,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) /* find center */ for (j = 0; j < pmap[i].count; j++) { const MPoly *p = &me->mpoly[pmap[i].indices[j]]; - + /* this double counts, not sure if that's bad or good */ for (k = 0; k < p->totloop; ++k) { int vndx = me->mloop[p->loopstart + k].v; @@ -827,18 +827,18 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) fake_poly.loopstart = 0; fake_loops = MEM_malloc_arrayN(p->totloop, sizeof(MLoop), "fake_loops"); fake_co = MEM_malloc_arrayN(p->totloop, 3 * sizeof(float), "fake_co"); - + for (k = 0; k < p->totloop; ++k) { int vndx = me->mloop[p->loopstart + k].v; - + fake_loops[k].v = k; - + if (vndx == i) copy_v3_v3(fake_co[k], center); else copy_v3_v3(fake_co[k], origco[vndx]); } - + BKE_mesh_calc_poly_normal_coords(&fake_poly, fake_loops, (const float(*)[3])fake_co, no); MEM_freeN(fake_loops); @@ -853,7 +853,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) copy_v3_v3(push, avg_no); mul_v3_fl(push, dist); add_v3_v3(me->mvert[i].co, push); - + } MEM_freeN(origco); @@ -942,7 +942,7 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl ccgSubSurf_updateLevels(ss, lvl, NULL, 0); /* reallocate displacements */ - multires_reallocate_mdisps(me->totloop, mdisps, totlvl); + multires_reallocate_mdisps(me->totloop, mdisps, totlvl); /* compute displacements */ multiresModifier_disp_run(highdm, me, NULL, CALC_DISPLACEMENTS, subGridData, totlvl); @@ -955,7 +955,7 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl } else { /* only reallocate, nothing to upsample */ - multires_reallocate_mdisps(me->totloop, mdisps, totlvl); + multires_reallocate_mdisps(me->totloop, mdisps, totlvl); } multires_set_tot_level(ob, mmd, totlvl); @@ -1128,7 +1128,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm int *gridOffset; int i, gridSize, dGridSize, dSkip; int totloop, totpoly; - + /* this happens in the dm made by bmesh_mdisps_space_set */ if (dm2 && CustomData_has_layer(&dm2->loopData, CD_MDISPS)) { mpoly = CustomData_get_layer(&dm2->polyData, CD_MPOLY); @@ -1140,7 +1140,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm totloop = me->totloop; totpoly = me->totpoly; } - + if (!mdisps) { if (op == CALC_DISPLACEMENTS) mdisps = CustomData_add_layer(&me->ldata, CD_MDISPS, CD_DEFAULT, NULL, me->totloop); @@ -1214,7 +1214,7 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm) if (mdisps) { int lvl = ccgdm->multires.lvl; int totlvl = ccgdm->multires.totlvl; - + if (lvl < totlvl) { DerivedMesh *lowdm, *cddm, *highdm; CCGElem **highGridData, **lowGridData, **subGridData, **gridData, *diffGrid; @@ -1311,7 +1311,7 @@ void multires_modifier_update_hidden(DerivedMesh *dm) if (mdisps) { int i; - + for (i = 0; i < me->totloop; i++) { MDisps *md = &mdisps[i]; BLI_bitmap *gh = grid_hidden[i]; @@ -1325,7 +1325,7 @@ void multires_modifier_update_hidden(DerivedMesh *dm) md->hidden); if (md->hidden) MEM_freeN(md->hidden); - + md->hidden = gh; } } @@ -1342,10 +1342,10 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) MultiresModifierData *mmd = get_multires_modifier(NULL, ob, 1); int *gridOffset, totlvl; int i, k, numGrids, gridSize, dGridSize, dSkip; - + if (!mmd) return; - + mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS); if (!mdisps) { @@ -1354,7 +1354,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) totlvl = mmd->totlvl; ccgdm = multires_dm_create_local(ob, dm, totlvl, totlvl, mmd->simple, false); - + subsurf = subsurf_dm_create_local(ob, dm, totlvl, mmd->simple, mmd->flags & eMultiresModifierFlag_ControlEdges, mmd->flags & eMultiresModifierFlag_PlainUv, 0); @@ -1369,7 +1369,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) subGridData[i] = MEM_calloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData"); memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize); } - + /* numGrids = ccgdm->dm->getNumGrids((DerivedMesh *)ccgdm); */ /*UNUSED*/ gridSize = ccgdm->getGridSize((DerivedMesh *)ccgdm); gridData = ccgdm->getGridData((DerivedMesh *)ccgdm); @@ -1384,7 +1384,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) for (i = 0; i < dm->numPolyData; ++i) { const int numVerts = mpoly[i].totloop; int S, x, y, gIndex = gridOffset[i]; - + for (S = 0; S < numVerts; ++S, ++gIndex, ++k) { MDisps *mdisp = &mdisps[mpoly[i].loopstart + S]; /* CCGElem *grid = gridData[gIndex]; */ /* UNUSED */ @@ -1405,7 +1405,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) float *data = dispgrid[dGridSize * y * dSkip + x * dSkip]; float *co = CCG_grid_elem_co(&key, subgrid, x, y); float mat[3][3], dco[3]; - + /* construct tangent space matrix */ grid_tangent_matrix(mat, &key, x, y, subgrid); @@ -1420,7 +1420,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) else if (from == MULTIRES_SPACE_ABSOLUTE) { copy_v3_v3(dco, data); } - + /*now, convert to desired displacement type*/ if (to == MULTIRES_SPACE_TANGENT) { invert_m3(mat); @@ -1544,10 +1544,10 @@ void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, const int st_max = st - 1; float urat, vrat, uopp; float d[4][3], d2[2][3]; - + if (!disps || isnan(u) || isnan(v)) return; - + if (u < 0) u = 0; else if (u >= st) @@ -1564,7 +1564,7 @@ void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, if (x2 >= st) x2 = st_max; if (y2 >= st) y2 = st_max; - + urat = u - x; vrat = v - y; uopp = 1 - urat; @@ -1639,7 +1639,7 @@ void multires_load_old_250(Mesh *me) for (i = 0; i < me->totface; i++) if (mdisps[i].totdisp) old_mdisps_convert(&me->mface[i], &mdisps[i]); - + CustomData_add_layer(&me->ldata, CD_MDISPS, CD_CALLOC, NULL, me->totloop); mdisps2 = CustomData_get_layer(&me->ldata, CD_MDISPS); @@ -1648,7 +1648,7 @@ void multires_load_old_250(Mesh *me) for (i = 0; i < me->totface; i++, mf++) { int nvert = mf->v4 ? 4 : 3; int totdisp = mdisps[i].totdisp / nvert; - + for (j = 0; j < nvert; j++, k++) { mdisps2[k].disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disp in conversion"); mdisps2[k].totdisp = totdisp; @@ -1709,11 +1709,11 @@ static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const Mult { int i, j; IndexNode *node = NULL; - + (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert face map"); (*mem) = MEM_calloc_arrayN(totface, 4 * sizeof(IndexNode), "vert face map mem"); node = *mem; - + /* Find the users */ for (i = 0; i < totface; ++i) { for (j = 0; j < (mface[i].v[3] ? 4 : 3); ++j, ++node) { @@ -1728,11 +1728,11 @@ static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const Mult { int i, j; IndexNode *node = NULL; - + (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert edge map"); (*mem) = MEM_calloc_arrayN(totedge, 2 * sizeof(IndexNode), "vert edge map mem"); node = *mem; - + /* Find the users */ for (i = 0; i < totedge; ++i) { for (j = 0; j < 2; ++j, ++node) { @@ -1853,7 +1853,7 @@ static void multires_mvert_to_ss(DerivedMesh *dm, MVert *mvert) vd = ccgSubSurf_getFaceCenterData(f); copy_v3_v3(CCG_elem_co(&key, vd), mvert[i].co); i++; - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++, i++) { vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x); @@ -2084,7 +2084,7 @@ static void multires_load_old_vcols(Mesh *me) * so we can assume the active vcol layer is the correct one */ if (!(mcol = CustomData_get_layer(&me->fdata, CD_MCOL))) return; - + for (i = 0; i < me->totface; ++i) { for (j = 0; j < 4; ++j) { mcol[i * 4 + j].a = colface[i].col[j].a; @@ -2163,7 +2163,7 @@ void multires_load_old(Object *ob, Mesh *me) /* Add a multires modifier to the object */ md = ob->modifiers.first; while (md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform) - md = md->next; + md = md->next; mmd = (MultiresModifierData *)modifier_new(eModifierType_Multires); BLI_insertlinkbefore(&ob->modifiers, md, mmd); diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c index 1db4e878c9a1..f91d88a8a4a3 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -79,31 +79,31 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip) { NlaStrip *cs, *csn; - + /* sanity checks */ if (strip == NULL) return; - + /* free child-strips */ for (cs = strip->strips.first; cs; cs = csn) { csn = cs->next; BKE_nlastrip_free(&strip->strips, cs); } - + /* remove reference to action */ if (strip->act) id_us_min(&strip->act->id); - + /* free remapping info */ //if (strip->remap) // BKE_animremap_free(); - + /* free own F-Curves */ free_fcurves(&strip->fcurves); - + /* free own F-Modifiers */ free_fmodifiers(&strip->modifiers); - + /* free the strip itself */ if (strips) BLI_freelinkN(strips, strip); @@ -117,17 +117,17 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip) void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt) { NlaStrip *strip, *stripn; - + /* sanity checks */ if (nlt == NULL) return; - + /* free strips */ for (strip = nlt->strips.first; strip; strip = stripn) { stripn = strip->next; BKE_nlastrip_free(&nlt->strips, strip); } - + /* free NLA track itself now */ if (tracks) BLI_freelinkN(tracks, nlt); @@ -141,17 +141,17 @@ void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt) void BKE_nla_tracks_free(ListBase *tracks) { NlaTrack *nlt, *nltn; - + /* sanity checks */ if (ELEM(NULL, tracks, tracks->first)) return; - + /* free tracks one by one */ for (nlt = tracks->first; nlt; nlt = nltn) { nltn = nlt->next; BKE_nlatrack_free(tracks, nlt); } - + /* clear the list's pointers to be safe */ BLI_listbase_clear(tracks); } @@ -167,15 +167,15 @@ NlaStrip *BKE_nlastrip_copy(Main *bmain, NlaStrip *strip, const bool use_same_ac { NlaStrip *strip_d; NlaStrip *cs, *cs_d; - + /* sanity check */ if (strip == NULL) return NULL; - + /* make a copy */ strip_d = MEM_dupallocN(strip); strip_d->next = strip_d->prev = NULL; - + /* handle action */ if (strip_d->act) { if (use_same_action) { @@ -187,19 +187,19 @@ NlaStrip *BKE_nlastrip_copy(Main *bmain, NlaStrip *strip, const bool use_same_ac strip_d->act = BKE_action_copy(bmain, strip_d->act); } } - + /* copy F-Curves and modifiers */ copy_fcurves(&strip_d->fcurves, &strip->fcurves); copy_fmodifiers(&strip_d->modifiers, &strip->modifiers); - + /* make a copy of all the child-strips, one at a time */ BLI_listbase_clear(&strip_d->strips); - + for (cs = strip->strips.first; cs; cs = cs->next) { cs_d = BKE_nlastrip_copy(bmain, cs, use_same_action); BLI_addtail(&strip_d->strips, cs_d); } - + /* return the strip */ return strip_d; } @@ -209,23 +209,23 @@ NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt, const bool use_same_acti { NlaStrip *strip, *strip_d; NlaTrack *nlt_d; - + /* sanity check */ if (nlt == NULL) return NULL; - + /* make a copy */ nlt_d = MEM_dupallocN(nlt); nlt_d->next = nlt_d->prev = NULL; - + /* make a copy of all the strips, one at a time */ BLI_listbase_clear(&nlt_d->strips); - + for (strip = nlt->strips.first; strip; strip = strip->next) { strip_d = BKE_nlastrip_copy(bmain, strip, use_same_actions); BLI_addtail(&nlt_d->strips, strip_d); } - + /* return the copy */ return nlt_d; } @@ -234,14 +234,14 @@ NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt, const bool use_same_acti void BKE_nla_tracks_copy(Main *bmain, ListBase *dst, ListBase *src) { NlaTrack *nlt, *nlt_d; - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + /* clear out the destination list first for precautions... */ BLI_listbase_clear(dst); - + /* copy each NLA-track, one at a time */ for (nlt = src->first; nlt; nlt = nlt->next) { /* make a copy, and add the copy to the destination list */ @@ -253,35 +253,35 @@ void BKE_nla_tracks_copy(Main *bmain, ListBase *dst, ListBase *src) /* Adding ------------------------------------------- */ -/* Add a NLA Track to the given AnimData +/* Add a NLA Track to the given AnimData * - prev: NLA-Track to add the new one after */ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) { NlaTrack *nlt; - + /* sanity checks */ if (adt == NULL) return NULL; - + /* allocate new track */ nlt = MEM_callocN(sizeof(NlaTrack), "NlaTrack"); - + /* set settings requiring the track to not be part of the stack yet */ nlt->flag = NLATRACK_SELECTED; nlt->index = BLI_listbase_count(&adt->nla_tracks); - + /* add track to stack, and make it the active one */ if (prev) BLI_insertlinkafter(&adt->nla_tracks, prev, nlt); else BLI_addtail(&adt->nla_tracks, nlt); BKE_nlatrack_set_active(&adt->nla_tracks, nlt); - + /* must have unique name, but we need to seed this */ strcpy(nlt->name, "NlaTrack"); BLI_uniquename(&adt->nla_tracks, nlt, DATA_("NlaTrack"), '.', offsetof(NlaTrack, name), sizeof(nlt->name)); - + /* return the new track */ return nlt; } @@ -290,15 +290,15 @@ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) NlaStrip *BKE_nlastrip_new(bAction *act) { NlaStrip *strip; - + /* sanity checks */ if (act == NULL) return NULL; - + /* allocate new strip */ strip = MEM_callocN(sizeof(NlaStrip), "NlaStrip"); - - /* generic settings + + /* generic settings * - selected flag to highlight this to the user * - (XXX) disabled Auto-Blends, as this was often causing some unwanted effects * - (XXX) synchronization of strip-length in accordance with changes to action-length @@ -306,23 +306,23 @@ NlaStrip *BKE_nlastrip_new(bAction *act) * though this decision is still subject to further review... */ strip->flag = NLASTRIP_FLAG_SELECT; - + /* assign the action reference */ strip->act = act; id_us_plus(&act->id); - - /* determine initial range + + /* determine initial range * - strip length cannot be 0... ever... */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + strip->start = strip->actstart; strip->end = (IS_EQF(strip->actstart, strip->actend)) ? (strip->actstart + 1.0f) : (strip->actend); - + /* strip should be referenced as-is */ strip->scale = 1.0f; strip->repeat = 1.0f; - + /* return the new strip */ return strip; } @@ -332,28 +332,28 @@ NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act) { NlaStrip *strip; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, act)) return NULL; - + /* create a new NLA strip */ strip = BKE_nlastrip_new(act); if (strip == NULL) return NULL; - + /* firstly try adding strip to last track, but if that fails, add to a new track */ if (BKE_nlatrack_add_strip(adt->nla_tracks.last, strip) == 0) { - /* trying to add to the last track failed (no track or no space), + /* trying to add to the last track failed (no track or no space), * so add a new track to the stack, and add to that... */ nlt = BKE_nlatrack_add(adt, NULL); BKE_nlatrack_add_strip(nlt, strip); } - + /* automatically name it too */ BKE_nlastrip_validate_name(adt, strip); - + /* returns the strip added */ return strip; } @@ -362,14 +362,14 @@ NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act) NlaStrip *BKE_nla_add_soundstrip(Scene *scene, Speaker *speaker) { NlaStrip *strip = MEM_callocN(sizeof(NlaStrip), "NlaSoundStrip"); - + /* if speaker has a sound, set the strip length to the length of the sound, * otherwise default to length of 10 frames */ #ifdef WITH_AUDASPACE if (speaker->sound) { AUD_SoundInfo info = AUD_getInfo(speaker->sound->playback_handle); - + strip->end = (float)ceil((double)info.length * FPS); } else @@ -380,17 +380,17 @@ NlaStrip *BKE_nla_add_soundstrip(Scene *scene, Speaker *speaker) (void)scene; (void)speaker; } - + /* general settings */ strip->type = NLASTRIP_TYPE_SOUND; - + strip->flag = NLASTRIP_FLAG_SELECT; strip->extendmode = NLASTRIP_EXTEND_NOTHING; /* nothing to extend... */ - + /* strip should be referenced as-is */ strip->scale = 1.0f; strip->repeat = 1.0f; - + /* return this strip */ return strip; } @@ -407,19 +407,19 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short { float actlength, scale; // float repeat; // UNUSED - + /* get number of repeats */ if (IS_EQF(strip->repeat, 0.0f)) strip->repeat = 1.0f; // repeat = strip->repeat; // UNUSED - + /* scaling */ if (IS_EQF(strip->scale, 0.0f)) strip->scale = 1.0f; scale = fabsf(strip->scale); /* scale must be positive - we've got a special flag for reversing */ - + /* length of referenced action */ actlength = strip->actend - strip->actstart; if (IS_EQF(actlength, 0.0f)) actlength = 1.0f; - + /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { /* FIXME: this won't work right with Graph Editor? */ @@ -431,7 +431,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF((float)cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip + /* this case prevents the motion snapping back to the first frame at the end of the strip * by catching the case where repeats is a whole number, which means that the end of the strip * could also be interpreted as the end of the start of a repeat */ @@ -454,7 +454,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF(cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip + /* this case prevents the motion snapping back to the first frame at the end of the strip * by catching the case where repeats is a whole number, which means that the end of the strip * could also be interpreted as the end of the start of a repeat */ @@ -476,10 +476,10 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short static float nlastrip_get_frame_transition(NlaStrip *strip, float cframe, short mode) { float length; - + /* length of strip */ length = strip->end - strip->start; - + /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { if (mode == NLATIME_CONVERT_MAP) @@ -507,7 +507,7 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) case NLASTRIP_TYPE_META: /* meta - for now, does the same as transition (is really just an empty container) */ case NLASTRIP_TYPE_TRANSITION: /* transition */ return nlastrip_get_frame_transition(strip, cframe, mode); - + case NLASTRIP_TYPE_CLIP: /* action-clip (default) */ default: return nlastrip_get_frame_actionclip(strip, cframe, mode); @@ -524,15 +524,15 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) { NlaStrip *strip; - - /* sanity checks + + /* sanity checks * - obviously we've got to have some starting data * - when not in tweakmode, the active Action does not have any scaling applied :) * - when in tweakmode, if the no-mapping flag is set, do not map */ if ((adt == NULL) || (adt->flag & ADT_NLA_EDIT_ON) == 0 || (adt->flag & ADT_NLA_EDIT_NOMAP)) return cframe; - + /* if the active-strip info has been stored already, access this, otherwise look this up * and store for (very probable) future usage */ @@ -546,15 +546,15 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) adt->actstrip = BKE_nlastrip_find_active(adt->act_track); } strip = adt->actstrip; - - /* sanity checks + + /* sanity checks * - in rare cases, we may not be able to find this strip for some reason (internal error) * - for now, if the user has defined a curve to control the time, this correction cannot be performed * reliably... */ if ((strip == NULL) || (strip->flag & NLASTRIP_FLAG_USR_TIME)) return cframe; - + /* perform the correction now... */ return nlastrip_get_frame(strip, cframe, mode); } @@ -569,7 +569,7 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) { NlaStrip *strip; - + /* sanity checks */ if ((strips == NULL) || IS_EQF(start, end)) return false; @@ -577,7 +577,7 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) puts("BKE_nlastrips_has_space() error... start and end arguments swapped"); SWAP(float, start, end); } - + /* loop over NLA strips checking for any overlaps with this area... */ for (strip = strips->first; strip; strip = strip->next) { /* if start frame of strip is past the target end-frame, that means that @@ -585,43 +585,43 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) */ if (strip->start >= end) return true; - + /* if the end of the strip is greater than either of the boundaries, the range * must fall within the extents of the strip */ if ((strip->end > start) || (strip->end > end)) return false; } - + /* if we are still here, we haven't encountered any overlapping strips */ return true; } -/* Rearrange the strips in the track so that they are always in order +/* Rearrange the strips in the track so that they are always in order * (usually only needed after a strip has been moved) */ void BKE_nlastrips_sort_strips(ListBase *strips) { ListBase tmp = {NULL, NULL}; NlaStrip *strip, *sstrip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* we simply perform insertion sort on this list, since it is assumed that per track, * there are only likely to be at most 5-10 strips */ for (strip = strips->first; strip; strip = stripn) { short not_added = 1; - + stripn = strip->next; - - /* remove this strip from the list, and add it to the new list, searching from the end of - * the list, assuming that the lists are in order + + /* remove this strip from the list, and add it to the new list, searching from the end of + * the list, assuming that the lists are in order */ BLI_remlink(strips, strip); - + for (sstrip = tmp.last; sstrip; sstrip = sstrip->prev) { /* check if add after */ if (sstrip->end <= strip->start) { @@ -630,33 +630,33 @@ void BKE_nlastrips_sort_strips(ListBase *strips) break; } } - + /* add before first? */ if (not_added) BLI_addhead(&tmp, strip); } - + /* reassign the start and end points of the strips */ strips->first = tmp.first; strips->last = tmp.last; } -/* Add the given NLA-Strip to the given list of strips, assuming that it +/* Add the given NLA-Strip to the given list of strips, assuming that it * isn't currently a member of another list */ bool BKE_nlastrips_add_strip(ListBase *strips, NlaStrip *strip) { NlaStrip *ns; bool not_added = true; - + /* sanity checks */ if (ELEM(NULL, strips, strip)) return false; - + /* check if any space to add */ if (BKE_nlastrips_has_space(strips, strip->start, strip->end) == 0) return false; - + /* find the right place to add the strip to the nominated track */ for (ns = strips->first; ns; ns = ns->next) { /* if current strip occurs after the new strip, add it before */ @@ -670,7 +670,7 @@ bool BKE_nlastrips_add_strip(ListBase *strips, NlaStrip *strip) /* just add to the end of the list of the strips then... */ BLI_addtail(strips, strip); } - + /* added... */ return true; } @@ -686,15 +686,15 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) { NlaStrip *mstrip = NULL; NlaStrip *strip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* group all continuous chains of selected strips into meta-strips */ for (strip = strips->first; strip; strip = stripn) { stripn = strip->next; - + if (strip->flag & NLASTRIP_FLAG_SELECT) { /* if there is an existing meta-strip, add this strip to it, otherwise, create a new one */ if (mstrip == NULL) { @@ -702,25 +702,25 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) mstrip = MEM_callocN(sizeof(NlaStrip), "Meta-NlaStrip"); mstrip->type = NLASTRIP_TYPE_META; BLI_insertlinkbefore(strips, strip, mstrip); - + /* set flags */ mstrip->flag = NLASTRIP_FLAG_SELECT; - + /* set temp flag if appropriate (i.e. for transform-type editing) */ if (is_temp) mstrip->flag |= NLASTRIP_FLAG_TEMP_META; - + /* set default repeat/scale values to prevent warnings */ mstrip->repeat = mstrip->scale = 1.0f; - + /* make its start frame be set to the start frame of the current strip */ mstrip->start = strip->start; } - + /* remove the selected strips from the track, and add to the meta */ BLI_remlink(strips, strip); BLI_addtail(&mstrip->strips, strip); - + /* expand the meta's dimensions to include the newly added strip- i.e. its last frame */ mstrip->end = strip->end; } @@ -737,11 +737,11 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) { NlaStrip *cs, *csn; - + /* sanity check */ if (ELEM(NULL, strips, strip)) return; - + /* move each one of the meta-strip's children before the meta-strip * in the list of strips after unlinking them from the meta-strip */ @@ -750,7 +750,7 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) BLI_remlink(&strip->strips, cs); BLI_insertlinkbefore(strips, strip, cs); } - + /* free the meta-strip now */ BKE_nlastrip_free(strips, strip); } @@ -762,15 +762,15 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) void BKE_nlastrips_clear_metas(ListBase *strips, bool only_sel, bool only_temp) { NlaStrip *strip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* remove meta-strips fitting the criteria of the arguments */ for (strip = strips->first; strip; strip = stripn) { stripn = strip->next; - + /* check if strip is a meta-strip */ if (strip->type == NLASTRIP_TYPE_META) { /* if check if selection and 'temporary-only' considerations are met */ @@ -791,37 +791,37 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) /* sanity checks */ if (ELEM(NULL, mstrip, strip)) return false; - + /* firstly, check if the meta-strip has space for this */ if (BKE_nlastrips_has_space(&mstrip->strips, strip->start, strip->end) == 0) return false; - + /* check if this would need to be added to the ends of the meta, * and subsequently, if the neighboring strips allow us enough room */ if (strip->start < mstrip->start) { - /* check if strip to the left (if it exists) ends before the - * start of the strip we're trying to add + /* check if strip to the left (if it exists) ends before the + * start of the strip we're trying to add */ if ((mstrip->prev == NULL) || (mstrip->prev->end <= strip->start)) { /* add strip to start of meta's list, and expand dimensions */ BLI_addhead(&mstrip->strips, strip); mstrip->start = strip->start; - + return true; } else /* failed... no room before */ return false; } else if (strip->end > mstrip->end) { - /* check if strip to the right (if it exists) starts before the - * end of the strip we're trying to add + /* check if strip to the right (if it exists) starts before the + * end of the strip we're trying to add */ if ((mstrip->next == NULL) || (mstrip->next->start >= strip->end)) { /* add strip to end of meta's list, and expand dimensions */ BLI_addtail(&mstrip->strips, strip); mstrip->end = strip->end; - + return true; } else /* failed... no room after */ @@ -833,7 +833,7 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) } } -/* Adjust the settings of NLA-Strips contained within a Meta-Strip (recursively), +/* Adjust the settings of NLA-Strips contained within a Meta-Strip (recursively), * until the Meta-Strips children all fit within the Meta-Strip's new dimensions */ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) @@ -842,8 +842,8 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) float oStart, oEnd, offset; float oLen, nLen; short scaleChanged = 0; - - /* sanity checks + + /* sanity checks * - strip must exist * - strip must be a meta-strip with some contents */ @@ -851,37 +851,37 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) return; if (mstrip->type != NLASTRIP_TYPE_META) return; - + /* get the original start/end points, and calculate the start-frame offset - * - these are simply the start/end frames of the child strips, + * - these are simply the start/end frames of the child strips, * since we assume they weren't transformed yet */ oStart = ((NlaStrip *)mstrip->strips.first)->start; oEnd = ((NlaStrip *)mstrip->strips.last)->end; offset = mstrip->start - oStart; - + /* optimization: * don't flush if nothing changed yet * TODO: maybe we need a flag to say always flush? */ if (IS_EQF(oStart, mstrip->start) && IS_EQF(oEnd, mstrip->end)) return; - + /* check if scale changed */ oLen = oEnd - oStart; nLen = mstrip->end - mstrip->start; if (IS_EQF(nLen, oLen) == 0) scaleChanged = 1; - + /* for each child-strip, calculate new start/end points based on this new info */ for (strip = mstrip->strips.first; strip; strip = strip->next) { if (scaleChanged) { float p1, p2; - + /* compute positions of endpoints relative to old extents of strip */ p1 = (strip->start - oStart) / oLen; p2 = (strip->end - oStart) / oLen; - + /* apply new strip endpoints using the proportions, then wait for second pass to flush scale properly */ strip->start = (p1 * nLen) + mstrip->start; strip->end = (p2 * nLen) + mstrip->start; @@ -892,20 +892,20 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) strip->end += offset; } } - + /* apply a second pass over child strips, to finish up unfinished business */ for (strip = mstrip->strips.first; strip; strip = strip->next) { /* only if scale changed, need to perform RNA updates */ if (scaleChanged) { PointerRNA ptr; - + /* use RNA updates to compute scale properly */ RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &ptr); - + RNA_float_set(&ptr, "frame_start", strip->start); RNA_float_set(&ptr, "frame_end", strip->end); } - + /* finally, make sure the strip's children (if it is a meta-itself), get updated */ BKE_nlameta_flush_transforms(strip); } @@ -917,17 +917,17 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) NlaTrack *BKE_nlatrack_find_active(ListBase *tracks) { NlaTrack *nlt; - + /* sanity check */ if (ELEM(NULL, tracks, tracks->first)) return NULL; - + /* try to find the first active track */ for (nlt = tracks->first; nlt; nlt = nlt->next) { if (nlt->flag & NLATRACK_ACTIVE) return nlt; } - + /* none found */ return NULL; } @@ -940,11 +940,11 @@ NlaTrack *BKE_nlatrack_find_active(ListBase *tracks) NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) { NlaTrack *nlt; - + /* sanity check */ if (adt == NULL) return NULL; - + /* Since the track itself gets disabled, we want the first disabled... */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (nlt->flag & (NLATRACK_ACTIVE | NLATRACK_DISABLED)) { @@ -954,13 +954,13 @@ NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) } else if (G.debug & G_DEBUG) { printf("%s: Active strip (%p, %s) not in NLA track found (%p, %s)\n", - __func__, + __func__, adt->actstrip, (adt->actstrip) ? adt->actstrip->name : "", nlt, nlt->name); } } } - + /* Not found! */ return NULL; } @@ -971,22 +971,22 @@ NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) { NlaTrack *nt; - + /* sanity check */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* firstly, make sure 'solo' flag for all tracks is disabled */ for (nt = adt->nla_tracks.first; nt; nt = nt->next) { if (nt != nlt) nt->flag &= ~NLATRACK_SOLO; } - + /* now, enable 'solo' for the given track if appropriate */ if (nlt) { /* toggle solo status */ nlt->flag ^= NLATRACK_SOLO; - + /* set or clear solo-status on AnimData */ if (nlt->flag & NLATRACK_SOLO) adt->flag |= ADT_NLA_SOLO_TRACK; @@ -997,21 +997,21 @@ void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) adt->flag &= ~ADT_NLA_SOLO_TRACK; } -/* Make the given NLA-track the active one for the given stack. If no track is provided, +/* Make the given NLA-track the active one for the given stack. If no track is provided, * this function can be used to simply deactivate all the NLA tracks in the given stack too. */ void BKE_nlatrack_set_active(ListBase *tracks, NlaTrack *nlt_a) { NlaTrack *nlt; - + /* sanity check */ if (ELEM(NULL, tracks, tracks->first)) return; - + /* deactive all the rest */ for (nlt = tracks->first; nlt; nlt = nlt->next) nlt->flag &= ~NLATRACK_ACTIVE; - + /* set the given one as the active one */ if (nlt_a) nlt_a->flag |= NLATRACK_ACTIVE; @@ -1020,24 +1020,24 @@ void BKE_nlatrack_set_active(ListBase *tracks, NlaTrack *nlt_a) /* Check if there is any space in the given track to add a strip of the given length */ bool BKE_nlatrack_has_space(NlaTrack *nlt, float start, float end) { - /* sanity checks + /* sanity checks * - track must exist * - track must be editable * - bounds cannot be equal (0-length is nasty) */ if ((nlt == NULL) || (nlt->flag & NLATRACK_PROTECTED) || IS_EQF(start, end)) return false; - + if (start > end) { puts("BKE_nlatrack_has_space() error... start and end arguments swapped"); SWAP(float, start, end); } - + /* check if there's any space left in the track for a strip of the given length */ return BKE_nlastrips_has_space(&nlt->strips, start, end); } -/* Rearrange the strips in the track so that they are always in order +/* Rearrange the strips in the track so that they are always in order * (usually only needed after a strip has been moved) */ void BKE_nlatrack_sort_strips(NlaTrack *nlt) @@ -1045,12 +1045,12 @@ void BKE_nlatrack_sort_strips(NlaTrack *nlt) /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return; - + /* sort the strips with a more generic function */ BKE_nlastrips_sort_strips(&nlt->strips); } -/* Add the given NLA-Strip to the given NLA-Track, assuming that it +/* Add the given NLA-Strip to the given NLA-Track, assuming that it * isn't currently attached to another one */ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) @@ -1058,11 +1058,11 @@ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) /* sanity checks */ if (ELEM(NULL, nlt, strip)) return false; - + /* do not allow adding strips if this track is locked */ if (nlt->flag & NLATRACK_PROTECTED) return false; - + /* try to add the strip to the track using a more generic function */ return BKE_nlastrips_add_strip(&nlt->strips, strip); } @@ -1073,25 +1073,25 @@ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) bool BKE_nlatrack_get_bounds(NlaTrack *nlt, float bounds[2]) { NlaStrip *strip; - + /* initialize bounds */ if (bounds) bounds[0] = bounds[1] = 0.0f; else return false; - + /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return false; - + /* lower bound is first strip's start frame */ strip = nlt->strips.first; bounds[0] = strip->start; - + /* upper bound is last strip's end frame */ strip = nlt->strips.last; bounds[1] = strip->end; - + /* done */ return true; } @@ -1102,17 +1102,17 @@ bool BKE_nlatrack_get_bounds(NlaTrack *nlt, float bounds[2]) NlaStrip *BKE_nlastrip_find_active(NlaTrack *nlt) { NlaStrip *strip; - + /* sanity check */ if (ELEM(NULL, nlt, nlt->strips.first)) return NULL; - + /* try to find the first active strip */ for (strip = nlt->strips.first; strip; strip = strip->next) { if (strip->flag & NLASTRIP_FLAG_ACTIVE) return strip; } - + /* none found */ return NULL; } @@ -1122,11 +1122,11 @@ void BKE_nlastrip_set_active(AnimData *adt, NlaStrip *strip) { NlaTrack *nlt; NlaStrip *nls; - + /* sanity checks */ if (adt == NULL) return; - + /* loop over tracks, deactivating*/ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (nls = nlt->strips.first; nls; nls = nls->next) { @@ -1144,11 +1144,11 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) { const float stripLen = (strip) ? strip->end - strip->start : 0.0f; const float boundsLen = fabsf(max - min); - + /* sanity checks */ if ((strip == NULL) || IS_EQF(stripLen, 0.0f) || IS_EQF(boundsLen, 0.0f)) return false; - + /* only ok if at least part of the strip is within the bounding window * - first 2 cases cover when the strip length is less than the bounding area * - second 2 cases cover when the strip length is greater than the bounding area @@ -1165,7 +1165,7 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) { return false; } - + /* should be ok! */ return true; } @@ -1178,7 +1178,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) if (strip->next) { NlaStrip *nls = strip->next; float offset = 0.0f; - + if (nls->type == NLASTRIP_TYPE_TRANSITION) { /* transition strips should grow/shrink to accomodate the resized strip, * but if the strip's bounds now exceed the transition, we're forced to @@ -1198,7 +1198,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) */ nls->start = nls->end - 1.0f; offset = ceilf(strip->end - nls->start); /* XXX: review whether preventing fractionals is good here... */ - + /* apply necessary offset to ensure that the strip has enough space */ for (; nls; nls = nls->next) { nls->start += offset; @@ -1211,7 +1211,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) * otherwise it will be very hard to get rid of later */ offset = ceilf(strip->end - nls->start); - + /* apply to times of all strips in this direction */ for (; nls; nls = nls->next) { nls->start += offset; @@ -1219,13 +1219,13 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) } } } - + /* previous strips - same routine as before */ /* NOTE: when strip bounds are recalculated, this is not considered! */ if (strip->prev) { NlaStrip *nls = strip->prev; float offset = 0.0f; - + if (nls->type == NLASTRIP_TYPE_TRANSITION) { /* transition strips should grow/shrink to accomodate the resized strip, * but if the strip's bounds now exceed the transition, we're forced to @@ -1245,7 +1245,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) */ nls->end = nls->start + 1.0f; offset = ceilf(nls->end - strip->start); /* XXX: review whether preventing fractionals is good here... */ - + /* apply necessary offset to ensure that the strip has enough space */ for (; nls; nls = nls->next) { nls->start -= offset; @@ -1258,7 +1258,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) * otherwise it will be very hard to get rid of later */ offset = ceilf(nls->end - strip->start); - + /* apply to times of all strips in this direction */ for (; nls; nls = nls->prev) { nls->start -= offset; @@ -1274,24 +1274,24 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) void BKE_nlastrip_recalculate_bounds(NlaStrip *strip) { float actlen, mapping; - + /* sanity checks * - must have a strip * - can only be done for action clips */ if ((strip == NULL) || (strip->type != NLASTRIP_TYPE_CLIP)) return; - + /* calculate new length factors */ actlen = strip->actend - strip->actstart; if (IS_EQF(actlen, 0.0f)) actlen = 1.0f; - + mapping = strip->scale * strip->repeat; - + /* adjust endpoint of strip in response to this */ if (IS_EQF(mapping, 0.0f) == 0) strip->end = (actlen * mapping) + strip->start; - + /* make sure we don't overlap our neighbors */ nlastrip_fix_resize_overlaps(strip); } @@ -1302,15 +1302,15 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) { NlaTrack *nlt; NlaStrip *ns; - + /* sanity checks */ if (ELEM(NULL, adt, strip)) return false; - + /* check if strip has any strips before it */ if (strip->prev) return false; - + /* check other tracks to see if they have a strip that's earlier */ /* TODO: or should we check that the strip's track is also the first? */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { @@ -1321,7 +1321,7 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) return false; } } - + /* should be first now */ return true; } @@ -1332,17 +1332,17 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) bool BKE_nlatrack_has_animated_strips(NlaTrack *nlt) { NlaStrip *strip; - + /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return false; - + /* check each strip for F-Curves only (don't care about whether the flags are set) */ for (strip = nlt->strips.first; strip; strip = strip->next) { if (strip->fcurves.first) return true; } - + /* none found */ return false; } @@ -1351,17 +1351,17 @@ bool BKE_nlatrack_has_animated_strips(NlaTrack *nlt) bool BKE_nlatracks_have_animated_strips(ListBase *tracks) { NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, tracks, tracks->first)) return false; - + /* check each track, stopping on the first hit */ for (nlt = tracks->first; nlt; nlt = nlt->next) { if (BKE_nlatrack_has_animated_strips(nlt)) return true; } - + /* none found */ return false; } @@ -1370,56 +1370,56 @@ bool BKE_nlatracks_have_animated_strips(ListBase *tracks) void BKE_nlastrip_validate_fcurves(NlaStrip *strip) { FCurve *fcu; - + /* sanity checks */ if (strip == NULL) return; - + /* if controlling influence... */ if (strip->flag & NLASTRIP_FLAG_USR_INFLUENCE) { /* try to get F-Curve */ fcu = list_find_fcurve(&strip->fcurves, "influence", 0); - + /* add one if not found */ if (fcu == NULL) { /* make new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "NlaStrip FCurve"); BLI_addtail(&strip->fcurves, fcu); - + /* set default flags */ fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED); fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL; - + /* store path - make copy, and store that */ fcu->rna_path = BLI_strdupn("influence", 9); - + /* insert keyframe to ensure current value stays on first refresh */ fcu->bezt = MEM_callocN(sizeof(BezTriple), "nlastrip influence bezt"); fcu->totvert = 1; - + fcu->bezt->vec[1][0] = strip->start; fcu->bezt->vec[1][1] = strip->influence; } } - + /* if controlling time... */ if (strip->flag & NLASTRIP_FLAG_USR_TIME) { /* try to get F-Curve */ fcu = list_find_fcurve(&strip->fcurves, "strip_time", 0); - + /* add one if not found */ if (fcu == NULL) { /* make new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "NlaStrip FCurve"); BLI_addtail(&strip->fcurves, fcu); - + /* set default flags */ fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED); fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL; - + /* store path - make copy, and store that */ fcu->rna_path = BLI_strdupn("strip_time", 10); - + /* TODO: insert a few keyframes to ensure default behavior? */ } } @@ -1433,28 +1433,28 @@ bool BKE_nlastrip_has_curves_for_property(const PointerRNA *ptr, const PropertyR /* sanity checks */ if (ELEM(NULL, ptr, prop)) return false; - + /* 1) Must be NLA strip */ if (ptr->type == &RNA_NlaStrip) { /* 2) Must be one of the predefined properties */ - static PropertyRNA *prop_influence = NULL; + static PropertyRNA *prop_influence = NULL; static PropertyRNA *prop_time = NULL; static bool needs_init = true; - + /* Init the properties on first use */ if (needs_init) { prop_influence = RNA_struct_type_find_property(&RNA_NlaStrip, "influence"); prop_time = RNA_struct_type_find_property(&RNA_NlaStrip, "strip_time"); - + needs_init = false; } - + /* Check if match */ if (ELEM(prop, prop_influence, prop_time)) { return true; } } - + /* No criteria met */ return false; } @@ -1466,7 +1466,7 @@ static bool nla_editbone_name_check(void *arg, const char *name) return BLI_ghash_haskey((GHash *)arg, (const void *)name); } -/* Find (and set) a unique name for a strip from the whole AnimData block +/* Find (and set) a unique name for a strip from the whole AnimData block * Uses a similar method to the BLI method, but is implemented differently * as we need to ensure that the name is unique over several lists of tracks, * not just a single track. @@ -1476,11 +1476,11 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) GHash *gh; NlaStrip *tstrip; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, strip)) return; - + /* give strip a default name if none already */ if (strip->name[0] == 0) { switch (strip->type) { @@ -1498,25 +1498,25 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) break; } } - - /* build a hash-table of all the strips in the tracks + + /* build a hash-table of all the strips in the tracks * - this is easier than iterating over all the tracks+strips hierarchy every time * (and probably faster) */ gh = BLI_ghash_str_new("nlastrip_validate_name gh"); - + for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (tstrip = nlt->strips.first; tstrip; tstrip = tstrip->next) { /* don't add the strip of interest */ - if (tstrip == strip) + if (tstrip == strip) continue; - + /* use the name of the strip as the key, and the strip as the value, since we're mostly interested in the keys */ BLI_ghash_insert(gh, tstrip->name, tstrip); } } - - /* if the hash-table has a match for this name, try other names... + + /* if the hash-table has a match for this name, try other names... * - in an extreme case, it might not be able to find a name, but then everything else in Blender would fail too :) */ BLI_uniquename_cb(nla_editbone_name_check, (void *)gh, DATA_("NlaStrip"), '.', strip->name, sizeof(strip->name)); @@ -1527,7 +1527,7 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) /* ---- */ -/* Get strips which overlap the given one at the start/end of its range +/* Get strips which overlap the given one at the start/end of its range * - strip: strip that we're finding overlaps for * - track: nla-track that the overlapping strips should be found from * - start, end: frames for the offending endpoints @@ -1535,9 +1535,9 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, NlaTrack *track, float **start, float **end) { NlaStrip *nls; - + /* find strips that overlap over the start/end of the given strip, - * but which don't cover the entire length + * but which don't cover the entire length */ /* TODO: this scheme could get quite slow for doing this on many strips... */ for (nls = track->strips.first; nls; nls = nls->next) { @@ -1547,13 +1547,13 @@ static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, NlaTrack *track, flo *end = NULL; return; } - + /* check if strip doesn't even occur anywhere near... */ if (nls->end < strip->start) continue; /* skip checking this strip... not worthy of mention */ if (nls->start > strip->end) return; /* the range we're after has already passed */ - + /* if this strip is not part of an island of continuous strips, it can be used * - this check needs to be done for each end of the strip we try and use... */ @@ -1573,7 +1573,7 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) { float *ps = NULL, *pe = NULL; float *ns = NULL, *ne = NULL; - + /* sanity checks */ if (ELEM(NULL, nls, nlt)) return; @@ -1581,16 +1581,16 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) return; if ((nls->flag & NLASTRIP_FLAG_AUTO_BLENDS) == 0) return; - + /* get test ranges */ if (nlt->prev) nlastrip_get_endpoint_overlaps(nls, nlt->prev, &ps, &pe); if (nlt->next) nlastrip_get_endpoint_overlaps(nls, nlt->next, &ns, &ne); - - /* set overlaps for this strip - * - don't use the values obtained though if the end in question - * is directly followed/preceded by another strip, forming an + + /* set overlaps for this strip + * - don't use the values obtained though if the end in question + * is directly followed/preceded by another strip, forming an * 'island' of continuous strips */ if ((ps || ns) && ((nls->prev == NULL) || IS_EQF(nls->prev->end, nls->start) == 0)) { @@ -1602,7 +1602,7 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) } else /* no overlap allowed/needed */ nls->blendin = 0.0f; - + if ((pe || ne) && ((nls->next == NULL) || IS_EQF(nls->next->start, nls->end) == 0)) { /* end overlaps - pick the largest overlap */ if ( ((pe && ne) && (*pe > *ne)) || (pe) ) @@ -1619,33 +1619,33 @@ void BKE_nla_validate_state(AnimData *adt) { NlaStrip *strip, *fstrip = NULL; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* adjust blending values for auto-blending, and also do an initial pass to find the earliest strip */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (strip = nlt->strips.first; strip; strip = strip->next) { /* auto-blending first */ BKE_nlastrip_validate_autoblends(nlt, strip); - + /* extend mode - find first strip */ if ((fstrip == NULL) || (strip->start < fstrip->start)) fstrip = strip; } } - + /* second pass over the strips to adjust the extend-mode to fix any problems */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (strip = nlt->strips.first; strip; strip = strip->next) { - /* apart from 'nothing' option which user has to explicitly choose, we don't really know if + /* apart from 'nothing' option which user has to explicitly choose, we don't really know if * we should be overwriting the extend setting (but assume that's what the user wanted) */ /* TODO: 1 solution is to tie this in with auto-blending... */ if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) { /* 1) First strip must be set to extend hold, otherwise, stuff before acts dodgy - * 2) Only overwrite extend mode if *not* changing it will most probably result in + * 2) Only overwrite extend mode if *not* changing it will most probably result in * occlusion problems, which will occur if... * - blendmode = REPLACE * - all channels the same (this is fiddly to test, so is currently assumed) @@ -1676,7 +1676,7 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) { NlaTrack *nlt; NlaStrip *strip; - + for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (strstr(nlt->name, STASH_TRACK_NAME)) { for (strip = nlt->strips.first; strip; strip = strip->next) { @@ -1685,7 +1685,7 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) } } } - + return false; } @@ -1697,60 +1697,60 @@ bool BKE_nla_action_stash(AnimData *adt) NlaTrack *prev_track = NULL; NlaTrack *nlt; NlaStrip *strip; - + /* sanity check */ if (ELEM(NULL, adt, adt->action)) { printf("%s: Invalid argument - %p %p\n", __func__, adt, adt->action); return false; } - + /* do not add if it is already stashed */ if (BKE_nla_action_is_stashed(adt, adt->action)) return false; - + /* create a new track, and add this immediately above the previous stashing track */ for (prev_track = adt->nla_tracks.last; prev_track; prev_track = prev_track->prev) { if (strstr(prev_track->name, STASH_TRACK_NAME)) { break; } } - + nlt = BKE_nlatrack_add(adt, prev_track); BLI_assert(nlt != NULL); - + /* we need to ensure that if there wasn't any previous instance, it must go to tbe bottom of the stack */ if (prev_track == NULL) { BLI_remlink(&adt->nla_tracks, nlt); BLI_addhead(&adt->nla_tracks, nlt); } - + BLI_strncpy(nlt->name, STASH_TRACK_NAME, sizeof(nlt->name)); BLI_uniquename(&adt->nla_tracks, nlt, STASH_TRACK_NAME, '.', offsetof(NlaTrack, name), sizeof(nlt->name)); - + /* add the action as a strip in this new track * NOTE: a new user is created here */ strip = BKE_nlastrip_new(adt->action); BLI_assert(strip != NULL); - + BKE_nlatrack_add_strip(nlt, strip); BKE_nlastrip_validate_name(adt, strip); - + /* mark the stash track and strip so that they doesn't disturb the stack animation, * and are unlikely to draw attention to itself (or be accidentally bumped around) - * + * * NOTE: this must be done *after* adding the strip to the track, or else * the strip locking will prevent the strip from getting added */ nlt->flag = (NLATRACK_MUTED | NLATRACK_PROTECTED); strip->flag &= ~(NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE); - + /* also mark the strip for auto syncing the length, so that the strips accurately * reflect the length of the action * XXX: we could do with some extra flags here to prevent repeats/scaling options from working! */ strip->flag |= NLASTRIP_FLAG_SYNC_LENGTH; - + /* succeeded */ return true; } @@ -1767,7 +1767,7 @@ void BKE_nla_action_pushdown(AnimData *adt) { NlaStrip *strip; const bool is_first = (adt) && (adt->nla_tracks.first == NULL); - + /* sanity checks */ /* TODO: need to report the error for this */ if (ELEM(NULL, adt, adt->action)) @@ -1781,16 +1781,16 @@ void BKE_nla_action_pushdown(AnimData *adt) printf("BKE_nla_action_pushdown(): action has no data\n"); return; } - + /* add a new NLA strip to the track, which references the active action */ strip = BKE_nlastack_add_strip(adt, adt->action); - + /* do other necessary work on strip */ if (strip) { /* clear reference to action now that we've pushed it onto the stack */ id_us_min(&adt->action->id); adt->action = NULL; - + /* copy current "action blending" settings from adt to the strip, * as it was keyframed with these settings, so omitting them will * change the effect [T54233] @@ -1801,7 +1801,7 @@ void BKE_nla_action_pushdown(AnimData *adt) strip->blendmode = adt->act_blendmode; strip->influence = adt->act_influence; strip->extendmode = adt->act_extendmode; - + if (adt->act_influence < 1.0f) { /* enable "user-controlled" influence (which will insert a default keyframe) * so that the influence doesn't get lost on the new update @@ -1816,7 +1816,7 @@ void BKE_nla_action_pushdown(AnimData *adt) BKE_nlastrip_validate_fcurves(strip); } } - + /* if the strip is the first one in the track it lives in, check if there * are strips in any other tracks that may be before this, and set the extend * mode accordingly @@ -1829,7 +1829,7 @@ void BKE_nla_action_pushdown(AnimData *adt) if (strip->extendmode == NLASTRIP_EXTEND_HOLD) strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD; } - + /* make strip the active one... */ BKE_nlastrip_set_active(adt, strip); } @@ -1842,17 +1842,17 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) { NlaTrack *nlt, *activeTrack = NULL; NlaStrip *strip, *activeStrip = NULL; - + /* verify that data is valid */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return false; - - /* if block is already in tweakmode, just leave, but we should report + + /* if block is already in tweakmode, just leave, but we should report * that this block is in tweakmode (as our returncode) */ if (adt->flag & ADT_NLA_EDIT_ON) return true; - + /* go over the tracks, finding the active one, and its active strip * - if we cannot find both, then there's nothing to do */ @@ -1861,16 +1861,16 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) if (nlt->flag & NLATRACK_ACTIVE) { /* store reference to this active track */ activeTrack = nlt; - + /* now try to find active strip */ activeStrip = BKE_nlastrip_find_active(nlt); break; } } - - /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all - * of those at once. Usually in those cases, it will usually just be a single strip per AnimData. - * In such cases, compromise and take the last selected track and/or last selected strip [#28468] + + /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all + * of those at once. Usually in those cases, it will usually just be a single strip per AnimData. + * In such cases, compromise and take the last selected track and/or last selected strip [#28468] */ if (activeTrack == NULL) { /* try last selected track for active strip */ @@ -1878,7 +1878,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) if (nlt->flag & NLATRACK_SELECTED) { /* assume this is the active track */ activeTrack = nlt; - + /* try to find active strip */ activeStrip = BKE_nlastrip_find_active(nlt); break; @@ -1894,7 +1894,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } } } - + if (ELEM(NULL, activeTrack, activeStrip, activeStrip->act)) { if (G.debug & G_DEBUG) { printf("NLA tweakmode enter - neither active requirement found\n"); @@ -1902,8 +1902,8 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } return false; } - - /* go over all the tracks up to the active one, tagging each strip that uses the same + + /* go over all the tracks up to the active one, tagging each strip that uses the same * action as the active strip, but leaving everything else alone */ for (nlt = activeTrack->prev; nlt; nlt = nlt->prev) { @@ -1914,7 +1914,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } } - + /* tag all other strips in active track that uses the same action as the active strip */ for (strip = activeTrack->strips.first; strip; strip = strip->next) { if ((strip->act == activeStrip->act) && (strip != activeStrip)) @@ -1922,13 +1922,13 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) else strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } - - /* go over all the tracks after AND INCLUDING the active one, tagging them as being disabled + + /* go over all the tracks after AND INCLUDING the active one, tagging them as being disabled * - the active track needs to also be tagged, otherwise, it'll overlap with the tweaks going on */ for (nlt = activeTrack; nlt; nlt = nlt->next) nlt->flag |= NLATRACK_DISABLED; - + /* handle AnimData level changes: * - 'real' active action to temp storage (no need to change user-counts) * - action of active strip set to be the 'active action', and have its usercount incremented @@ -1941,7 +1941,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) adt->actstrip = activeStrip; id_us_plus(&activeStrip->act->id); adt->flag |= ADT_NLA_EDIT_ON; - + /* done! */ return true; } @@ -1951,27 +1951,27 @@ void BKE_nla_tweakmode_exit(AnimData *adt) { NlaStrip *strip; NlaTrack *nlt; - + /* verify that data is valid */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* hopefully the flag is correct - skip if not on */ if ((adt->flag & ADT_NLA_EDIT_ON) == 0) return; - + /* sync the length of the user-strip with the new state of the action * but only if the user has explicitly asked for this to happen * (see [#34645] for things to be careful about) */ if ((adt->actstrip) && (adt->actstrip->flag & NLASTRIP_FLAG_SYNC_LENGTH)) { strip = adt->actstrip; - + /* must be action-clip only (transitions don't have scale) */ if ((strip->type == NLASTRIP_TYPE_CLIP) && (strip->act)) { /* recalculate the length of the action */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + /* adjust the strip extents in response to this */ BKE_nlastrip_recalculate_bounds(strip); } @@ -1982,22 +1982,22 @@ void BKE_nla_tweakmode_exit(AnimData *adt) */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { nlt->flag &= ~NLATRACK_DISABLED; - + for (strip = nlt->strips.first; strip; strip = strip->next) { /* sync strip extents if this strip uses the same action */ if ((adt->actstrip) && (adt->actstrip->act == strip->act) && (strip->flag & NLASTRIP_FLAG_SYNC_LENGTH)) { /* recalculate the length of the action */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + /* adjust the strip extents in response to this */ BKE_nlastrip_recalculate_bounds(strip); } - + /* clear tweakuser flag */ strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } } - + /* handle AnimData level changes: * - 'temporary' active action needs its usercount decreased, since we're removing this reference * - 'real' active action is restored from storage @@ -2019,23 +2019,23 @@ void BKE_nla_tweakmode_exit(AnimData *adt) static void UNUSED_FUNCTION(BKE_nla_bake) (Scene *scene, ID *UNUSED(id), AnimData *adt, int UNUSED(flag)) { - /* verify that data is valid - * 1) Scene and AnimData must be provided + /* verify that data is valid + * 1) Scene and AnimData must be provided * 2) there must be tracks to merge... */ if (ELEM(NULL, scene, adt, adt->nla_tracks.first)) return; - + /* if animdata currently has an action, 'push down' this onto the stack first */ if (adt->action) BKE_nla_action_pushdown(adt); - + /* get range of motion to bake, and the channels involved... */ - + /* temporarily mute the action, and start keying to it */ - + /* start keying... */ - + /* unmute the action */ } diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index 5ac6bc6964d1..bf70ae6060a8 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -92,7 +92,7 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType sockdef = ntype->inputs; while (sockdef->type != -1) { /* sock = */ node_add_socket_from_template(ntree, node, sockdef, SOCK_IN); - + sockdef++; } } @@ -100,7 +100,7 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType sockdef = ntype->outputs; while (sockdef->type != -1) { /* sock = */ node_add_socket_from_template(ntree, node, sockdef, SOCK_OUT); - + sockdef++; } } @@ -115,11 +115,11 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) bNodeType *ntype = node->typeinfo; if (ntype == &NodeTypeUndefined) return; - + /* only do this once */ if (node->flag & NODE_INIT) return; - + node->flag = NODE_SELECT | NODE_OPTIONS | ntype->flag; node->width = ntype->width; node->miniwidth = 42.0f; @@ -134,7 +134,7 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) * than adding "do_translate" flags to this func (and labelfunc() as well). */ BLI_strncpy(node->name, DATA_(ntype->ui_name), NODE_MAXSTR); nodeUniqueName(ntree, node); - + node_add_sockets_from_type(ntree, node, ntype); if (ntype->initfunc != NULL) @@ -147,17 +147,17 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) if (ntype->initfunc_api) { PointerRNA ptr; RNA_pointer_create((ID *)ntree, &RNA_Node, node, &ptr); - + /* XXX Warning: context can be NULL in case nodes are added in do_versions. * Delayed init is not supported for nodes with context-based initfunc_api atm. */ BLI_assert(C != NULL); ntype->initfunc_api(C, &ptr); } - + if (node->id) id_us_plus(node->id); - + node->flag |= NODE_INIT; } @@ -165,13 +165,13 @@ static void ntree_set_typeinfo(bNodeTree *ntree, bNodeTreeType *typeinfo) { if (typeinfo) { ntree->typeinfo = typeinfo; - + /* deprecated integer type */ ntree->type = typeinfo->type; } else { ntree->typeinfo = &NodeTreeTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -183,19 +183,19 @@ static void node_set_typeinfo(const struct bContext *C, bNodeTree *ntree, bNode if (typeinfo && typeinfo->storagename[0] && !node->storage) typeinfo = NULL; } - + if (typeinfo) { node->typeinfo = typeinfo; - + /* deprecated integer type */ node->type = typeinfo->type; - + /* initialize the node if necessary */ node_init(C, ntree, node); } else { node->typeinfo = &NodeTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -204,10 +204,10 @@ static void node_socket_set_typeinfo(bNodeTree *ntree, bNodeSocket *sock, bNodeS { if (typeinfo) { sock->typeinfo = typeinfo; - + /* deprecated integer type */ sock->type = typeinfo->type; - + if (sock->default_value == NULL) { /* initialize the default_value pointer used by standard socket types */ node_socket_init_default_value(sock); @@ -215,7 +215,7 @@ static void node_socket_set_typeinfo(bNodeTree *ntree, bNodeSocket *sock, bNodeS } else { sock->typeinfo = &NodeSocketTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -225,21 +225,21 @@ static void update_typeinfo(Main *bmain, const struct bContext *C, bNodeTreeType { if (!bmain) return; - + FOREACH_NODETREE(bmain, ntree, id) { bNode *node; bNodeSocket *sock; - + ntree->init |= NTREE_TYPE_INIT; - + if (treetype && STREQ(ntree->idname, treetype->idname)) ntree_set_typeinfo(ntree, unregister ? NULL : treetype); - + /* initialize nodes */ for (node = ntree->nodes.first; node; node = node->next) { if (nodetype && STREQ(node->idname, nodetype->idname)) node_set_typeinfo(C, ntree, node, unregister ? NULL : nodetype); - + /* initialize node sockets */ for (sock = node->inputs.first; sock; sock = sock->next) if (socktype && STREQ(sock->idname, socktype->idname)) @@ -248,7 +248,7 @@ static void update_typeinfo(Main *bmain, const struct bContext *C, bNodeTreeType if (socktype && STREQ(sock->idname, socktype->idname)) node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); } - + /* initialize tree sockets */ for (sock = ntree->inputs.first; sock; sock = sock->next) if (socktype && STREQ(sock->idname, socktype->idname)) @@ -269,20 +269,20 @@ void ntreeSetTypes(const struct bContext *C, bNodeTree *ntree) { bNode *node; bNodeSocket *sock; - + ntree->init |= NTREE_TYPE_INIT; - + ntree_set_typeinfo(ntree, ntreeTypeFind(ntree->idname)); - + for (node = ntree->nodes.first; node; node = node->next) { node_set_typeinfo(C, ntree, node, nodeTypeFind(node->idname)); - + for (sock = node->inputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); for (sock = node->outputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); } - + for (sock = ntree->inputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); for (sock = ntree->outputs.first; sock; sock = sock->next) @@ -312,7 +312,9 @@ void ntreeTypeAdd(bNodeTreeType *nt) { BLI_ghash_insert(nodetreetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, nt, NULL, NULL, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, nt, NULL, NULL, false); } /* callback for hash value free function */ @@ -320,7 +322,9 @@ static void ntree_free_type(void *treetype_v) { bNodeTreeType *treetype = treetype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, treetype, NULL, NULL, true); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, treetype, NULL, NULL, true); MEM_freeN(treetype); } @@ -369,12 +373,14 @@ static void node_free_type(void *nodetype_v) { bNodeType *nodetype = nodetype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, NULL, nodetype, NULL, true); - + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, nodetype, NULL, true); + /* XXX deprecated */ if (nodetype->type == NODE_DYNAMIC) free_dynamic_typeinfo(nodetype); - + if (nodetype->needs_free) MEM_freeN(nodetype); } @@ -384,10 +390,12 @@ void nodeRegisterType(bNodeType *nt) /* debug only: basic verification of registered types */ BLI_assert(nt->idname[0] != '\0'); BLI_assert(nt->poll != NULL); - + BLI_ghash_insert(nodetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, NULL, nt, NULL, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, nt, NULL, false); } void nodeUnregisterType(bNodeType *nt) @@ -423,8 +431,10 @@ static void node_free_socket_type(void *socktype_v) { bNodeSocketType *socktype = socktype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, NULL, NULL, socktype, true); - + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, NULL, socktype, true); + MEM_freeN(socktype); } @@ -432,7 +442,9 @@ void nodeRegisterSocketType(bNodeSocketType *st) { BLI_ghash_insert(nodesockettypes_hash, (void *)st->idname, st); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, NULL, NULL, st, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, NULL, st, false); } void nodeUnregisterSocketType(bNodeSocketType *st) @@ -477,7 +489,7 @@ static bNodeSocket *make_socket(bNodeTree *ntree, bNode *UNUSED(node), int in_ou { bNodeSocket *sock; char auto_identifier[MAX_NAME]; - + if (identifier && identifier[0] != '\0') { /* use explicit identifier */ BLI_strncpy(auto_identifier, identifier, sizeof(auto_identifier)); @@ -488,21 +500,21 @@ static bNodeSocket *make_socket(bNodeTree *ntree, bNode *UNUSED(node), int in_ou } /* make the identifier unique */ BLI_uniquename_cb(unique_identifier_check, lb, "socket", '.', auto_identifier, sizeof(auto_identifier)); - + sock = MEM_callocN(sizeof(bNodeSocket), "sock"); sock->in_out = in_out; - + BLI_strncpy(sock->identifier, auto_identifier, NODE_MAXSTR); sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); - + BLI_strncpy(sock->name, name, NODE_MAXSTR); sock->storage = NULL; sock->flag |= SOCK_COLLAPSED; sock->type = SOCK_CUSTOM; /* int type undefined by default */ - + BLI_strncpy(sock->idname, idname, sizeof(sock->idname)); node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(idname)); - + return sock; } @@ -531,12 +543,12 @@ bNodeSocket *nodeAddSocket(bNodeTree *ntree, bNode *node, int in_out, const char { ListBase *lb = (in_out == SOCK_IN ? &node->inputs : &node->outputs); bNodeSocket *sock = make_socket(ntree, node, in_out, lb, idname, identifier, name); - + BLI_remlink(lb, sock); /* does nothing for new socket */ BLI_addtail(lb, sock); - + node->update |= NODE_UPDATE; - + return sock; } @@ -545,12 +557,12 @@ bNodeSocket *nodeInsertSocket(bNodeTree *ntree, bNode *node, int in_out, const c { ListBase *lb = (in_out == SOCK_IN ? &node->inputs : &node->outputs); bNodeSocket *sock = make_socket(ntree, node, in_out, lb, idname, identifier, name); - + BLI_remlink(lb, sock); /* does nothing for new socket */ BLI_insertlinkbefore(lb, next_sock, sock); - + node->update |= NODE_UPDATE; - + return sock; } @@ -681,12 +693,12 @@ bNodeSocket *nodeAddStaticSocket(bNodeTree *ntree, bNode *node, int in_out, int { const char *idname = nodeStaticSocketType(type, subtype); bNodeSocket *sock; - + if (!idname) { printf("Error: static node socket type %d undefined\n", type); return NULL; } - + sock = nodeAddSocket(ntree, node, in_out, idname, identifier, name); sock->type = type; return sock; @@ -697,12 +709,12 @@ bNodeSocket *nodeInsertStaticSocket(bNodeTree *ntree, bNode *node, int in_out, i { const char *idname = nodeStaticSocketType(type, subtype); bNodeSocket *sock; - + if (!idname) { printf("Error: static node socket type %d undefined\n", type); return NULL; } - + sock = nodeInsertSocket(ntree, node, in_out, idname, next_sock, identifier, name); sock->type = type; return sock; @@ -714,7 +726,7 @@ static void node_socket_free(bNodeTree *UNUSED(ntree), bNodeSocket *sock, bNode IDP_FreeProperty(sock->prop); MEM_freeN(sock->prop); } - + if (sock->default_value) MEM_freeN(sock->default_value); } @@ -722,21 +734,21 @@ static void node_socket_free(bNodeTree *UNUSED(ntree), bNodeSocket *sock, bNode void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock) { bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromsock == sock || link->tosock == sock) { nodeRemLink(ntree, link); } } - + /* this is fast, this way we don't need an in_out argument */ BLI_remlink(&node->inputs, sock); BLI_remlink(&node->outputs, sock); - + node_socket_free(ntree, sock, node); MEM_freeN(sock); - + node->update |= NODE_UPDATE; } @@ -744,14 +756,14 @@ void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node) { bNodeSocket *sock, *sock_next; bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromnode == node || link->tonode == node) { nodeRemLink(ntree, link); } } - + for (sock = node->inputs.first; sock; sock = sock_next) { sock_next = sock->next; node_socket_free(ntree, sock, node); @@ -765,7 +777,7 @@ void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node) MEM_freeN(sock); } BLI_listbase_clear(&node->outputs); - + node->update |= NODE_UPDATE; } @@ -782,7 +794,7 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin bNode *node; bNodeSocket *tsock; int index = 0; - + for (node = ntree->nodes.first; node; node = node->next) { tsock = (in_out == SOCK_IN ? node->inputs.first : node->outputs.first); for (index = 0; tsock; tsock = tsock->next, index++) { @@ -798,7 +810,7 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin if (sockindex) *sockindex = index; return 1; } - + *nodep = NULL; return 0; } @@ -890,22 +902,22 @@ void nodeUniqueName(bNodeTree *ntree, bNode *node) bNode *nodeAddNode(const struct bContext *C, bNodeTree *ntree, const char *idname) { bNode *node; - + node = MEM_callocN(sizeof(bNode), "new node"); BLI_addtail(&ntree->nodes, node); - + BLI_strncpy(node->idname, idname, sizeof(node->idname)); node_set_typeinfo(C, ntree, node, nodeTypeFind(idname)); - + ntree->update |= NTREE_UPDATE_NODES; - + return node; } bNode *nodeAddStaticNode(const struct bContext *C, bNodeTree *ntree, int type) { const char *idname = NULL; - + NODE_TYPES_BEGIN(ntype) /* do an extra poll here, because some int types are used * for multiple node types, this helps find the desired type @@ -1022,11 +1034,11 @@ bNode *nodeCopyNode(bNodeTree *ntree, bNode *node) bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, bNode *tonode, bNodeSocket *tosock) { bNodeLink *link = NULL; - + /* test valid input */ BLI_assert(fromnode); BLI_assert(tonode); - + if (fromsock->in_out == SOCK_OUT && tosock->in_out == SOCK_IN) { link = MEM_callocN(sizeof(bNodeLink), "link"); if (ntree) @@ -1046,10 +1058,10 @@ bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, link->tonode = fromnode; link->tosock = fromsock; } - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; - + return link; } @@ -1062,7 +1074,7 @@ void nodeRemLink(bNodeTree *ntree, bNodeLink *link) if (link->tosock) link->tosock->link = NULL; MEM_freeN(link); - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; } @@ -1070,14 +1082,14 @@ void nodeRemLink(bNodeTree *ntree, bNodeLink *link) void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock) { bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromsock == sock || link->tosock == sock) { nodeRemLink(ntree, link); } } - + ntree->update |= NTREE_UPDATE_LINKS; } @@ -1089,15 +1101,15 @@ bool nodeLinkIsHidden(bNodeLink *link) void nodeInternalRelink(bNodeTree *ntree, bNode *node) { bNodeLink *link, *link_next; - + /* store link pointers in output sockets, for efficient lookup */ for (link = node->internal_links.first; link; link = link->next) link->tosock->link = link; - + /* redirect downstream links */ for (link = ntree->links.first; link; link = link_next) { link_next = link->next; - + /* do we have internal link? */ if (link->fromnode == node) { if (link->fromsock->link) { @@ -1107,13 +1119,13 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) if (fromlink) { link->fromnode = fromlink->fromnode; link->fromsock = fromlink->fromsock; - + /* if the up- or downstream link is invalid, * the replacement link will be invalid too. */ if (!(fromlink->flag & NODE_LINK_VALID)) link->flag &= ~NODE_LINK_VALID; - + ntree->update |= NTREE_UPDATE_LINKS; } else @@ -1123,11 +1135,11 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) nodeRemLink(ntree, link); } } - + /* remove remaining upstream links */ for (link = ntree->links.first; link; link = link_next) { link_next = link->next; - + if (link->tonode == node) nodeRemLink(ntree, link); } @@ -1177,7 +1189,7 @@ void nodeAttachNode(bNode *node, bNode *parent) BLI_assert(nodeAttachNodeCheck(parent, node) == false); nodeToView(node, 0.0f, 0.0f, &locx, &locy); - + node->parent = parent; /* transform to parent space */ nodeFromView(parent, locx, locy, &node->locx, &node->locy); @@ -1186,7 +1198,7 @@ void nodeAttachNode(bNode *node, bNode *parent) void nodeDetachNode(struct bNode *node) { float locx, locy; - + if (node->parent) { BLI_assert(node->parent->type == NODE_FRAME); @@ -1207,7 +1219,7 @@ void ntreeInitDefault(bNodeTree *ntree) bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) { bNodeTree *ntree; - + /* trees are created as local trees for compositor, material or texture nodes, * node groups and other tree types are created as library data. */ @@ -1219,15 +1231,15 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) *( (short *)ntree->id.name ) = ID_NT; BLI_strncpy(ntree->id.name + 2, name, sizeof(ntree->id.name)); } - + /* Types are fully initialized at this point, * if an undefined node is added later this will be reset. */ ntree->init |= NTREE_TYPE_INIT; - + BLI_strncpy(ntree->idname, idname, sizeof(ntree->idname)); ntree_set_typeinfo(ntree, ntreeTypeFind(idname)); - + return ntree; } @@ -1358,7 +1370,7 @@ int BKE_node_preview_used(bNode *node) bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstanceKey key, int xsize, int ysize, bool create) { bNodePreview *preview; - + preview = BKE_node_instance_hash_lookup(previews, key); if (!preview) { if (create) { @@ -1368,11 +1380,11 @@ bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstance else return NULL; } - + /* node previews can get added with variable size this way */ if (xsize == 0 || ysize == 0) return preview; - + /* sanity checks & initialize */ if (preview->rect) { if (preview->xsize != xsize || preview->ysize != ysize) { @@ -1380,14 +1392,14 @@ bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstance preview->rect = NULL; } } - + if (preview->rect == NULL) { preview->rect = MEM_callocN(4 * xsize + xsize * ysize * sizeof(char) * 4, "node preview rect"); preview->xsize = xsize; preview->ysize = ysize; } /* no clear, makes nicer previews */ - + return preview; } @@ -1411,14 +1423,14 @@ static void node_preview_init_tree_recursive(bNodeInstanceHash *previews, bNodeT bNode *node; for (node = ntree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, ntree, node); - + if (BKE_node_preview_used(node)) { node->preview_xsize = xsize; node->preview_ysize = ysize; - + BKE_node_preview_verify(previews, key, xsize, ysize, create); } - + if (node->type == NODE_GROUP && node->id) node_preview_init_tree_recursive(previews, (bNodeTree *)node->id, key, xsize, ysize, create); } @@ -1428,10 +1440,10 @@ void BKE_node_preview_init_tree(bNodeTree *ntree, int xsize, int ysize, int crea { if (!ntree) return; - + if (!ntree->previews) ntree->previews = BKE_node_instance_hash_new("node previews"); - + node_preview_init_tree_recursive(ntree->previews, ntree, NODE_INSTANCE_KEY_BASE, xsize, ysize, create_previews); } @@ -1440,10 +1452,10 @@ static void node_preview_tag_used_recursive(bNodeInstanceHash *previews, bNodeTr bNode *node; for (node = ntree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, ntree, node); - + if (BKE_node_preview_used(node)) BKE_node_instance_hash_tag_key(previews, key); - + if (node->type == NODE_GROUP && node->id) node_preview_tag_used_recursive(previews, (bNodeTree *)node->id, key); } @@ -1453,11 +1465,11 @@ void BKE_node_preview_remove_unused(bNodeTree *ntree) { if (!ntree || !ntree->previews) return; - + /* use the instance hash functions for tagging and removing unused previews */ BKE_node_instance_hash_clear_tags(ntree->previews); node_preview_tag_used_recursive(ntree->previews, ntree, NODE_INSTANCE_KEY_BASE); - + BKE_node_instance_hash_remove_untagged(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); } @@ -1465,7 +1477,7 @@ void BKE_node_preview_free_tree(bNodeTree *ntree) { if (!ntree) return; - + if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); ntree->previews = NULL; @@ -1481,10 +1493,10 @@ void BKE_node_preview_clear(bNodePreview *preview) void BKE_node_preview_clear_tree(bNodeTree *ntree) { bNodeInstanceHashIterator iter; - + if (!ntree || !ntree->previews) return; - + NODE_INSTANCE_HASH_ITER(iter, ntree->previews) { bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); BKE_node_preview_clear(preview); @@ -1495,7 +1507,7 @@ static void node_preview_sync(bNodePreview *to, bNodePreview *from) { /* sizes should have been initialized by BKE_node_preview_init_tree */ BLI_assert(to->xsize == from->xsize && to->ysize == from->ysize); - + /* copy over contents of previews */ if (to->rect && from->rect) { int xsize = to->xsize; @@ -1509,15 +1521,15 @@ void BKE_node_preview_sync_tree(bNodeTree *to_ntree, bNodeTree *from_ntree) bNodeInstanceHash *from_previews = from_ntree->previews; bNodeInstanceHash *to_previews = to_ntree->previews; bNodeInstanceHashIterator iter; - + if (!from_previews || !to_previews) return; - + NODE_INSTANCE_HASH_ITER(iter, from_previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *from = BKE_node_instance_hash_iterator_get_value(&iter); bNodePreview *to = BKE_node_instance_hash_lookup(to_previews, key); - + if (from && to) node_preview_sync(to, from); } @@ -1529,27 +1541,27 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo /* free old previews */ if (to_ntree->previews) BKE_node_instance_hash_free(to_ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); - + /* transfer previews */ to_ntree->previews = from_ntree->previews; from_ntree->previews = NULL; - + /* clean up, in case any to_ntree nodes have been removed */ BKE_node_preview_remove_unused(to_ntree); } else { bNodeInstanceHashIterator iter; - + if (from_ntree->previews) { NODE_INSTANCE_HASH_ITER(iter, from_ntree->previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); - + /* replace existing previews */ BKE_node_instance_hash_remove(to_ntree->previews, key, (bNodeInstanceValueFP)BKE_node_preview_free); BKE_node_instance_hash_insert(to_ntree->previews, key, preview); } - + /* Note: NULL free function here, because pointers have already been moved over to to_ntree->previews! */ BKE_node_instance_hash_free(from_ntree->previews, NULL); from_ntree->previews = NULL; @@ -1557,7 +1569,7 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo } } -/* hack warning! this function is only used for shader previews, and +/* hack warning! this function is only used for shader previews, and * since it gets called multiple times per pixel for Ztransp we only * add the color once. Preview gets cleared before it starts render though */ void BKE_node_preview_set_pixel(bNodePreview *preview, const float col[4], int x, int y, bool do_manage) @@ -1566,7 +1578,7 @@ void BKE_node_preview_set_pixel(bNodePreview *preview, const float col[4], int x if (x >= 0 && y >= 0) { if (x < preview->xsize && y < preview->ysize) { unsigned char *tar = preview->rect + 4 * ((preview->xsize * y) + x); - + if (do_manage) { linearrgb_to_srgb_uchar4(tar, col); } @@ -1591,10 +1603,10 @@ static void nodeClearPreview(bNode *node) void ntreeClearPreview(bNodeTree *ntree) { bNode *node; - + if (ntree == NULL) return; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->typeinfo->flag & NODE_PREVIEW) nodeClearPreview(node); @@ -1603,7 +1615,7 @@ void ntreeClearPreview(bNodeTree *ntree) } } -/* hack warning! this function is only used for shader previews, and +/* hack warning! this function is only used for shader previews, and * since it gets called multiple times per pixel for Ztransp we only * add the color once. Preview gets cleared before it starts render though */ void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_manage) @@ -1613,7 +1625,7 @@ void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_mana if (x >= 0 && y >= 0) { if (x < preview->xsize && y < preview->ysize) { unsigned char *tar = preview->rect + 4 * ((preview->xsize * y) + x); - + if (do_manage) { linearrgb_to_srgb_uchar4(tar, col); } @@ -1636,10 +1648,10 @@ void nodeUnlinkNode(bNodeTree *ntree, bNode *node) bNodeLink *link, *next; bNodeSocket *sock; ListBase *lb; - + for (link = ntree->links.first; link; link = next) { next = link->next; - + if (link->fromnode == node) { lb = &node->outputs; if (link->tonode) @@ -1675,30 +1687,30 @@ static void node_unlink_attached(bNodeTree *ntree, bNode *parent) static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdata, bool use_api_free_cb) { bNodeSocket *sock, *nextsock; - + /* don't remove node animdata if the tree is localized, * Action is shared with the original tree (T38221) */ remove_animdata &= ntree && !(ntree->flag & NTREE_IS_LOCALIZED); - + /* extra free callback */ if (use_api_free_cb && node->typeinfo->freefunc_api) { PointerRNA ptr; RNA_pointer_create((ID *)ntree, &RNA_Node, node, &ptr); - + node->typeinfo->freefunc_api(&ptr); } - + /* since it is called while free database, node->id is undefined */ - + /* can be called for nodes outside a node tree (e.g. clipboard) */ if (ntree) { /* remove all references to this node */ nodeUnlinkNode(ntree, node); node_unlink_attached(ntree, node); - + BLI_remlink(&ntree->nodes, node); - + if (remove_animdata) { char propname_esc[MAX_IDPROP_NAME * 2]; char prefix[MAX_IDPROP_NAME * 2]; @@ -1711,7 +1723,7 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat if (ntree->typeinfo->free_node_cache) ntree->typeinfo->free_node_cache(ntree, node); - + /* texture node has bad habit of keeping exec data around */ if (ntree->type == NTREE_TEXTURE && ntree->execdata) { ntreeTexEndExecTree(ntree->execdata); @@ -1742,7 +1754,7 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat } MEM_freeN(node); - + if (ntree) ntree->update |= NTREE_UPDATE_NODES; } @@ -1758,7 +1770,7 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), bNodeSocket *so IDP_FreeProperty(sock->prop); MEM_freeN(sock->prop); } - + if (sock->default_value) MEM_freeN(sock->default_value); } @@ -1766,7 +1778,7 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), bNodeSocket *so static void free_localized_node_groups(bNodeTree *ntree) { bNode *node; - + /* Only localized node trees store a copy for each node group tree. * Each node group tree in a localized node tree can be freed, * since it is a localized copy itself (no risk of accessing free'd @@ -1774,7 +1786,7 @@ static void free_localized_node_groups(bNodeTree *ntree) */ if (!(ntree->flag & NTREE_IS_LOCALIZED)) return; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->type == NODE_GROUP && node->id) { bNodeTree *ngroup = (bNodeTree *)node->id; @@ -1787,7 +1799,6 @@ static void free_localized_node_groups(bNodeTree *ntree) /** Free (or release) any data used by this nodetree (does not free the nodetree itself). */ void ntreeFreeTree(bNodeTree *ntree) { - bNodeTree *tntree; bNode *node, *next; bNodeSocket *sock, *nextsock; @@ -1809,15 +1820,15 @@ void ntreeFreeTree(bNodeTree *ntree) break; } } - + /* XXX not nice, but needed to free localized node groups properly */ free_localized_node_groups(ntree); - + /* unregister associated RNA types */ ntreeInterfaceTypeFree(ntree); - + BLI_freelistN(&ntree->links); /* do first, then unlink_node goes fast */ - + for (node = ntree->nodes.first; node; node = next) { next = node->next; node_free_node_ex(ntree, node, false, false); @@ -1834,7 +1845,7 @@ void ntreeFreeTree(bNodeTree *ntree) node_socket_interface_free(ntree, sock); MEM_freeN(sock); } - + /* free preview hash */ if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); @@ -1842,12 +1853,9 @@ void ntreeFreeTree(bNodeTree *ntree) if (ntree->duplilock) BLI_mutex_free(ntree->duplilock); - + /* if ntree is not part of library, free the libblock data explicitly */ - for (tntree = G.main->nodetree.first; tntree; tntree = tntree->id.next) - if (tntree == ntree) - break; - if (tntree == NULL) { + if (ntree->id.tag & LIB_TAG_NO_MAIN) { BKE_libblock_free_data(&ntree->id, true); } } @@ -1855,7 +1863,7 @@ void ntreeFreeTree(bNodeTree *ntree) void ntreeFreeCache(bNodeTree *ntree) { if (ntree == NULL) return; - + if (ntree->typeinfo->free_cache) ntree->typeinfo->free_cache(ntree); } @@ -1869,7 +1877,7 @@ void ntreeSetOutput(bNodeTree *ntree) if (node->typeinfo->nclass == NODE_CLASS_OUTPUT) { bNode *tnode; int output = 0; - + /* we need a check for which output node should be tagged like this, below an exception */ if (node->type == CMP_NODE_OUTPUT_FILE) continue; @@ -1877,9 +1885,9 @@ void ntreeSetOutput(bNodeTree *ntree) /* there is more types having output class, each one is checked */ for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { if (tnode->typeinfo->nclass == NODE_CLASS_OUTPUT) { - + if (ntree->type == NTREE_COMPOSIT) { - + /* same type, exception for viewer */ if (tnode->type == node->type || (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) && @@ -1907,12 +1915,12 @@ void ntreeSetOutput(bNodeTree *ntree) if (output == 0) node->flag |= NODE_DO_OUTPUT; } - + /* group node outputs use this flag too */ if (node->type == NODE_GROUP_OUTPUT) { bNode *tnode; int output = 0; - + for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { if (tnode->type == NODE_GROUP_OUTPUT) { if (tnode->flag & NODE_DO_OUTPUT) { @@ -1926,7 +1934,7 @@ void ntreeSetOutput(bNodeTree *ntree) node->flag |= NODE_DO_OUTPUT; } } - + /* here we could recursively set which nodes have to be done, * might be different for editor or for "real" use... */ } @@ -2075,7 +2083,7 @@ void ntreeLocalMerge(Main *bmain, bNodeTree *localtree, bNodeTree *ntree) if (ntree && localtree) { if (ntree->typeinfo->local_merge) ntree->typeinfo->local_merge(bmain, localtree, ntree); - + ntreeFreeTree(localtree); MEM_freeN(localtree); } @@ -2100,7 +2108,7 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, int in_out, node_socket_set_typeinfo(ntree, sock, stype); sock->in_out = in_out; sock->type = SOCK_CUSTOM; /* int type undefined by default */ - + /* assign new unique index */ own_index = ntree->cur_index++; /* use the own_index as socket identifier */ @@ -2127,13 +2135,13 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, int in_out, #endif #endif /* USE_NODE_COMPAT_CUSTOMNODES */ - + sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); - + BLI_strncpy(sock->name, name, NODE_MAXSTR); sock->storage = NULL; sock->flag |= SOCK_COLLAPSED; - + return sock; } @@ -2149,7 +2157,7 @@ bNodeSocket *ntreeFindSocketInterface(bNodeTree *ntree, int in_out, const char * bNodeSocket *ntreeAddSocketInterface(bNodeTree *ntree, int in_out, const char *idname, const char *name) { bNodeSocket *iosock; - + iosock = make_socket_interface(ntree, in_out, idname, name); if (in_out == SOCK_IN) { BLI_addtail(&ntree->inputs, iosock); @@ -2159,7 +2167,7 @@ bNodeSocket *ntreeAddSocketInterface(bNodeTree *ntree, int in_out, const char *i BLI_addtail(&ntree->outputs, iosock); ntree->update |= NTREE_UPDATE_GROUP_OUT; } - + return iosock; } @@ -2167,7 +2175,7 @@ bNodeSocket *ntreeInsertSocketInterface(bNodeTree *ntree, int in_out, const char bNodeSocket *next_sock, const char *name) { bNodeSocket *iosock; - + iosock = make_socket_interface(ntree, in_out, idname, name); if (in_out == SOCK_IN) { BLI_insertlinkbefore(&ntree->inputs, next_sock, iosock); @@ -2177,7 +2185,7 @@ bNodeSocket *ntreeInsertSocketInterface(bNodeTree *ntree, int in_out, const char BLI_insertlinkbefore(&ntree->outputs, next_sock, iosock); ntree->update |= NTREE_UPDATE_GROUP_OUT; } - + return iosock; } @@ -2206,10 +2214,10 @@ void ntreeRemoveSocketInterface(bNodeTree *ntree, bNodeSocket *sock) /* this is fast, this way we don't need an in_out argument */ BLI_remlink(&ntree->inputs, sock); BLI_remlink(&ntree->outputs, sock); - + node_socket_interface_free(ntree, sock); MEM_freeN(sock); - + ntree->update |= NTREE_UPDATE_GROUP; } @@ -2236,7 +2244,7 @@ static void ntree_interface_identifier(bNodeTree *ntree, const char *base, char */ identifier[0] = '\0'; BLI_uniquename_cb(ntree_interface_unique_identifier_check, NULL, base, '_', identifier, maxlen); - + sprintf(name, "Node Tree %s Interface", ntree->id.name + 2); sprintf(description, "Interface properties of node group %s", ntree->id.name + 2); } @@ -2247,20 +2255,20 @@ static void ntree_interface_type_create(bNodeTree *ntree) bNodeSocket *sock; /* strings are generated from base string + ID name, sizes are sufficient */ char base[MAX_ID_NAME + 64], identifier[MAX_ID_NAME + 64], name[MAX_ID_NAME + 64], description[MAX_ID_NAME + 64]; - + /* generate a valid RNA identifier */ ntree_interface_identifier_base(ntree, base); ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description); - + /* register a subtype of PropertyGroup */ srna = RNA_def_struct_ptr(&BLENDER_RNA, identifier, &RNA_PropertyGroup); RNA_def_struct_ui_text(srna, name, description); RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna); - + /* associate the RNA type with the node tree */ ntree->interface_type = srna; RNA_struct_blender_type_set(srna, ntree); - + /* add socket properties */ for (sock = ntree->inputs.first; sock; sock = sock->next) { bNodeSocketType *stype = sock->typeinfo; @@ -2279,20 +2287,20 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) if (ntree->interface_type) { /* strings are generated from base string + ID name, sizes are sufficient */ char base[MAX_ID_NAME + 64], identifier[MAX_ID_NAME + 64], name[MAX_ID_NAME + 64], description[MAX_ID_NAME + 64]; - + /* A bit of a hack: when changing the ID name, update the RNA type identifier too, * so that the names match. This is not strictly necessary to keep it working, * but better for identifying associated NodeTree blocks and RNA types. */ StructRNA *srna = ntree->interface_type; - + ntree_interface_identifier_base(ntree, base); - + /* RNA identifier may have a number suffix, but should start with the idbase string */ if (!STREQLEN(RNA_struct_identifier(srna), base, sizeof(base))) { /* generate new unique RNA identifier from the ID name */ ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description); - + /* rename the RNA type */ RNA_def_struct_free_pointers(&BLENDER_RNA, srna); RNA_def_struct_identifier(&BLENDER_RNA, srna, identifier); @@ -2303,7 +2311,7 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) else if (create) { ntree_interface_type_create(ntree); } - + return ntree->interface_type; } @@ -2364,7 +2372,7 @@ bool ntreeHasTree(const bNodeTree *ntree, const bNodeTree *lookup) bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to) { bNodeLink *link; - + for (link = ntree->links.first; link; link = link->next) { if (link->fromsock == from && link->tosock == to) return link; @@ -2378,7 +2386,7 @@ int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock) { bNodeLink *link; int tot = 0; - + for (link = ntree->links.first; link; link = link->next) { if (link->fromsock == sock || link->tosock == sock) tot++; @@ -2389,9 +2397,9 @@ int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock) bNode *nodeGetActive(bNodeTree *ntree) { bNode *node; - + if (ntree == NULL) return NULL; - + for (node = ntree->nodes.first; node; node = node->next) if (node->flag & NODE_ACTIVE) break; @@ -2422,7 +2430,7 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, bNodeIns } } } - + return NULL; } @@ -2471,9 +2479,9 @@ bool nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id) void nodeClearActiveID(bNodeTree *ntree, short idtype) { bNode *node; - + if (ntree == NULL) return; - + for (node = ntree->nodes.first; node; node = node->next) if (node->id && GS(node->id->name) == idtype) node->flag &= ~NODE_ACTIVE_ID; @@ -2486,9 +2494,9 @@ void nodeSetSelected(bNode *node, bool select) } else { bNodeSocket *sock; - + node->flag &= ~NODE_SELECT; - + /* deselect sockets too */ for (sock = node->inputs.first; sock; sock = sock->next) sock->flag &= ~NODE_SELECT; @@ -2511,11 +2519,11 @@ void nodeClearActive(bNodeTree *ntree) void nodeSetActive(bNodeTree *ntree, bNode *node) { bNode *tnode; - + /* make sure only one node is active, and only one per ID type */ for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { tnode->flag &= ~NODE_ACTIVE; - + if (node->id && tnode->id) { if (GS(node->id->name) == GS(tnode->id->name)) tnode->flag &= ~NODE_ACTIVE_ID; @@ -2523,7 +2531,7 @@ void nodeSetActive(bNodeTree *ntree, bNode *node) if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) tnode->flag &= ~NODE_ACTIVE_TEXTURE; } - + node->flag |= NODE_ACTIVE; if (node->id) node->flag |= NODE_ACTIVE_ID; @@ -2579,13 +2587,13 @@ void BKE_node_clipboard_clear(void) { bNode *node, *node_next; bNodeLink *link, *link_next; - + for (link = node_clipboard.links.first; link; link = link_next) { link_next = link->next; nodeRemLink(NULL, link); } BLI_listbase_clear(&node_clipboard.links); - + for (node = node_clipboard.nodes.first; node; node = node_next) { node_next = node->next; node_free_node_ex(NULL, node, false, false); @@ -2623,7 +2631,8 @@ bool BKE_node_clipboard_validate(void) /* currently only validate the ID */ if (node->id) { - ListBase *lb = which_libbase(G.main, GS(node_info->id_name)); + /* We want to search into current blend file, so using G_MAIN is valid here too. */ + ListBase *lb = which_libbase(G_MAIN, GS(node_info->id_name)); BLI_assert(lb != NULL); if (BLI_findindex(lb, node_info->id) == -1) { @@ -2704,25 +2713,25 @@ const bNodeInstanceKey NODE_INSTANCE_KEY_NONE = {0}; static bNodeInstanceKey node_hash_int_str(bNodeInstanceKey hash, const char *str) { char c; - + while ((c = *str++)) hash.value = ((hash.value << 5) + hash.value) ^ c; /* (hash * 33) ^ c */ - + /* separator '\0' character, to avoid ambiguity from concatenated strings */ hash.value = (hash.value << 5) + hash.value; /* hash * 33 */ - + return hash; } bNodeInstanceKey BKE_node_instance_key(bNodeInstanceKey parent_key, bNodeTree *ntree, bNode *node) { bNodeInstanceKey key; - + key = node_hash_int_str(parent_key, ntree->id.name + 2); - + if (node) key = node_hash_int_str(key, node->name); - + return key; } @@ -2793,10 +2802,10 @@ int BKE_node_instance_hash_size(bNodeInstanceHash *hash) void BKE_node_instance_hash_clear_tags(bNodeInstanceHash *hash) { bNodeInstanceHashIterator iter; - + NODE_INSTANCE_HASH_ITER(iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); - + value->tag = 0; } } @@ -2810,7 +2819,7 @@ void BKE_node_instance_hash_tag(bNodeInstanceHash *UNUSED(hash), void *value) bool BKE_node_instance_hash_tag_key(bNodeInstanceHash *hash, bNodeInstanceKey key) { bNodeInstanceHashEntry *entry = BKE_node_instance_hash_lookup(hash, key); - + if (entry) { entry->tag = 1; return true; @@ -2827,19 +2836,19 @@ void BKE_node_instance_hash_remove_untagged(bNodeInstanceHash *hash, bNodeInstan bNodeInstanceKey *untagged = MEM_mallocN(sizeof(bNodeInstanceKey) * BKE_node_instance_hash_size(hash), "temporary node instance key list"); bNodeInstanceHashIterator iter; int num_untagged, i; - + num_untagged = 0; NODE_INSTANCE_HASH_ITER(iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); - + if (!value->tag) untagged[num_untagged++] = BKE_node_instance_hash_iterator_get_key(&iter); } - + for (i = 0; i < num_untagged; ++i) { BKE_node_instance_hash_remove(hash, untagged[i], valfreefp); } - + MEM_freeN(untagged); } @@ -2852,9 +2861,9 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort bNode *fromnode; bNodeLink *link; int level = 0xFFF; - + node->done = true; - + /* check linked nodes */ for (link = ntree->links.first; link; link = link->next) { if (link->tonode == node) { @@ -2865,7 +2874,7 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort level = fromnode->level - 1; } } - + /* check parent node */ if (node->parent) { if (node->parent->done == 0) @@ -2873,21 +2882,21 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort if (node->parent->level <= level) level = node->parent->level - 1; } - + if (nsort) { **nsort = node; (*nsort)++; } - + return level; } void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, int *totnodes) { bNode *node, **nsort; - + *totnodes = 0; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { node->done = false; @@ -2897,9 +2906,9 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in *deplist = NULL; return; } - + nsort = *deplist = MEM_callocN((*totnodes) * sizeof(bNode *), "sorted node array"); - + /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { @@ -2912,12 +2921,12 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in static void ntree_update_node_level(bNodeTree *ntree) { bNode *node; - + /* first clear tag */ for (node = ntree->nodes.first; node; node = node->next) { node->done = false; } - + /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { @@ -2931,7 +2940,7 @@ void ntreeTagUsedSockets(bNodeTree *ntree) bNode *node; bNodeSocket *sock; bNodeLink *link; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { for (sock = node->inputs.first; sock; sock = sock->next) { @@ -2941,12 +2950,12 @@ void ntreeTagUsedSockets(bNodeTree *ntree) sock->flag &= ~SOCK_IN_USE; } } - + for (link = ntree->links.first; link; link = link->next) { /* link is unused if either side is disabled */ if ((link->fromsock->flag & SOCK_UNAVAIL) || (link->tosock->flag & SOCK_UNAVAIL)) continue; - + link->fromsock->flag |= SOCK_IN_USE; link->tosock->flag |= SOCK_IN_USE; } @@ -2957,7 +2966,7 @@ static void ntree_update_link_pointers(bNodeTree *ntree) bNode *node; bNodeSocket *sock; bNodeLink *link; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { for (sock = node->inputs.first; sock; sock = sock->next) { @@ -2968,14 +2977,14 @@ static void ntree_update_link_pointers(bNodeTree *ntree) for (link = ntree->links.first; link; link = link->next) { link->tosock->link = link; } - + ntreeTagUsedSockets(ntree); } static void ntree_validate_links(bNodeTree *ntree) { bNodeLink *link; - + for (link = ntree->links.first; link; link = link->next) { link->flag |= NODE_LINK_VALID; if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level) @@ -2991,7 +3000,7 @@ void ntreeVerifyNodes(struct Main *main, struct ID *id) { FOREACH_NODETREE(main, ntree, owner_id) { bNode *node; - + for (node = ntree->nodes.first; node; node = node->next) if (node->typeinfo->verifyfunc) node->typeinfo->verifyfunc(ntree, node, id); @@ -3001,31 +3010,31 @@ void ntreeVerifyNodes(struct Main *main, struct ID *id) void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) { bNode *node; - + if (!ntree) return; - + /* avoid reentrant updates, can be caused by RNA update callbacks */ if (ntree->is_updating) return; ntree->is_updating = true; - + if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { /* set the bNodeSocket->link pointers */ ntree_update_link_pointers(ntree); } - + /* update individual nodes */ for (node = ntree->nodes.first; node; node = node->next) { /* node tree update tags override individual node update flags */ if ((node->update & NODE_UPDATE) || (ntree->update & NTREE_UPDATE)) { if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); - + nodeUpdateInternalLinks(ntree, node); } } - + /* generic tree update callback */ if (ntree->typeinfo->update) ntree->typeinfo->update(ntree); @@ -3034,28 +3043,28 @@ void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) */ if (ntree->update & NTREE_UPDATE_GROUP) ntreeInterfaceTypeUpdate(ntree); - + /* XXX hack, should be done by depsgraph!! */ if (bmain) ntreeVerifyNodes(bmain, &ntree->id); - + if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { /* node updates can change sockets or links, repeat link pointer update afterward */ ntree_update_link_pointers(ntree); - + /* update the node level from link dependencies */ ntree_update_node_level(ntree); - + /* check link validity */ ntree_validate_links(ntree); } - + /* clear update flags */ for (node = ntree->nodes.first; node; node = node->next) { node->update = 0; } ntree->update = 0; - + ntree->is_updating = false; } @@ -3065,15 +3074,15 @@ void nodeUpdate(bNodeTree *ntree, bNode *node) if (ntree->is_updating) return; ntree->is_updating = true; - + if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); - + nodeUpdateInternalLinks(ntree, node); - + /* clear update flag */ node->update = 0; - + ntree->is_updating = false; } @@ -3081,15 +3090,15 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) { bNode *node; bool changed = false; - + if (ELEM(NULL, id, ntree)) return changed; - + /* avoid reentrant updates, can be caused by RNA update callbacks */ if (ntree->is_updating) return changed; ntree->is_updating = true; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->id == id) { changed = true; @@ -3100,11 +3109,11 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) node->update = 0; } } - + for (node = ntree->nodes.first; node; node = node->next) { nodeUpdateInternalLinks(ntree, node); } - + ntree->is_updating = false; return changed; } @@ -3112,7 +3121,7 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node) { BLI_freelistN(&node->internal_links); - + if (node->typeinfo && node->typeinfo->update_internal_links) node->typeinfo->update_internal_links(ntree, node); } @@ -3122,7 +3131,7 @@ void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node) void nodeSynchronizeID(bNode *node, bool copy_to_id) { if (node->id == NULL) return; - + if (ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) { bNodeSocket *sock; Material *ma = (Material *)node->id; @@ -3131,7 +3140,7 @@ void nodeSynchronizeID(bNode *node, bool copy_to_id) if (!copy_to_id) check_flags |= SOCK_HIDDEN; - + /* hrmf, case in loop isn't super fast, but we don't edit 100s of material at same time either! */ for (a = 0, sock = node->inputs.first; sock; sock = sock->next, a++) { if (!(sock->flag & check_flags)) { @@ -3223,13 +3232,13 @@ static void node_type_base_defaults(bNodeType *ntype) } /* allow this node for any tree type */ -static int node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *UNUSED(ntree)) +static bool node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *UNUSED(ntree)) { return true; } /* use the basic poll function */ -static int node_poll_instance_default(bNode *node, bNodeTree *ntree) +static bool node_poll_instance_default(bNode *node, bNodeTree *ntree) { return node->typeinfo->poll(node->typeinfo, ntree); } @@ -3250,14 +3259,14 @@ void node_type_base(bNodeType *ntype, int type, const char *name, short nclass, BLI_assert(ntype->ext.srna != NULL); \ RNA_struct_blender_type_set(ntype->ext.srna, ntype); \ break; - + switch (type) { #include "NOD_static_types.h" } - + /* make sure we have a valid type (everything registered) */ BLI_assert(ntype->idname[0] != '\0'); - + ntype->type = type; BLI_strncpy(ntype->ui_name, name, sizeof(ntype->ui_name)); ntype->nclass = nclass; @@ -3284,7 +3293,7 @@ static bool unique_socket_template_identifier_check(void *arg, const char *name) { bNodeSocketTemplate *ntemp; struct {bNodeSocketTemplate *list; bNodeSocketTemplate *ntemp;} *data = arg; - + for (ntemp = data->list; ntemp->type >= 0; ++ntemp) { if (ntemp != data->ntemp) { if (STREQ(ntemp->identifier, name)) { @@ -3292,7 +3301,7 @@ static bool unique_socket_template_identifier_check(void *arg, const char *name) } } } - + return false; } @@ -3308,16 +3317,16 @@ static void unique_socket_template_identifier(bNodeSocketTemplate *list, bNodeSo void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTemplate *inputs, struct bNodeSocketTemplate *outputs) { bNodeSocketTemplate *ntemp; - + ntype->inputs = inputs; ntype->outputs = outputs; - + /* automatically generate unique identifiers */ if (inputs) { /* clear identifier strings (uninitialized memory) */ for (ntemp = inputs; ntemp->type >= 0; ++ntemp) ntemp->identifier[0] = '\0'; - + for (ntemp = inputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); unique_socket_template_identifier(inputs, ntemp, ntemp->identifier, '_'); @@ -3327,7 +3336,7 @@ void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTempl /* clear identifier strings (uninitialized memory) */ for (ntemp = outputs; ntemp->type >= 0; ++ntemp) ntemp->identifier[0] = '\0'; - + for (ntemp = outputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); unique_socket_template_identifier(outputs, ntemp, ntemp->identifier, '_'); @@ -3422,7 +3431,7 @@ void node_type_compatibility(struct bNodeType *ntype, short compatibility) /* callbacks for undefined types */ -static int node_undefined_poll(bNodeType *UNUSED(ntype), bNodeTree *UNUSED(nodetree)) +static bool node_undefined_poll(bNodeType *UNUSED(ntype), bNodeTree *UNUSED(nodetree)) { /* this type can not be added deliberately, it's just a placeholder */ return false; @@ -3434,14 +3443,14 @@ static void register_undefined_types(void) /* Note: these types are not registered in the type hashes, * they are just used as placeholders in case the actual types are not registered. */ - + strcpy(NodeTreeTypeUndefined.idname, "NodeTreeUndefined"); strcpy(NodeTreeTypeUndefined.ui_name, "Undefined"); strcpy(NodeTreeTypeUndefined.ui_description, "Undefined Node Tree Type"); - + node_type_base_custom(&NodeTypeUndefined, "NodeUndefined", "Undefined", 0, 0); NodeTypeUndefined.poll = node_undefined_poll; - + BLI_strncpy(NodeSocketTypeUndefined.idname, "NodeSocketUndefined", sizeof(NodeSocketTypeUndefined.idname)); /* extra type info for standard socket types */ NodeSocketTypeUndefined.type = SOCK_CUSTOM; @@ -3451,7 +3460,7 @@ static void register_undefined_types(void) static void registerCompositNodes(void) { register_node_type_cmp_group(); - + register_node_type_cmp_rlayers(); register_node_type_cmp_image(); register_node_type_cmp_texture(); @@ -3459,13 +3468,13 @@ static void registerCompositNodes(void) register_node_type_cmp_rgb(); register_node_type_cmp_curve_time(); register_node_type_cmp_movieclip(); - + register_node_type_cmp_composite(); register_node_type_cmp_viewer(); register_node_type_cmp_splitviewer(); register_node_type_cmp_output_file(); register_node_type_cmp_view_levels(); - + register_node_type_cmp_curve_rgb(); register_node_type_cmp_mix_rgb(); register_node_type_cmp_hue_sat(); @@ -3476,13 +3485,13 @@ static void registerCompositNodes(void) register_node_type_cmp_zcombine(); register_node_type_cmp_colorbalance(); register_node_type_cmp_huecorrect(); - + register_node_type_cmp_normal(); register_node_type_cmp_curve_vec(); register_node_type_cmp_map_value(); register_node_type_cmp_map_range(); register_node_type_cmp_normalize(); - + register_node_type_cmp_filter(); register_node_type_cmp_blur(); register_node_type_cmp_dblur(); @@ -3493,7 +3502,7 @@ static void registerCompositNodes(void) register_node_type_cmp_despeckle(); register_node_type_cmp_defocus(); register_node_type_cmp_sunbeams(); - + register_node_type_cmp_valtorgb(); register_node_type_cmp_rgbtobw(); register_node_type_cmp_setalpha(); @@ -3508,7 +3517,7 @@ static void registerCompositNodes(void) register_node_type_cmp_sepycca(); register_node_type_cmp_combycca(); register_node_type_cmp_premulkey(); - + register_node_type_cmp_diff_matte(); register_node_type_cmp_distance_matte(); register_node_type_cmp_chroma_matte(); @@ -3519,6 +3528,7 @@ static void registerCompositNodes(void) register_node_type_cmp_doubleedgemask(); register_node_type_cmp_keyingscreen(); register_node_type_cmp_keying(); + register_node_type_cmp_cryptomatte(); register_node_type_cmp_translate(); register_node_type_cmp_rotate(); @@ -3549,7 +3559,7 @@ static void registerCompositNodes(void) register_node_type_cmp_cornerpin(); } -static void registerShaderNodes(void) +static void registerShaderNodes(void) { register_node_type_sh_group(); @@ -3615,6 +3625,7 @@ static void registerShaderNodes(void) register_node_type_sh_bsdf_velvet(); register_node_type_sh_bsdf_toon(); register_node_type_sh_bsdf_hair(); + register_node_type_sh_bsdf_hair_principled(); register_node_type_sh_emission(); register_node_type_sh_holdout(); register_node_type_sh_volume_absorption(); @@ -3650,7 +3661,7 @@ static void registerTextureNodes(void) { register_node_type_tex_group(); - + register_node_type_tex_math(); register_node_type_tex_mix_rgb(); register_node_type_tex_valtorgb(); @@ -3664,26 +3675,26 @@ static void registerTextureNodes(void) register_node_type_tex_distance(); register_node_type_tex_compose(); register_node_type_tex_decompose(); - + register_node_type_tex_output(); register_node_type_tex_viewer(); register_node_type_sh_script(); register_node_type_sh_tangent(); register_node_type_sh_normal_map(); register_node_type_sh_hair_info(); - + register_node_type_tex_checker(); register_node_type_tex_texture(); register_node_type_tex_bricks(); register_node_type_tex_image(); register_node_type_sh_bsdf_refraction(); register_node_type_sh_ambient_occlusion(); - + register_node_type_tex_rotate(); register_node_type_tex_translate(); register_node_type_tex_scale(); register_node_type_tex_at(); - + register_node_type_tex_proc_voronoi(); register_node_type_tex_proc_blend(); register_node_type_tex_proc_magic(); @@ -3696,7 +3707,7 @@ static void registerTextureNodes(void) register_node_type_tex_proc_distnoise(); } -void init_nodesystem(void) +void init_nodesystem(void) { nodetreetypes_hash = BLI_ghash_str_new("nodetreetypes_hash gh"); nodetypes_hash = BLI_ghash_str_new("nodetypes_hash gh"); @@ -3715,13 +3726,13 @@ void init_nodesystem(void) register_node_type_reroute(); register_node_type_group_input(); register_node_type_group_output(); - + registerCompositNodes(); registerShaderNodes(); registerTextureNodes(); } -void free_nodesystem(void) +void free_nodesystem(void) { if (nodetypes_hash) { NODE_TYPES_BEGIN(nt) diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index 7d0e3eadecfd..f5a022dbabb1 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -147,7 +147,7 @@ static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER; void BKE_object_workob_clear(Object *workob) { memset(workob, 0, sizeof(Object)); - + workob->size[0] = workob->size[1] = workob->size[2] = 1.0f; workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f; workob->rotmode = ROT_MODE_EUL; @@ -357,7 +357,7 @@ void BKE_object_free_derived_caches(Object *ob) ob->derivedDeform->release(ob->derivedDeform); ob->derivedDeform = NULL; } - + BKE_object_free_curve_cache(ob); } @@ -434,9 +434,9 @@ void BKE_object_free(Object *ob) free_controllers(&ob->controllers); free_actuators(&ob->actuators); BKE_python_component_free_list(&ob->components); - + BKE_constraints_free_ex(&ob->constraints, false); - + free_partdeflect(ob->pd); BKE_rigidbody_free_object(ob); BKE_rigidbody_free_constraint(ob); @@ -474,7 +474,7 @@ bool BKE_object_is_in_editmode(const Object *ob) { if (ob->data == NULL) return false; - + if (ob->type == OB_MESH) { Mesh *me = ob->data; if (me->edit_btmesh) @@ -482,25 +482,25 @@ bool BKE_object_is_in_editmode(const Object *ob) } else if (ob->type == OB_ARMATURE) { bArmature *arm = ob->data; - + if (arm->edbo) return true; } else if (ob->type == OB_FONT) { Curve *cu = ob->data; - + if (cu->editfont) return true; } else if (ob->type == OB_MBALL) { MetaBall *mb = ob->data; - + if (mb->editelems) return true; } else if (ob->type == OB_LATTICE) { Lattice *lt = ob->data; - + if (lt->editlatt) return true; } @@ -534,9 +534,9 @@ bool BKE_object_is_in_wpaint_select_vert(const Object *ob) bool BKE_object_exists_check(Main *bmain, const Object *obtest) { Object *ob; - + if (obtest == NULL) return false; - + ob = bmain->object.first; while (ob) { if (ob == obtest) return true; @@ -597,12 +597,12 @@ void BKE_object_init(Object *ob) ob->col[0] = ob->col[1] = ob->col[2] = 1.0; ob->col[3] = 1.0; - + ob->size[0] = ob->size[1] = ob->size[2] = 1.0; ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0; - - /* objects should default to having Euler XYZ rotations, - * but rotations default to quaternions + + /* objects should default to having Euler XYZ rotations, + * but rotations default to quaternions */ ob->rotmode = ROT_MODE_EUL; @@ -614,13 +614,16 @@ void BKE_object_init(Object *ob) /* rotation locks should be 4D for 4 component rotations by default... */ ob->protectflag = OB_LOCK_ROT4D; - + unit_m4(ob->constinv); unit_m4(ob->parentinv); unit_m4(ob->obmat); ob->dt = OB_TEXTURE; ob->empty_drawtype = OB_PLAINAXES; ob->empty_drawsize = 1.0; + if (ob->type == OB_EMPTY) { + copy_v2_fl(ob->ima_ofs, -0.5f); + } if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) { ob->trackflag = OB_NEGZ; @@ -630,7 +633,7 @@ void BKE_object_init(Object *ob) ob->trackflag = OB_POSY; ob->upflag = OB_POSZ; } - + ob->dupon = 1; ob->dupoff = 0; ob->dupsta = 1; ob->dupend = 100; ob->dupfacesca = 1.0; @@ -664,7 +667,7 @@ void BKE_object_init(Object *ob) ob->fluidsimSettings = NULL; BLI_listbase_clear(&ob->pc_ids); - + /* Animation Visualization defaults */ animviz_settings_init(&ob->avs); } @@ -701,7 +704,7 @@ Object *BKE_object_add( ob->data = BKE_object_obdata_add_from_type(bmain, type, name); ob->lay = scene->lay; - + base = BKE_scene_base_add(scene, ob); BKE_scene_base_deselect_all(scene); BKE_scene_base_select(scene, base); @@ -727,7 +730,7 @@ void BKE_object_lod_add(Object *ob) base->obhysteresis = 10; last = ob->currentlod = base; } - + lod->distance = last->distance + 25.0f; lod->obhysteresis = 10; lod->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT; @@ -847,9 +850,9 @@ struct Object *BKE_object_lod_matob_get(Object *ob, Scene *scene) SoftBody *copy_softbody(const SoftBody *sb, const int flag) { SoftBody *sbn; - + if (sb == NULL) return(NULL); - + sbn = MEM_dupallocN(sb); if ((flag & LIB_ID_COPY_CACHES) == 0) { @@ -875,10 +878,10 @@ SoftBody *copy_softbody(const SoftBody *sb, const int flag) if (sb->bspring) sbn->bspring = MEM_dupallocN(sb->bspring); } - + sbn->keys = NULL; sbn->totkey = sbn->totpointkey = 0; - + sbn->scratch = NULL; sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, flag); @@ -921,10 +924,10 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int f if (key) key = MEM_dupallocN(key); - + if (boid) boid = MEM_dupallocN(boid); - + for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) { if (boid) pa->boid = boid++; @@ -950,11 +953,11 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int f psysn->effectors = NULL; psysn->tree = NULL; psysn->bvhtree = NULL; - + BLI_listbase_clear(&psysn->pathcachebufs); BLI_listbase_clear(&psysn->childcachebufs); psysn->renderdata = NULL; - + /* XXX Never copy caches here? */ psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag & ~LIB_ID_COPY_CACHES); @@ -1004,7 +1007,7 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const } else if (md->type == eModifierType_Smoke) { SmokeModifierData *smd = (SmokeModifierData *) md; - + if (smd->type == MOD_SMOKE_TYPE_FLOW) { if (smd->flow) { if (smd->flow->psys == psys) @@ -1027,31 +1030,31 @@ void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src) static void copy_object_pose(Object *obn, const Object *ob, const int flag) { bPoseChannel *chan; - + /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */ obn->pose = NULL; BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true); /* true = copy constraints */ for (chan = obn->pose->chanbase.first; chan; chan = chan->next) { bConstraint *con; - + chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE); - + /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but... * the flush_constraint_targets callback am not sure about, so will delay that for now. */ for (con = chan->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar == ob) ct->tar = obn; } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 0); } @@ -1127,14 +1130,20 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->matbits = MEM_dupallocN(ob_src->matbits); ob_dst->totcol = ob_src->totcol; } + else if (ob_dst->mat != NULL || ob_dst->matbits != NULL) { + /* This shall not be needed, but better be safe than sorry. */ + BLI_assert(!"Object copy: non-NULL material pointers with zero counter, should not happen."); + ob_dst->mat = NULL; + ob_dst->matbits = NULL; + } if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser); - + if (ob_src->bb) ob_dst->bb = MEM_dupallocN(ob_src->bb); ob_dst->flag &= ~OB_FROMGROUP; - + BLI_listbase_clear(&ob_dst->modifiers); - + for (md = ob_src->modifiers.first; md; md = md->next) { ModifierData *nmd = modifier_new(md->type); BLI_strncpy(nmd->name, md->name, sizeof(nmd->name)); @@ -1172,7 +1181,7 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata); BKE_object_copy_particlesystems(ob_dst, ob_src, flag_subdata); - + ob_dst->derivedDeform = NULL; ob_dst->derivedFinal = NULL; @@ -1182,7 +1191,7 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->mpath = NULL; copy_object_lod(ob_dst, ob_src, flag_subdata); - + /* Do not copy runtime curve data. */ ob_dst->curve_cache = NULL; @@ -1274,34 +1283,34 @@ static void armature_set_id_extern(Object *ob) bArmature *arm = ob->data; bPoseChannel *pchan; unsigned int lay = arm->layer_protected; - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { if (!(pchan->bone->layer & lay)) id_lib_extern((ID *)pchan->custom); } - + } void BKE_object_copy_proxy_drivers(Object *ob, Object *target) { if ((target->adt) && (target->adt->drivers.first)) { FCurve *fcu; - + /* add new animdata block */ if (!ob->adt) ob->adt = BKE_animdata_add_id(&ob->id); - + /* make a copy of all the drivers (for now), then correct any links that need fixing */ free_fcurves(&ob->adt->drivers); copy_fcurves(&ob->adt->drivers, &target->adt->drivers); - + for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* all drivers */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { if (dtar->id) { if ((Object *)dtar->id == target) @@ -1332,14 +1341,14 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *gob) printf("cannot make proxy\n"); return; } - + ob->proxy = target; ob->proxy_group = gob; id_lib_extern(&target->id); - + DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); DAG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); - + /* copy transform * - gob means this proxy comes from a group, just apply the matrix * so the object wont move from its dupli-transform. @@ -1361,13 +1370,13 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *gob) ob->parent = target->parent; /* libdata */ copy_m4_m4(ob->parentinv, target->parentinv); } - + /* copy animdata stuff - drivers only for now... */ BKE_object_copy_proxy_drivers(ob, target); /* skip constraints? */ /* FIXME: this is considered by many as a bug */ - + /* set object type and link to data */ ob->type = target->type; ob->data = target->data; @@ -1384,24 +1393,24 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *gob) ob->matbits = NULL; if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) { int i; - + ob->actcol = target->actcol; ob->totcol = target->totcol; - + ob->mat = MEM_dupallocN(target->mat); ob->matbits = MEM_dupallocN(target->matbits); for (i = 0; i < target->totcol; i++) { /* don't need to run test_object_materials since we know this object is new and not used elsewhere */ - id_us_plus((ID *)ob->mat[i]); + id_us_plus((ID *)ob->mat[i]); } } - + /* type conversions */ if (target->type == OB_ARMATURE) { copy_object_pose(ob, target, 0); /* data copy, object pointers in constraints */ BKE_pose_rest(ob->pose); /* clear all transforms in channels */ BKE_pose_rebuild(ob, ob->data); /* set all internal links */ - + armature_set_id_extern(ob); } else if (target->type == OB_EMPTY) { @@ -1485,7 +1494,7 @@ void BKE_object_scale_to_mat3(Object *ob, float mat[3][3]) void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) { float rmat[3][3], dmat[3][3]; - + /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied * with the rotation matrix to yield the appropriate rotation */ @@ -1504,14 +1513,14 @@ void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) else { /* quats are normalized before use to eliminate scaling issues */ float tquat[4]; - + normalize_qt_qt(tquat, ob->quat); quat_to_mat3(rmat, tquat); - + normalize_qt_qt(tquat, ob->dquat); quat_to_mat3(dmat, tquat); } - + /* combine these rotations */ if (use_drot) mul_m3_m3m3(mat, dmat, rmat); @@ -1635,7 +1644,7 @@ void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */ float smat[3][3]; float rmat[3][3]; /*float q1[4];*/ - + /* size */ BKE_object_scale_to_mat3(ob, smat); @@ -1647,9 +1656,9 @@ void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */ void BKE_object_to_mat4(Object *ob, float mat[4][4]) { float tmat[3][3]; - + BKE_object_to_mat3(ob, tmat); - + copy_m4_m3(mat, tmat); add_v3_v3v3(mat[3], ob->loc, ob->dloc); @@ -1696,7 +1705,7 @@ static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4]) /* catch exceptions: curve paths used as a duplicator */ if (enable_cu_speed) { /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + * but this will only work if it actually is animated... * * we divide the curvetime calculated in the previous step by the length of the path, to get a time * factor, which then gets clamped to lie within 0.0 - 1.0 range @@ -1720,10 +1729,10 @@ static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4]) if (cu->pathlen) { ctime /= cu->pathlen; } - + CLAMP(ctime, 0.0f, 1.0f); } - + unit_m4(mat); /* vec: 4 items! */ @@ -1733,7 +1742,7 @@ static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4]) #if 0 float si, q[4]; vec_to_quat(quat, dir, ob->trackflag, ob->upflag); - + /* the tilt */ normalize_v3(dir); q[0] = cosf(0.5 * vec[3]); @@ -1748,7 +1757,7 @@ static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4]) normalize_qt(quat); quat_to_mat4(mat, quat); } - + if (cu->flag & CU_PATH_RADIUS) { float tmat[4][4], rmat[4][4]; scale_m4_fl(tmat, radius); @@ -1757,22 +1766,22 @@ static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4]) } copy_v3_v3(mat[3], vec); - + } return true; } static void ob_parbone(Object *ob, Object *par, float mat[4][4]) -{ +{ bPoseChannel *pchan; float vec[3]; - + if (par->type != OB_ARMATURE) { unit_m4(mat); return; } - + /* Make sure the bone is still valid */ pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr); if (!pchan || !pchan->bone) { @@ -1800,14 +1809,14 @@ static void ob_parbone(Object *ob, Object *par, float mat[4][4]) static void give_parvert(Object *par, int nr, float vec[3]) { zero_v3(vec); - + if (par->type == OB_MESH) { Mesh *me = par->data; BMEditMesh *em = me->edit_btmesh; DerivedMesh *dm; dm = (em) ? em->derivedFinal : par->derivedFinal; - + if (dm) { int count = 0; int numVerts = dm->getNumVerts(dm); @@ -1983,16 +1992,16 @@ void BKE_object_get_parent_matrix(Scene *scene, Object *ob, Object *par, float p ok = 1; } } - + if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat); else copy_m4_m4(parentmat, par->obmat); - + break; case PARBONE: ob_parbone(ob, par, tmat); mul_m4_m4m4(parentmat, par->obmat, tmat); break; - + case PARVERT1: unit_m4(parentmat); give_parvert(par, ob->par1, vec); @@ -2000,10 +2009,10 @@ void BKE_object_get_parent_matrix(Scene *scene, Object *ob, Object *par, float p break; case PARVERT3: ob_parvert3(ob, par, tmat); - + mul_m4_m4m4(parentmat, par->obmat, tmat); break; - + case PARSKEL: copy_m4_m4(parentmat, par->obmat); break; @@ -2020,22 +2029,22 @@ static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4 float totmat[4][4]; float tmat[4][4]; float locmat[4][4]; - + BKE_object_to_mat4(ob, locmat); - + if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat); BKE_object_get_parent_matrix(scene, ob, par, totmat); - + /* total */ mul_m4_m4m4(tmat, totmat, ob->parentinv); mul_m4_m4m4(obmat, tmat, locmat); - + if (r_originmat) { /* usable originmat */ copy_m3_m4(r_originmat, tmat); } - + /* origin, for help line */ if (set_origin) { if ((ob->partype & PARTYPE) == PARSKEL) { @@ -2072,18 +2081,18 @@ void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime, RigidBodyWorld *rbw, float r_originmat[3][3]) { if (ob == NULL) return; - + /* execute drivers only, as animation has already been done */ BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS); - + if (ob->parent) { Object *par = ob->parent; float slowmat[4][4]; - + /* calculate parent matrix */ solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, true); - - /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around + + /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around * An old-fashioned hack which probably doesn't really cut it anymore */ if (ob->partype & PARSLOW) { @@ -2099,7 +2108,7 @@ void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime, rbw = rbw ? rbw : scene->rigidbody_world; /* read values pushed into RBO from sim/cache... */ BKE_rigidbody_sync_transforms(rbw, ob, ctime); - + /* solve constraints */ if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) { bConstraintOb *cob; @@ -2107,7 +2116,7 @@ void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime, BKE_constraints_solve(&ob->constraints, cob, ctime); BKE_constraints_clear_evalob(cob); } - + /* set negative scale flag in object */ if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE; else ob->transflag &= ~OB_NEG_SCALE; @@ -2129,9 +2138,9 @@ void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4]) float slowmat[4][4]; Object *par = ob->parent; - + solve_parenting(scene, ob, par, obmat, slowmat, NULL, false); - + if (ob->partype & PARSLOW) where_is_object_parslow(ob, obmat, slowmat); } @@ -2153,7 +2162,7 @@ void BKE_object_where_is_calc(Scene *scene, Object *ob) void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob) { BKE_object_workob_clear(workob); - + unit_m4(workob->obmat); unit_m4(workob->parentinv); unit_m4(workob->constinv); @@ -2161,7 +2170,7 @@ void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob) workob->trackflag = ob->trackflag; workob->upflag = ob->upflag; - + workob->partype = ob->partype; workob->par1 = ob->par1; workob->par2 = ob->par2; @@ -2214,7 +2223,7 @@ BoundBox *BKE_boundbox_alloc_unit(void) bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox"); BKE_boundbox_init_from_minmax(bb, min, max); - + return bb; } @@ -2222,7 +2231,7 @@ void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float { bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0]; bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0]; - + bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1]; bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1]; @@ -2257,7 +2266,7 @@ void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], BoundBox *BKE_object_boundbox_get(Object *ob) { BoundBox *bb = NULL; - + if (ob->type == OB_MESH) { bb = BKE_mesh_boundbox_get(ob); } @@ -2289,13 +2298,13 @@ void BKE_object_boundbox_flag(Object *ob, int flag, const bool set) void BKE_object_dimensions_get(Object *ob, float vec[3]) { BoundBox *bb = NULL; - + bb = BKE_object_boundbox_get(ob); if (bb) { float scale[3]; - + mat4_to_size(scale, ob->obmat); - + vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]); vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]); vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]); @@ -2308,17 +2317,17 @@ void BKE_object_dimensions_get(Object *ob, float vec[3]) void BKE_object_dimensions_set(Object *ob, const float value[3]) { BoundBox *bb = NULL; - + bb = BKE_object_boundbox_get(ob); if (bb) { float scale[3], len[3]; - + mat4_to_size(scale, ob->obmat); - + len[0] = bb->vec[4][0] - bb->vec[0][0]; len[1] = bb->vec[2][1] - bb->vec[0][1]; len[2] = bb->vec[1][2] - bb->vec[0][2]; - + if (len[0] > 0.f) ob->size[0] = value[0] / len[0]; if (len[1] > 0.f) ob->size[1] = value[1] / len[1]; if (len[2] > 0.f) ob->size[2] = value[2] / len[2]; @@ -2330,7 +2339,7 @@ void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool us BoundBox bb; float vec[3]; bool changed = false; - + switch (ob->type) { case OB_CURVE: case OB_FONT: @@ -2676,7 +2685,7 @@ void BKE_object_handle_update_ex(Main *bmain, object_handle_update_proxy(bmain, eval_ctx, scene, ob, do_proxy_update); } -/* WARNING: "scene" here may not be the scene object actually resides in. +/* WARNING: "scene" here may not be the scene object actually resides in. * When dealing with background-sets, "scene" is actually the active scene. * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world @@ -2721,10 +2730,10 @@ void BKE_object_sculpt_modifiers_changed(Object *ob) int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot) { - + if (ob->data == NULL) return 0; - + switch (GS(((ID *)ob->data)->name)) { case ID_ME: { @@ -2773,7 +2782,7 @@ static int pc_cmp(const void *a, const void *b) else return 0; } -int BKE_object_insert_ptcache(Object *ob) +int BKE_object_insert_ptcache(Object *ob) { LinkData *link = NULL; int i = 0; @@ -2798,18 +2807,18 @@ static int pc_findindex(ListBase *listbase, int index) { LinkData *link = NULL; int number = 0; - + if (listbase == NULL) return -1; - + link = listbase->first; while (link) { if (GET_INT_FROM_POINTER(link->data) == index) return number; - + number++; link = link->next; } - + return -1; } @@ -2934,7 +2943,7 @@ static KeyBlock *insert_curvekey(Main *bmain, Object *ob, const char *name, cons } KeyBlock *BKE_object_shapekey_insert(Main *bmain, Object *ob, const char *name, const bool from_mix) -{ +{ switch (ob->type) { case OB_MESH: return insert_meshkey(bmain, ob, name, from_mix); diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index 61533e13d7a2..dc36f2ed2027 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -132,7 +132,7 @@ bDeformGroup *BKE_object_defgroup_add_name(Object *ob, const char *name) /** * Add a vgroup of default name to object. *Does not* handle MDeformVert data at all! */ -bDeformGroup *BKE_object_defgroup_add(Object *ob) +bDeformGroup *BKE_object_defgroup_add(Object *ob) { return BKE_object_defgroup_add_name(ob, DATA_("Group")); } @@ -781,4 +781,3 @@ void BKE_object_defgroup_subset_to_index_array( } } } - diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c index 4201bf3d3fb9..589c4468000b 100644 --- a/source/blender/blenkernel/intern/object_dupli.c +++ b/source/blender/blenkernel/intern/object_dupli.c @@ -126,7 +126,7 @@ static void init_context( static void copy_dupli_context(DupliContext *r_ctx, const DupliContext *ctx, Object *ob, float mat[4][4], int index, bool animated) { *r_ctx = *ctx; - + r_ctx->animated |= animated; /* object animation makes all children animated */ /* XXX annoying, previously was done by passing an ID* argument, this at least is more explicit */ @@ -1281,7 +1281,7 @@ DupliApplyData *duplilist_apply(Object *ob, Scene *scene, ListBase *duplilist) { DupliApplyData *apply_data = NULL; int num_objects = BLI_listbase_count(duplilist); - + if (num_objects > 0) { DupliObject *dob; int i; @@ -1302,7 +1302,7 @@ DupliApplyData *duplilist_apply(Object *ob, Scene *scene, ListBase *duplilist) /* copy obmat from duplis */ copy_m4_m4(apply_data->extra[i].obmat, dob->ob->obmat); copy_m4_m4(dob->ob->obmat, dob->mat); - + /* copy layers from the main duplicator object */ apply_data->extra[i].lay = dob->ob->lay; dob->ob->lay = ob->lay; @@ -1322,7 +1322,7 @@ void duplilist_restore(ListBase *duplilist, DupliApplyData *apply_data) for (dob = duplilist->last, i = apply_data->num_objects - 1; dob; dob = dob->prev, --i) { copy_m4_m4(dob->ob->obmat, apply_data->extra[i].obmat); dob->ob->transflag &= ~OB_DUPLICALCDERIVED; - + dob->ob->lay = apply_data->extra[i].lay; } } diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 2d8527f23d66..7f3f916964aa 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -156,7 +156,7 @@ static float gaussRand(RNG *rng) { /* Note: to avoid numerical problems with very small numbers, we make these variables singe-precision floats, * but later we call the double-precision log() and sqrt() functions instead of logf() and sqrtf(). - */ + */ float x; float y; float length2; diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index 07cd28da556a..da455faaa867 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -34,7 +34,7 @@ #include #include -#ifndef WIN32 +#ifndef WIN32 #include #else #include @@ -90,14 +90,14 @@ int seekPackedFile(PackedFile *pf, int offset, int whence) return(oldseek); } - + void rewindPackedFile(PackedFile *pf) { seekPackedFile(pf, 0, SEEK_SET); } int readPackedFile(PackedFile *pf, void *data, int size) -{ +{ if ((pf != NULL) && (size >= 0) && (data != NULL)) { if (size + pf->seek > pf->size) { size = pf->size - pf->seek; @@ -125,7 +125,7 @@ int countPackedFiles(Main *bmain) VFont *vf; bSound *sound; int count = 0; - + /* let's check if there are packed files... */ for (ima = bmain->image.first; ima; ima = ima->id.next) if (BKE_image_has_packedfile(ima)) @@ -167,7 +167,7 @@ PackedFile *newPackedFileMemory(void *mem, int memlen) PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile"); pf->data = mem; pf->size = memlen; - + return pf; } @@ -177,14 +177,14 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char int file, filelen; char name[FILE_MAX]; void *data; - + /* render result has no filename and can be ignored * any other files with no name can be ignored too */ if (filename[0] == '\0') return NULL; //XXX waitcursor(1); - + /* convert relative filenames to absolute filenames */ BLI_strncpy(name, filename, sizeof(name)); @@ -219,7 +219,7 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char } //XXX waitcursor(0); - + return (pf); } @@ -230,7 +230,7 @@ void packAll(Main *bmain, ReportList *reports, bool verbose) VFont *vfont; bSound *sound; int tot = 0; - + for (ima = bmain->image.first; ima; ima = ima->id.next) { if (BKE_image_has_packedfile(ima) == false && !ID_IS_LINKED(ima)) { if (ima->source == IMA_SRC_FILE) { @@ -257,7 +257,7 @@ void packAll(Main *bmain, ReportList *reports, bool verbose) tot++; } } - + if (tot > 0) BKE_reportf(reports, RPT_INFO, "Packed %d files", tot); else if (verbose) @@ -275,7 +275,7 @@ static char *find_new_name(char *name) char tempname[FILE_MAX]; char *newname; size_t len; - + if (fop_exists(name)) { for (number = 1; number <= 999; number++) { BLI_snprintf(tempname, sizeof(tempname), "%s.%03d", name, number); @@ -300,12 +300,12 @@ int writePackedFile( char name[FILE_MAX]; char tempname[FILE_MAX]; /* void *data; */ - + if (guimode) {} //XXX waitcursor(1); - + BLI_strncpy(name, filename, sizeof(name)); BLI_path_abs(name, ref_file_name); - + if (BLI_exists(name)) { for (number = 1; number <= 999; number++) { BLI_snprintf(tempname, sizeof(tempname), "%s.%03d_", name, number); @@ -317,10 +317,10 @@ int writePackedFile( } } } - + /* make sure the path to the file exists... */ BLI_make_existing_file(name); - + file = BLI_open(name, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666); if (file == -1) { BKE_reportf(reports, RPT_ERROR, "Error creating file '%s'", name); @@ -334,10 +334,10 @@ int writePackedFile( else { BKE_reportf(reports, RPT_INFO, "Saved packed file to: %s", name); } - + close(file); } - + if (remove_tmp) { if (ret_value == RET_ERROR) { if (BLI_rename(tempname, name) != 0) { @@ -350,7 +350,7 @@ int writePackedFile( } } } - + if (guimode) {} //XXX waitcursor(0); return (ret_value); @@ -370,10 +370,10 @@ int checkPackedFile(const char *ref_file_name, const char *filename, PackedFile int ret_val, i, len, file; char buf[4096]; char name[FILE_MAX]; - + BLI_strncpy(name, filename, sizeof(name)); BLI_path_abs(name, ref_file_name); - + if (BLI_stat(name, &st) == -1) { ret_val = PF_NOFILE; } @@ -408,11 +408,11 @@ int checkPackedFile(const char *ref_file_name, const char *filename, PackedFile } } } - + close(file); } } - + return(ret_val); } @@ -430,7 +430,7 @@ char *unpackFile( { char *newname = NULL; const char *temp = NULL; - + if (pf != NULL) { switch (how) { case -1: @@ -484,12 +484,12 @@ char *unpackFile( printf("unpackFile: unknown return_value %d\n", how); break; } - + if (temp) { newname = BLI_strdup(temp); } } - + return newname; } @@ -539,7 +539,7 @@ int unpackVFont(Main *bmain, ReportList *reports, VFont *vfont, int how) char localname[FILE_MAX], absname[FILE_MAX]; char *newname; int ret_value = RET_ERROR; - + if (vfont != NULL) { unpack_generate_paths(vfont->name, (ID *)vfont, absname, localname, sizeof(absname), sizeof(localname)); newname = unpackFile(reports, BKE_main_blendfile_path(bmain), absname, localname, vfont->packedfile, how); @@ -551,7 +551,7 @@ int unpackVFont(Main *bmain, ReportList *reports, VFont *vfont, int how) MEM_freeN(newname); } } - + return (ret_value); } @@ -576,7 +576,7 @@ int unpackSound(Main *bmain, ReportList *reports, bSound *sound, int how) ret_value = RET_OK; } } - + return(ret_value); } @@ -633,16 +633,16 @@ int unpackLibraries(Main *bmain, ReportList *reports) Library *lib; char *newname; int ret_value = RET_ERROR; - + for (lib = bmain->library.first; lib; lib = lib->id.next) { if (lib->packedfile && lib->name[0]) { - + newname = unpackFile(reports, BKE_main_blendfile_path(bmain), lib->filepath, lib->filepath, lib->packedfile, PF_WRITE_ORIGINAL); if (newname != NULL) { ret_value = RET_OK; - + printf("Unpacked .blend library: %s\n", newname); - + freePackedFile(lib->packedfile); lib->packedfile = NULL; @@ -650,24 +650,24 @@ int unpackLibraries(Main *bmain, ReportList *reports) } } } - + return(ret_value); } void packLibraries(Main *bmain, ReportList *reports) { Library *lib; - + /* test for relativenss */ for (lib = bmain->library.first; lib; lib = lib->id.next) if (!BLI_path_is_rel(lib->name)) break; - + if (lib) { BKE_reportf(reports, RPT_ERROR, "Cannot pack absolute file: '%s'", lib->name); return; } - + for (lib = bmain->library.first; lib; lib = lib->id.next) if (lib->packedfile == NULL) lib->packedfile = newPackedFile(reports, lib->name, BKE_main_blendfile_path(bmain)); diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index 46fb7c9f9b33..2c17fa442294 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -160,7 +160,7 @@ Paint *BKE_paint_get_active(Scene *sce) { if (sce) { ToolSettings *ts = sce->toolsettings; - + if (sce->basact && sce->basact->object) { switch (sce->basact->object->mode) { case OB_MODE_SCULPT: @@ -601,7 +601,7 @@ float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level, { int factor = BKE_ccg_factor(level, gpm->level); int gridsize = BKE_ccg_gridsize(gpm->level); - + return gpm->data[(y * factor) * gridsize + (x * factor)]; } diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index c064f2e5f71a..50706a05dc06 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -197,7 +197,7 @@ ParticleSystem *psys_get_current(Object *ob) if (psys->flag & PSYS_CURRENT) return psys; } - + return NULL; } short psys_get_current_num(Object *ob) @@ -210,7 +210,7 @@ short psys_get_current_num(Object *ob) for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) if (psys->flag & PSYS_CURRENT) return i; - + return i; } void psys_set_current_num(Object *ob, int index) @@ -348,7 +348,7 @@ void psys_check_group_weights(ParticleSettings *part) dw = part->dupliweights.first; while (dw && dw->ob != go->ob) dw = dw->next; - + if (!dw) { dw = MEM_callocN(sizeof(ParticleDupliWeight), "ParticleDupliWeight"); dw->ob = go->ob; @@ -387,7 +387,7 @@ int psys_uses_gravity(ParticleSimulationData *sim) static void fluid_free_settings(SPHFluidSettings *fluid) { if (fluid) - MEM_freeN(fluid); + MEM_freeN(fluid); } /** Free (or release) any data used by this particle settings (does not free the partsett itself). */ @@ -396,7 +396,7 @@ void BKE_particlesettings_free(ParticleSettings *part) int a; BKE_animdata_free((ID *)part, false); - + for (a = 0; a < MAX_MTEX; a++) { MEM_SAFE_FREE(part->mtex[a]); } @@ -407,7 +407,7 @@ void BKE_particlesettings_free(ParticleSettings *part) curvemapping_free(part->roughcurve); if (part->twistcurve) curvemapping_free(part->twistcurve); - + free_partdeflect(part->pd); free_partdeflect(part->pd2); @@ -438,7 +438,7 @@ void free_hair(Object *UNUSED(ob), ParticleSystem *psys, int dynamics) psys->pointcache = NULL; modifier_free((ModifierData *)psys->clmd); - + psys->clmd = NULL; psys->pointcache = BKE_ptcache_add(&psys->ptcaches); } @@ -517,10 +517,10 @@ void psys_free_particles(ParticleSystem *psys) MEM_freeN(pa->hair); } } - + if (psys->particles->keys) MEM_freeN(psys->particles->keys); - + if (psys->particles->boid) MEM_freeN(psys->particles->boid); @@ -555,11 +555,11 @@ void psys_free_pdd(ParticleSystem *psys) } /* free everything */ void psys_free(Object *ob, ParticleSystem *psys) -{ +{ if (psys) { int nr = 0; ParticleSystem *tpsys; - + psys_free_path_cache(psys, NULL); free_hair(ob, psys, 1); @@ -574,7 +574,7 @@ void psys_free(Object *ob, ParticleSystem *psys) psys->child = NULL; psys->totchild = 0; } - + /* check if we are last non-visible particle system */ for (tpsys = ob->particlesystem.first; tpsys; tpsys = tpsys->next) { if (tpsys->part) { @@ -592,7 +592,7 @@ void psys_free(Object *ob, ParticleSystem *psys) BKE_ptcache_free_list(&psys->ptcaches); psys->pointcache = NULL; - + BLI_freelistN(&psys->targets); BLI_bvhtree_free(psys->bvhtree); @@ -680,7 +680,7 @@ void psys_render_restore(Object *ob, ParticleSystem *psys) data = psys->renderdata; if (!data) return; - + if (data->elems) MEM_freeN(data->elems); @@ -765,7 +765,7 @@ bool psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float if (!(psys->renderdata && (psys->part->simplify_flag & PART_SIMPLIFY_ENABLE))) return false; - + data = psys->renderdata; if (!data->do_simplify) return false; @@ -822,7 +822,7 @@ static float interpolate_particle_value(float v1, float v2, float v3, float v4, value += w[3] * v4; CLAMP(value, 0.f, 1.f); - + return value; } @@ -1075,7 +1075,7 @@ static void do_particle_interpolation(ParticleSystem *psys, int p, ParticleData while (pind->kkey[1]->time < real_t) pind->kkey[1]++; - + pind->kkey[0] = pind->kkey[1] - 1; } else if (pind->cache) { @@ -1236,7 +1236,7 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or if (mface->v4) { v4 = mvert[mface->v4].co; normal_short_to_float_v3(n4, mvert[mface->v4].no); - + interp_v3_v3v3v3v3(vec, v1, v2, v3, v4, w); if (nor) { @@ -1256,7 +1256,7 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or normal_tri_v3(nor, v1, v2, v3); } } - + /* calculate tangent vectors */ if (utan && vtan) { if (tface) { @@ -1364,7 +1364,7 @@ void psys_interpolate_mcol(const MCol *mcol, int quad, const float w[4], MCol *m cp1 = (const char *)&mcol[0]; cp2 = (const char *)&mcol[1]; cp3 = (const char *)&mcol[2]; - + if (quad) { cp4 = (char *)&mcol[3]; @@ -1395,7 +1395,7 @@ static float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int MFace *mf = dm->getTessFaceData(dm, index, CD_MFACE); return interpolate_particle_value(values[mf->v1], values[mf->v2], values[mf->v3], values[mf->v4], fw, mf->v4); } - + } return 0.0f; } @@ -1418,7 +1418,7 @@ static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, const float w[4 psys_w_to_origspace(w, co); co[2] = 0.0f; - + if (quad) { v[3][0] = osface->uv[3][0]; v[3][1] = osface->uv[3][1]; v[3][2] = 0.0f; interp_weights_poly_v3(neww, v, 4, co); @@ -1501,7 +1501,7 @@ int psys_particle_dm_face_lookup( } psys_w_to_origspace(fw, uv); - + if (poly_nodes) { /* we can have a restricted linked list of faces to check, faster! */ LinkNode *tessface_node = poly_nodes[pindex_orig]; @@ -1687,7 +1687,7 @@ float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData * if (!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) return 0.0f; - + return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values); } @@ -1764,13 +1764,13 @@ CustomDataMask psys_emitter_customdata_mask(ParticleSystem *psys) break; } } - + /* particles only need this if they are after a non deform modifier, and * the modifier stack will only create them in that case. */ dataMask |= CD_MASK_ORIGSPACE_MLOOP | CD_MASK_ORIGINDEX; dataMask |= CD_MASK_ORCO; - + return dataMask; } @@ -1814,10 +1814,10 @@ void precalc_guides(ParticleSimulationData *sim, ListBase *effectors) LOOP_PARTICLES { psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, state.co, 0, 0, 0, 0, 0); - + mul_m4_v3(sim->ob->obmat, state.co); mul_mat3_m4_v3(sim->ob->obmat, state.vel); - + pd_point_from_particle(sim, pa, &state, &point); for (eff = effectors->first; eff; eff = eff->next) { @@ -1855,22 +1855,22 @@ int do_guides(ParticleSettings *part, ListBase *effectors, ParticleKey *state, i if (effectors) for (eff = effectors->first; eff; eff = eff->next) { pd = eff->pd; - + if (pd->forcefield != PFIELD_GUIDE) continue; - + data = eff->guide_data + index; - + if (data->strength <= 0.0f) continue; - + guidetime = time / (1.0f - pd->free_end); - + if (guidetime > 1.0f) continue; - + cu = (Curve *)eff->ob->data; - + if (pd->flag & PFIELD_GUIDE_PATH_ADD) { if (where_on_path(eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) return 0; @@ -1879,14 +1879,14 @@ int do_guides(ParticleSettings *part, ListBase *effectors, ParticleKey *state, i if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) return 0; } - + mul_m4_v3(eff->ob->obmat, guidevec); mul_mat3_m4_v3(eff->ob->obmat, guidedir); - + normalize_v3(guidedir); - + copy_v3_v3(vec_to_point, data->vec_to_point); - + if (guidetime != 0.0f) { /* curve direction */ cross_v3_v3v3(temp, eff->guide_dir, guidedir); @@ -1894,52 +1894,52 @@ int do_guides(ParticleSettings *part, ListBase *effectors, ParticleKey *state, i angle = saacos(angle); axis_angle_to_quat(rot2, temp, angle); mul_qt_v3(rot2, vec_to_point); - + /* curve tilt */ axis_angle_to_quat(rot2, guidedir, guidevec[3] - eff->guide_loc[3]); mul_qt_v3(rot2, vec_to_point); } - + /* curve taper */ if (cu->taperobj) mul_v3_fl(vec_to_point, BKE_displist_calc_taper(eff->scene, cu->taperobj, (int)(data->strength * guidetime * 100.0f), 100)); - + else { /* curve size*/ if (cu->flag & CU_PATH_RADIUS) { mul_v3_fl(vec_to_point, radius); } } - + if (clumpcurve) curvemapping_changed_all(clumpcurve); if (roughcurve) curvemapping_changed_all(roughcurve); - + { ParticleKey key; float par_co[3] = {0.0f, 0.0f, 0.0f}; float par_vel[3] = {0.0f, 0.0f, 0.0f}; float par_rot[4] = {1.0f, 0.0f, 0.0f, 0.0f}; float orco_offset[3] = {0.0f, 0.0f, 0.0f}; - + copy_v3_v3(key.co, vec_to_point); do_kink(&key, par_co, par_vel, par_rot, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, 0.f, pd->kink, pd->kink_axis, 0, 0); do_clump(&key, par_co, guidetime, orco_offset, pd->clump_fac, pd->clump_pow, 1.0f, part->child_flag & PART_CHILD_USE_CLUMP_NOISE, part->clump_noise_size, clumpcurve); copy_v3_v3(vec_to_point, key.co); } - + add_v3_v3(vec_to_point, guidevec); - + //sub_v3_v3v3(pa_loc, pa_loc, pa_zero); madd_v3_v3fl(effect, vec_to_point, data->strength); madd_v3_v3fl(veffect, guidedir, data->strength); totstrength += data->strength; - + if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT) totstrength *= weight; } - + if (totstrength != 0.0f) { if (totstrength > 1.0f) mul_v3_fl(effect, 1.0f / totstrength); @@ -2096,7 +2096,7 @@ static bool psys_thread_context_init_path( if (totchild && part->childtype == PART_CHILD_FACES) { totparent = (int)(totchild * part->parents * 0.3f); - + if ((psys->renderdata || use_render_params) && part->child_nbr && part->ren_child_nbr) totparent *= (float)part->child_nbr / (float)part->ren_child_nbr; @@ -2170,7 +2170,7 @@ static void psys_task_init_path(ParticleTask *task, ParticleSimulationData *sim) { /* init random number generator */ int seed = 31415926 + sim->psys->seed; - + task->rng_path = BLI_rng_new(seed); } @@ -2277,7 +2277,7 @@ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cp /* get the original coordinates (orco) for texture usage */ cpa_num = cpa->num; - + foffset = cpa->foffset; cpa_fuv = cpa->fuv; cpa_from = PART_FROM_FACE; @@ -2426,14 +2426,14 @@ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cp if (pa->flag & PARS_UNEXIST) pa = NULL; } - + if (pa) { ListBase modifiers; BLI_listbase_clear(&modifiers); - + psys_particle_on_emitter(ctx->sim.psmd, part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, par_co, NULL, NULL, NULL, par_orco, NULL); - + psys_apply_child_modifiers(ctx, &modifiers, cpa, &ptex, orco, ornor, hairmat, child_keys, par, par_orco); } else @@ -2471,57 +2471,57 @@ void psys_cache_child_paths( ParticleTask *tasks_parent, *tasks_child; int numtasks_parent, numtasks_child; int i, totchild, totparent; - + if (sim->psys->flag & PSYS_GLOBAL_HAIR) return; - + /* create a task pool for child path tasks */ if (!psys_thread_context_init_path(&ctx, sim, sim->scene, cfra, editupdate, use_render_params)) return; - + task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); totchild = ctx.totchild; totparent = ctx.totparent; - + if (editupdate && sim->psys->childcache && totchild == sim->psys->totchildcache) { ; /* just overwrite the existing cache */ } else { /* clear out old and create new empty path cache */ free_child_path_cache(sim->psys); - + sim->psys->childcache = psys_alloc_path_cache_buffers(&sim->psys->childcachebufs, totchild, ctx.segments + ctx.extra_segments + 1); sim->psys->totchildcache = totchild; } - + /* cache parent paths */ ctx.parent_pass = 1; psys_tasks_create(&ctx, 0, totparent, &tasks_parent, &numtasks_parent); for (i = 0; i < numtasks_parent; ++i) { ParticleTask *task = &tasks_parent[i]; - + psys_task_init_path(task, sim); BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); - + /* cache child paths */ ctx.parent_pass = 0; psys_tasks_create(&ctx, totparent, totchild, &tasks_child, &numtasks_child); for (i = 0; i < numtasks_child; ++i) { ParticleTask *task = &tasks_child[i]; - + psys_task_init_path(task, sim); BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); BLI_task_pool_free(task_pool); - + psys_tasks_free(tasks_parent, numtasks_parent); psys_tasks_free(tasks_child, numtasks_child); - + psys_thread_context_free(&ctx); } @@ -2577,15 +2577,15 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re ParticleCacheKey *ca, **cache; DerivedMesh *hair_dm = (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS) ? psys->hair_out_dm : NULL; - + ParticleKey result; - + Material *ma; ParticleInterpolationData pind; ParticleTexture ptex; PARTICLE_P; - + float birthtime = 0.0, dietime = 0.0; float t, time = 0.0, dfra = 1.0 /* , frs_sec = sim->scene->r.frs_sec*/ /*UNUSED*/; float col[4] = {0.5f, 0.5f, 0.5f, 1.0f}; @@ -2622,7 +2622,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if ((psys->flag & PSYS_GLOBAL_HAIR) == 0) { if ((psys->part->flag & PART_CHILD_EFFECT) == 0) vg_effector = psys_cache_vgroup(psmd->dm_final, psys, PSYS_VG_EFFECTOR); - + if (!psys->totchild) vg_length = psys_cache_vgroup(psmd->dm_final, psys, PSYS_VG_LENGTH); } @@ -2697,7 +2697,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if (part->type == PART_HAIR) { HairKey *hkey; - + for (k = 0, hkey = pa->hair; k < pa->totkey; ++k, ++hkey) { mul_v3_m4v3(hkey->world_co, hairmat, hkey->co); } @@ -2775,7 +2775,7 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf { ParticleCacheKey *ca, **cache = edit->pathcache; ParticleEditSettings *pset = &scene->toolsettings->particle; - + PTCacheEditPoint *point = NULL; PTCacheEditKey *ekey = NULL; @@ -2785,7 +2785,7 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf ParticleInterpolationData pind; ParticleKey result; - + float birthtime = 0.0f, dietime = 0.0f; float t, time = 0.0f, keytime = 0.0f /*, frs_sec */; float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f}; @@ -3060,7 +3060,7 @@ static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat sub_v3_v3v3(mat[1], v2, v1); normalize_v3(mat[1]); } - + /* third as a cross product */ cross_v3_v3v3(mat[0], mat[1], mat[2]); } @@ -3077,7 +3077,7 @@ static void psys_face_mat(Object *ob, DerivedMesh *dm, ParticleData *pa, float m mface = dm->getTessFaceData(dm, i, CD_MFACE); osface = dm->getTessFaceData(dm, i, CD_ORIGSPACE); - + if (orco && (orcodata = dm->getVertDataArray(dm, CD_ORCO))) { copy_v3_v3(v[0], orcodata[mface->v1]); copy_v3_v3(v[1], orcodata[mface->v2]); @@ -3106,7 +3106,7 @@ void psys_mat_hair_to_object(Object *UNUSED(ob), DerivedMesh *dm, short from, Pa unit_m4(hairmat); return; } - + psys_face_mat(0, dm, pa, hairmat, 0); psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0); copy_v3_v3(hairmat[3], vec); @@ -3255,7 +3255,7 @@ static void default_particle_settings(ParticleSettings *part) part->grid_res = 10; part->timetweak = 1.0; part->courant_target = 0.2; - + part->integrator = PART_INT_MIDPOINT; part->phystype = PART_PHYS_NEWTON; part->hair_step = 5; @@ -3326,7 +3326,7 @@ ParticleSettings *BKE_particlesettings_add(Main *bmain, const char *name) ParticleSettings *part; part = BKE_libblock_alloc(bmain, ID_PA, name, 0); - + default_particle_settings(part); return part; @@ -3335,24 +3335,24 @@ ParticleSettings *BKE_particlesettings_add(Main *bmain, const char *name) void BKE_particlesettings_clump_curve_init(ParticleSettings *part) { CurveMapping *cumap = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f); - + cumap->cm[0].curve[0].x = 0.0f; cumap->cm[0].curve[0].y = 1.0f; cumap->cm[0].curve[1].x = 1.0f; cumap->cm[0].curve[1].y = 1.0f; - + part->clumpcurve = cumap; } void BKE_particlesettings_rough_curve_init(ParticleSettings *part) { CurveMapping *cumap = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f); - + cumap->cm[0].curve[0].x = 0.0f; cumap->cm[0].curve[0].y = 1.0f; cumap->cm[0].curve[1].x = 1.0f; cumap->cm[0].curve[1].y = 1.0f; - + part->roughcurve = cumap; } @@ -3427,7 +3427,7 @@ static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int index, const f MFace *mf; MTFace *tf; int i; - + tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, name); if (tf == NULL) @@ -3624,7 +3624,7 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex ATTR_FALLTHROUGH; case TEXCO_ORCO: psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co, 0, 0, 0, texvec, 0); - + if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) { BKE_mesh_texspace_calc(me); } @@ -3720,7 +3720,7 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float UNUSED { ParticleSettings *part = psys->part; float size; // time XXX - + if (part->childtype == PART_CHILD_FACES) { int w = 0; size = 0.0; @@ -3857,7 +3857,7 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey * } else { float par_co[3], par_orco[3]; - + cpa = psys->child + p - totpart; if (state->time < 0.0f) @@ -4134,9 +4134,9 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta /* convert velocity to timestep size */ mul_v3_fl(keys[1].vel, dfra * timestep); mul_v3_fl(keys[2].vel, dfra * timestep); - + psys_interpolate_particle(-1, keys, keytime, state, 1); - + /* convert back to real velocity */ mul_v3_fl(state->vel, 1.f / (dfra * timestep)); @@ -4162,7 +4162,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta if (sim->psys->lattice_deform_data) calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength); } - + return 1; } } @@ -4200,7 +4200,7 @@ void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part, mtface += cpa->num; psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv); } - + psys_particle_on_emitter(psmd, PART_FROM_FACE, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, loc, 0, 0, 0, orco, 0); return; } @@ -4411,7 +4411,7 @@ void psys_apply_hair_lattice(Scene *scene, Object *ob, ParticleSystem *psys) mul_m4_v3(imat, hkey->co); } } - + end_latt_deform(psys->lattice_deform_data); psys->lattice_deform_data = NULL; diff --git a/source/blender/blenkernel/intern/particle_child.c b/source/blender/blenkernel/intern/particle_child.c index c921e1ea107a..79c3f2472329 100644 --- a/source/blender/blenkernel/intern/particle_child.c +++ b/source/blender/blenkernel/intern/particle_child.c @@ -737,6 +737,10 @@ static void do_twist(const ParticleChildModifierContext *modifier_ctx, ParticleTexture *ptex = modifier_ctx->ptex; ParticleSettings *part = sim->psys->part; /* Early output checks. */ + if (modifier_ctx->parent_keys == NULL) { + /* Cannot get axis of rotation... */ + return; + } if (part->childtype != PART_CHILD_PARTICLES) { /* Interpolated children behave weird with twist. */ return; diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index d1c6dbe421c4..8a3b1312590e 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -94,7 +94,7 @@ static void distribute_simple_children(Scene *scene, Object *ob, DerivedMesh *fi for (p=0; ptotpart; p++,cpa++) { float length=2.0; cpa->parent=p; - + /* create even spherical distribution inside unit sphere */ while (length>=1.0f) { cpa->fuv[0]=2.0f*BLI_frand()-1.0f; @@ -136,7 +136,7 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys) /* determine major axis */ axis = axis_dominant_v3_single(delta); - + d = delta[axis]/(float)res; size[axis] = res; @@ -198,7 +198,7 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys) totface=dm->getNumTessFaces(dm); mface=mface_array=dm->getTessFaceDataArray(dm,CD_MFACE); - + for (a=0; a= value) && (sum[mid - 1] < value)) return mid; - + if (sum[mid] > value) { high = mid - 1; } @@ -472,22 +472,22 @@ static void distribute_from_verts_exec(ParticleTask *thread, ParticleData *pa, i } } } - + #if ONLY_WORKING_WITH_PA_VERTS if (ctx->tree) { KDTreeNearest ptn[3]; int w, maxw; - + psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0); BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1); maxw = BLI_kdtree_find_nearest_n(ctx->tree,orco1,ptn,3); - + for (w=0; wverts[w]=ptn->num; } } #endif - + if (rng_skip_tot > 0) /* should never be below zero */ BLI_rng_skip(thread->rng, rng_skip_tot); } @@ -501,10 +501,10 @@ static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, i int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ MFace *mface; - + pa->num = i = ctx->index[p]; mface = dm->getTessFaceData(dm,i,CD_MFACE); - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -524,12 +524,12 @@ static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, i randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mface->v4, pa->fuv); break; } pa->foffset= 0.0f; - + if (rng_skip_tot > 0) /* should never be below zero */ BLI_rng_skip(thread->rng, rng_skip_tot); } @@ -542,13 +542,13 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, int distr= ctx->distr; int i, intersect, tot; int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ - + MFace *mface; MVert *mvert=dm->getVertDataArray(dm,CD_MVERT); - + pa->num = i = ctx->index[p]; mface = dm->getTessFaceData(dm,i,CD_MFACE); - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -568,30 +568,30 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mface->v4, pa->fuv); break; } pa->foffset= 0.0f; - + /* experimental */ tot=dm->getNumTessFaces(dm); - + psys_interpolate_face(mvert,mface,0,0,pa->fuv,co,nor,0,0,0,0); - + normalize_v3(nor); negate_v3(nor); - + min_d=FLT_MAX; intersect=0; - + for (i=0,mface=dm->getTessFaceDataArray(dm,CD_MFACE); inum) continue; - + v1=mvert[mface->v1].co; v2=mvert[mface->v2].co; v3=mvert[mface->v3].co; - + if (isect_ray_tri_v3(co, nor, v2, v3, v1, &cur_d, NULL)) { if (cur_dv4) { v4=mvert[mface->v4].co; - + if (isect_ray_tri_v3(co, nor, v4, v1, v3, &cur_d, NULL)) { if (cur_d 0) /* should never be below zero */ BLI_rng_skip(thread->rng, rng_skip_tot); } @@ -637,40 +637,40 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i int cfrom= ctx->cfrom; int i; int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ - + MFace *mf; - + if (ctx->index[p] < 0) { cpa->num=0; cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]=0.0f; cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0; return; } - + mf= dm->getTessFaceData(dm, ctx->index[p], CD_MFACE); - + randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mf->v4, cpa->fuv); - + cpa->num = ctx->index[p]; - + if (ctx->tree) { KDTreeNearest ptn[10]; int w,maxw;//, do_seams; float maxd /*, mind,dd */, totw= 0.0f; int parent[10]; float pweight[10]; - + psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,NULL,NULL,orco1,NULL); BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1); maxw = BLI_kdtree_find_nearest_n(ctx->tree,orco1,ptn,3); - + maxd=ptn[maxw-1].dist; /* mind=ptn[0].dist; */ /* UNUSED */ - + /* the weights here could be done better */ for (w=0; w=0) { cpa->pa[i]=parent[w]; @@ -693,13 +693,13 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i cpa->pa[i]=-1; cpa->w[i]=0.0f; } - + if (totw > 0.0f) { for (w = 0; w < 4; w++) { cpa->w[w] /= totw; } } - + cpa->parent=cpa->pa[0]; } @@ -715,7 +715,7 @@ static void exec_distribute_parent(TaskPool * __restrict UNUSED(pool), void *tas int p; BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP * task->begin); - + pa= psys->particles + task->begin; switch (psys->part->from) { case PART_FROM_FACE: @@ -739,20 +739,20 @@ static void exec_distribute_child(TaskPool * __restrict UNUSED(pool), void *task ParticleSystem *psys = task->ctx->sim.psys; ChildParticle *cpa; int p; - + /* RNG skipping at the beginning */ cpa = psys->child; for (p = 0; p < task->begin; ++p, ++cpa) { if (task->ctx->skip) /* simplification skip */ BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP * task->ctx->skip[p]); - + BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP); } - + for (; p < task->end; ++p, ++cpa) { if (task->ctx->skip) /* simplification skip */ BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP * task->ctx->skip[p]); - + distribute_children_exec(task, cpa, p); } } @@ -825,28 +825,28 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti int jitlevel= 1, distr; float *element_weight=NULL,*jitter_offset=NULL, *vweight=NULL; float cur, maxweight=0.0, tweight, totweight, inv_totweight, co[3], nor[3], orco[3]; - + if (ELEM(NULL, ob, psys, psys->part)) return 0; - + part=psys->part; totpart=psys->totpart; if (totpart==0) return 0; - + if (!finaldm->deformedOnly && !finaldm->getTessFaceDataArray(finaldm, CD_ORIGINDEX)) { printf("Can't create particles with the current modifier stack, disable destructive modifiers\n"); // XXX error("Can't paint with the current modifier stack, disable destructive modifiers"); return 0; } - + /* XXX This distribution code is totally broken in case from == PART_FROM_CHILD, it's always using finaldm * even if use_modifier_stack is unset... But making things consistent here break all existing edited * hair systems, so better wait for complete rewrite. */ psys_thread_context_init(ctx, sim); - + /* First handle special cases */ if (from == PART_FROM_CHILD) { /* Simple children */ @@ -878,7 +878,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti return 0; } } - + /* Create trees and original coordinates if needed */ if (from == PART_FROM_CHILD) { distr=PART_DISTR_RAND; @@ -906,7 +906,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti else { distr = part->distr; BLI_srandom(31415926 + psys->seed); - + if (psys->part->use_modifier_stack) dm = finaldm; else @@ -964,7 +964,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti MVert *v1, *v2, *v3, *v4; float totarea=0.f, co1[3], co2[3], co3[3], co4[3]; float (*orcodata)[3]; - + orcodata= dm->getVertDataArray(dm, CD_ORCO); for (i=0; iv4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3); - + if (cur > maxweight) maxweight = cur; @@ -1028,7 +1028,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti for (i=0;igetTessFaceData(dm,i,CD_MFACE); tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3]; - + if (mf->v4) { tweight += vweight[mf->v4]; tweight /= 4.0f; @@ -1101,7 +1101,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } else { double step, pos; - + step = (totpart < 2) ? 0.5 : 1.0 / (double)totpart; /* This is to address tricky issues with vertex-emitting when user tries (and expects) exact 1-1 vert/part * distribution (see T47983 and its two example files). It allows us to consider pos as @@ -1145,17 +1145,17 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti /* Create jittering if needed */ if (distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) { jitlevel= part->userjit; - + if (jitlevel == 0) { jitlevel= totpart/totelem; if (part->flag & PART_EDISTR) jitlevel*= 2; /* looks better in general, not very scientific */ if (jitlevel<3) jitlevel= 3; } - + jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit"); /* for small amounts of particles we use regular jitter since it looks - * a bit better, for larger amounts we switch to hammersley sequence + * a bit better, for larger amounts we switch to hammersley sequence * because it is much faster */ if (jitlevel < 25) init_mv_jit(jit, jitlevel, psys->seed, part->jitfac); @@ -1192,7 +1192,7 @@ static void psys_task_init_distribute(ParticleTask *task, ParticleSimulationData { /* init random number generator */ int seed = 31415926 + sim->psys->seed; - + task->rng = BLI_rng_new(seed); } @@ -1204,19 +1204,19 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) ParticleTask *tasks; DerivedMesh *finaldm = sim->psmd->dm_final; int i, totpart, numtasks; - + /* create a task pool for distribution tasks */ if (!psys_thread_context_init_distribute(&ctx, sim, from)) return; - + task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); - + totpart = (from == PART_FROM_CHILD ? sim->psys->totchild : sim->psys->totpart); psys_tasks_create(&ctx, 0, totpart, &tasks, &numtasks); for (i = 0; i < numtasks; ++i) { ParticleTask *task = &tasks[i]; - + psys_task_init_distribute(task, sim); if (from == PART_FROM_CHILD) BLI_task_pool_push(task_pool, exec_distribute_child, task, false, TASK_PRIORITY_LOW); @@ -1224,16 +1224,16 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) BLI_task_pool_push(task_pool, exec_distribute_parent, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); - + BLI_task_pool_free(task_pool); - + psys_calc_dmcache(sim->ob, finaldm, sim->psmd->dm_deformed, sim->psys); - + if (ctx.dm != finaldm) ctx.dm->release(ctx.dm); - + psys_tasks_free(tasks, numtasks); - + psys_thread_context_free(&ctx); } @@ -1277,12 +1277,12 @@ static float psys_render_projected_area(ParticleSystem *psys, const float center { ParticleRenderData *data = psys->renderdata; float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius; - + /* transform to view space */ copy_v3_v3(co, center); co[3] = 1.0f; mul_m4_v4(data->viewmat, co); - + /* compute two vectors orthogonal to view vector */ normalize_v3_v3(view, co); ortho_basis_v3v3_v3(ortho1, ortho2, view); @@ -1320,7 +1320,7 @@ static float psys_render_projected_area(ParticleSystem *psys, const float center *viewport *= psys_render_viewport_falloff(vprate, -(co[1] + radius), data->winy); else if (co[1] - radius > data->winy) *viewport *= psys_render_viewport_falloff(vprate, (co[1] - radius) - data->winy, data->winy); - + return area; } diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 9eaebc2c55ca..353c75d63c60 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -169,8 +169,9 @@ void psys_reset(ParticleSystem *psys, int mode) } else if (mode == PSYS_RESET_CACHE_MISS) { /* set all particles to be skipped */ - LOOP_PARTICLES + LOOP_PARTICLES { pa->flag |= PARS_NO_DISP; + } } /* reset children */ @@ -238,7 +239,7 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) } } } - + if (psys->particles) { totsaved=MIN2(psys->totpart,totpart); /*save old pars*/ @@ -268,13 +269,14 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) MEM_freeN(psys->particles); psys_free_pdd(psys); } - + psys->particles=newpars; psys->totpart=totpart; if (newboids) { - LOOP_PARTICLES + LOOP_PARTICLES { pa->boid = newboids++; + } } } @@ -313,14 +315,14 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm_final, DerivedMesh *dm_deform { /* use for building derived mesh mapping info: * - * node: the allocated links - total derived mesh element count + * node: the allocated links - total derived mesh element count * nodearray: the array of nodes aligned with the base mesh's elements, so * each original elements can reference its derived elements */ Mesh *me= (Mesh*)ob->data; bool use_modifier_stack= psys->part->use_modifier_stack; PARTICLE_P; - + /* CACHE LOCATIONS */ if (!dm_final->deformedOnly) { /* Will use later to speed up subsurf/derivedmesh */ @@ -424,7 +426,7 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm_final, DerivedMesh *dm_deform /* TODO PARTICLE, make the following line unnecessary, each function * should know to use the num or num_dmcache, set the num_dmcache to * an invalid value, just in case */ - + LOOP_PARTICLES { pa->num_dmcache = DMCACHE_NOTFOUND; } @@ -453,15 +455,15 @@ void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, P int numtasks = ceil_ii((endpart - startpart), MAX_PARTICLES_PER_TASK); float particles_per_task = (float)(endpart - startpart) / (float)numtasks, p, pnext; int i; - + tasks = MEM_callocN(sizeof(ParticleTask) * numtasks, "ParticleThread"); *r_numtasks = numtasks; *r_tasks = tasks; - + p = (float)startpart; for (i = 0; i < numtasks; i++, p = pnext) { pnext = p + particles_per_task; - + tasks[i].ctx = ctx; tasks[i].begin = (int)p; tasks[i].end = min_ii((int)pnext, endpart); @@ -471,7 +473,7 @@ void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, P void psys_tasks_free(ParticleTask *tasks, int numtasks) { int i; - + /* threads */ for (i = 0; i < numtasks; ++i) { if (tasks[i].rng) @@ -534,7 +536,7 @@ static void initialize_particle_texture(ParticleSimulationData *sim, ParticleDat ParticleTexture ptex; psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f); - + switch (part->type) { case PART_EMITTER: if (ptex.exist < psys_frand(psys, p + 125)) { @@ -558,7 +560,7 @@ void initialize_particle(ParticleSimulationData *sim, ParticleData *pa) { ParticleSettings *part = sim->psys->part; float birth_time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart; - + pa->flag &= ~PARS_UNEXIST; pa->time = part->sta + (part->end - part->sta) * birth_time; @@ -617,7 +619,7 @@ static void free_unexisting_particles(ParticleSimulationData *sim) if (psys->totunexist) { int newtotpart = psys->totpart - psys->totunexist; ParticleData *npa, *newpars; - + npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles"); for (p=0, pa=psys->particles; ppsmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0); else psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0); - + /* get possible textural influence */ psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra); @@ -713,7 +715,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic /* let's convert: */ /* -location */ mul_m4_v3(ob->obmat, loc); - + /* -normal */ mul_mat3_m4_v3(ob->obmat, nor); normalize_v3(nor); @@ -731,10 +733,10 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic copy_v3_v3(utan, nor); mul_v3_fl(utan,dot_v3v3(vtan,nor)); sub_v3_v3(vtan, utan); - + normalize_v3(vtan); } - + /* -velocity (boids need this even if there's no random velocity) */ if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) { @@ -755,7 +757,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic mul_mat3_m4_v3(ob->obmat,r_ave); normalize_v3(r_ave); } - + /* -rotation */ if (part->randrotfac != 0.0f) { r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f); @@ -792,7 +794,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic negate_v3_v3(mat[2], r_vel); normalize_v3(mat[2]); cross_v3_v3v3(mat[1], mat[2], mat[0]); - + /* apply rotation */ mat3_to_quat_is_ok( q,mat); copy_qt_qt(state->rot, q); @@ -811,11 +813,11 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic sub_v3_v3v3(vel, loc, state->co); mul_v3_fl(vel, part->obfac/dtime); } - + /* *emitter normal */ if (part->normfac != 0.f) madd_v3_v3fl(vel, nor, part->normfac); - + /* *emitter tangent */ if (sim->psmd && part->tanfac != 0.f) madd_v3_v3fl(vel, vtan, part->tanfac); @@ -844,7 +846,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic /* *particle */ if (part->partfac != 0.f) madd_v3_v3fl(vel, p_vel, part->partfac); - + mul_v3_v3fl(state->vel, vel, ptex.ivel); /* -location from emitter */ @@ -883,7 +885,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic use_global_space = true; break; } - + /* create rotation quat */ @@ -992,7 +994,7 @@ static void evaluate_emitter_anim(Scene *scene, Object *ob, float cfra) { if (ob->parent) evaluate_emitter_anim(scene, ob->parent, cfra); - + /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */ BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM); BKE_object_where_is_calc_time(scene, ob, cfra); @@ -1006,7 +1008,7 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, ParticleTexture ptex; int p = pa - psys->particles; part=psys->part; - + /* get precise emitter matrix if particle is born */ if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) { evaluate_emitter_anim(sim->scene, sim->ob, pa->time); @@ -1083,7 +1085,7 @@ static void reset_all_particles(ParticleSimulationData *sim, float dtime, float { ParticleData *pa; int p, totpart=sim->psys->totpart; - + for (p=from, pa=sim->psys->particles+from; pscene; - + /* no proper targets so let's clear and bail out */ if (psys->totkeyed==0) { free_keyed_keys(psys); @@ -1154,16 +1156,16 @@ static void set_keyed_keys(ParticleSimulationData *sim) if (totpart && psys->particles->totkey != totkeys) { free_keyed_keys(psys); - + key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys"); - + LOOP_PARTICLES { pa->keys = key; pa->totkey = totkeys; key += totkeys; } } - + psys->flag &= ~PSYS_KEYED; @@ -1245,17 +1247,17 @@ static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra) BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ); need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra; BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); - + if (need_rebuild) { LOOP_SHOWN_PARTICLES { totpart++; } - + BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_WRITE); - + BLI_bvhtree_free(psys->bvhtree); psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6); - + LOOP_SHOWN_PARTICLES { if (pa->alive == PARS_ALIVE) { if (pa->state.time == cfra) @@ -1265,9 +1267,9 @@ static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra) } } BLI_bvhtree_balance(psys->bvhtree); - + psys->bvhtree_frame = cfra; - + BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); } } @@ -1361,7 +1363,7 @@ static void integrate_particle(ParticleSettings *part, ParticleData *pa, float d if (external_acceleration) add_v3_v3(acceleration, external_acceleration); - + /* calculate next state */ add_v3_v3(states[i].vel, impulse); @@ -1494,7 +1496,7 @@ static void sph_springs_modify(ParticleSystem *psys, float dtime) SPHFluidSettings *fluid = psys->part->fluid; ParticleData *pa1, *pa2; ParticleSpring *spring = psys->fluid_springs; - + float h, d, Rij[3], rij, Lij; int i; @@ -1587,9 +1589,9 @@ static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], } else { BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ); - + BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr); - + BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); } } @@ -1769,7 +1771,7 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa } } } - + /* Artificial buoyancy force in negative gravity direction */ if (fluid->buoyancy > 0.f && gravity) madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density)); @@ -2516,7 +2518,7 @@ static int collision_sphere_to_edges(ParticleCollision *col, float radius, Parti result->uv[0] = u; - + hit = cur; *t = ct; } @@ -2541,7 +2543,7 @@ static int collision_sphere_to_verts(ParticleCollision *col, float radius, Parti cur->inside = 0; ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert); - + if (ct >= 0.f && ct < *t) { *result = *cur; @@ -2688,7 +2690,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* get exact velocity right before collision */ madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1); - + /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */ mul_v3_fl(pce->vel, col->inv_timestep); @@ -2705,14 +2707,14 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* angular <-> linear velocity */ if (dynamic_rotation) { float vr_tan[3], v1_tan[3], ave[3]; - + /* linear velocity of particle surface */ cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave); mul_v3_fl(vr_tan, pa->size); /* change to coordinates that move with the collision plane */ sub_v3_v3v3(v1_tan, v0_tan, vc_tan); - + /* The resulting velocity is a weighted average of particle cm & surface * velocity. This weight (related to particle's moment of inertia) could * be made a parameter for angular <-> linear conversion. @@ -2775,7 +2777,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR v0[2] = 0.0f; } } - + /* re-apply acceleration to final location and velocity */ madd_v3_v3v3fl(pa->state.co, co, v0, dt2); madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2); @@ -2784,7 +2786,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* make sure particle stays on the right side of the surface */ if (!through) { distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor); - + if (distance < col->radius + COLLISION_MIN_DISTANCE) madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance); @@ -2885,7 +2887,7 @@ static void collision_check(ParticleSimulationData *sim, int p, float dfra, floa /* 10 iterations to catch multiple collisions */ while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) { if (collision_detect(pa, &col, &hit, sim->colliders)) { - + collision_count++; if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS) @@ -2989,19 +2991,19 @@ static bool psys_hair_use_simulation(ParticleData *pa, float max_length) * but this can happen in old files when e.g. cutting hair. */ const float min_length = 0.1f * max_length; - + HairKey *key; int k; - + if (pa->totkey < 2) return false; - + for (k=1, key=pa->hair+1; ktotkey; k++,key++) { float length = len_v3v3(key->co, (key-1)->co); if (length < min_length) return false; } - + return true; } @@ -3012,7 +3014,7 @@ static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight) dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight"); dvert->totweight = 1; } - + dvert->dw->weight = weight; dvert++; } @@ -3034,7 +3036,7 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int float hairmat[4][4]; float max_length; float hair_radius; - + dm = *r_dm; if (!dm) { *r_dm = dm = CDDM_new(totpoint, totedge, 0, 0, 0); @@ -3043,12 +3045,12 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int mvert = CDDM_get_verts(dm); medge = CDDM_get_edges(dm); dvert = DM_get_vert_data_layer(dm, CD_MDEFORMVERT); - + hairdata = *r_hairdata; if (!hairdata) { *r_hairdata = hairdata = MEM_mallocN(sizeof(ClothHairData) * totpoint, "hair data"); } - + /* calculate maximum segment length */ max_length = 0.0f; LOOP_PARTICLES { @@ -3060,12 +3062,12 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int } } } - + psys->clmd->sim_parms->vgroup_mass = 1; - + /* XXX placeholder for more flexible future hair settings */ hair_radius = part->size; - + /* make vgroup for pin roots etc.. */ hair_index = 1; LOOP_PARTICLES { @@ -3153,7 +3155,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) int totedge; float (*deformedVerts)[3]; bool realloc_roots; - + if (!psys->clmd) { psys->clmd = (ClothModifierData*)modifier_new(eModifierType_Cloth); psys->clmd->sim_parms->goalspring = 0.0f; @@ -3161,7 +3163,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) psys->clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_GOAL|CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS; psys->clmd->coll_parms->flags &= ~CLOTH_COLLSETTINGS_FLAG_SELF; } - + /* count simulated points */ totpoint = 0; totedge = 0; @@ -3172,7 +3174,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) totpoint += pa->totkey + 1; /* +1 for virtual root point */ } } - + realloc_roots = false; /* whether hair root info array has to be reallocated */ if (psys->hair_in_dm) { DerivedMesh *dm = psys->hair_in_dm; @@ -3182,36 +3184,36 @@ static void do_hair_dynamics(ParticleSimulationData *sim) realloc_roots = true; } } - + if (!psys->hair_in_dm || !psys->clmd->hairdata || realloc_roots) { if (psys->clmd->hairdata) { MEM_freeN(psys->clmd->hairdata); psys->clmd->hairdata = NULL; } } - + hair_create_input_dm(sim, totpoint, totedge, &psys->hair_in_dm, &psys->clmd->hairdata); - + if (psys->hair_out_dm) psys->hair_out_dm->release(psys->hair_out_dm); - + psys->clmd->point_cache = psys->pointcache; /* for hair sim we replace the internal cloth effector weights temporarily * to use the particle settings */ clmd_effweights = psys->clmd->sim_parms->effector_weights; psys->clmd->sim_parms->effector_weights = psys->part->effector_weights; - + deformedVerts = MEM_mallocN(sizeof(*deformedVerts) * psys->hair_in_dm->getNumVerts(psys->hair_in_dm), "do_hair_dynamics vertexCos"); psys->hair_out_dm = CDDM_copy(psys->hair_in_dm); psys->hair_out_dm->getVertCos(psys->hair_out_dm, deformedVerts); - + clothModifier_do(psys->clmd, sim->scene, sim->ob, psys->hair_in_dm, deformedVerts); - + CDDM_apply_vert_coords(psys->hair_out_dm, deformedVerts); - + MEM_freeN(deformedVerts); - + /* restore cloth effector weights */ psys->clmd->sim_parms->effector_weights = clmd_effweights; } @@ -3260,11 +3262,11 @@ static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra)) PARTICLE_P; invert_m4_m4(ob->imat, ob->obmat); - + psys->lattice_deform_data= psys_create_lattice_deform_data(sim); if (psys->totpart==0) return; - + /* save new keys for elements if needed */ LOOP_PARTICLES { /* first time alloc */ @@ -3417,7 +3419,7 @@ static void dynamics_step_sph_ddr_task_cb_ex( } static void dynamics_step_sph_classical_basic_integrate_task_cb_ex( - void *__restrict userdata, + void *__restrict userdata, const int p, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -3556,7 +3558,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { ParticleTarget *pt = psys->targets.first; psys_update_particle_bvhtree(psys, cfra); - + for (; pt; pt=pt->next) { /* Updating others systems particle tree for fluid-fluid interaction */ if (pt->ob) psys_update_particle_bvhtree(BLI_findlink(&pt->ob->particlesystem, pt->psys-1), cfra); @@ -3613,7 +3615,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) LOOP_DYNAMIC_PARTICLES { /* do global forces & effectors */ basic_integrate(sim, p, pa->state.time, cfra); - + /* deflection */ if (sim->colliders) collision_check(sim, p, pa->state.time, cfra); @@ -3627,7 +3629,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { LOOP_DYNAMIC_PARTICLES { bbd.goal_ob = NULL; - + boid_brain(&bbd, p, pa); if (pa->alive != PARS_DYING) { @@ -3761,7 +3763,7 @@ static void cached_step(ParticleSimulationData *sim, float cfra) float disp, dietime; psys_update_effectors(sim); - + disp= psys_get_current_display_percentage(psys); LOOP_PARTICLES { @@ -3811,7 +3813,7 @@ static void particles_fluid_step( #ifdef WITH_MOD_FLUID { FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(sim->ob, eModifierType_Fluidsim); - + if ( fluidmd && fluidmd->fss) { FluidsimSettings *fss= fluidmd->fss; ParticleSettings *part = psys->part; @@ -3822,7 +3824,7 @@ static void particles_fluid_step( int p, j, totpart; int readMask, activeParts = 0, fileParts = 0; gzFile gzf; - + // XXX if (ob==G.obedit) // off... // return; @@ -3831,7 +3833,7 @@ static void particles_fluid_step( BLI_path_abs(filename, modifier_path_relbase(bmain, sim->ob)); - BLI_path_frame(filename, curFrame, 0); // fixed #frame-no + BLI_path_frame(filename, curFrame, 0); // fixed #frame-no gzf = BLI_gzopen(filename, "rb"); if (!gzf) { @@ -3839,46 +3841,46 @@ static void particles_fluid_step( // XXX bad level call elbeemDebugOut(debugStrBuffer); return; } - + gzread(gzf, &totpart, sizeof(totpart)); totpart = (use_render_params) ? totpart:(part->disp*totpart) / 100; - + part->totpart= totpart; part->sta=part->end = 1.0f; part->lifetime = sim->scene->r.efra + 1; - + /* allocate particles */ realloc_particles(sim, part->totpart); - + // set up reading mask readMask = fss->typeFlags; - + for (p=0, pa=psys->particles; psize), sizeof(float)); - + pa->size /= 10.0f; - + for (j=0; j<3; j++) { float wrf; - gzread(gzf, &wrf, sizeof( wrf )); + gzread(gzf, &wrf, sizeof( wrf )); pa->state.co[j] = wrf; //fprintf(stderr,"Rj%d ",j); } for (j=0; j<3; j++) { float wrf; - gzread(gzf, &wrf, sizeof( wrf )); + gzread(gzf, &wrf, sizeof( wrf )); pa->state.vel[j] = wrf; } - + zero_v3(pa->state.ave); unit_qt(pa->state.rot); - + pa->time = 1.f; pa->dietime = sim->scene->r.efra + 1; pa->lifetime = sim->scene->r.efra; @@ -3888,18 +3890,18 @@ static void particles_fluid_step( else { // skip... for (j=0; j<2*3+1; j++) { - float wrf; gzread(gzf, &wrf, sizeof( wrf )); + float wrf; gzread(gzf, &wrf, sizeof( wrf )); } } fileParts++; } gzclose(gzf); - + totpart = psys->totpart = activeParts; BLI_snprintf(debugStrBuffer,sizeof(debugStrBuffer),"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d\n", psys->totpart,activeParts,fileParts,readMask); // bad level call // XXX elbeemDebugOut(debugStrBuffer); - + } // fluid sim particles done } #else @@ -3945,7 +3947,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ pid = &ptcacheid; BKE_ptcache_id_from_particles(pid, sim->ob, psys); - + BKE_ptcache_id_time(pid, sim->scene, 0.0f, &startframe, &endframe, NULL); /* clear everything on start frame, or when psys needs full reset! */ @@ -3954,7 +3956,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ BKE_ptcache_validate(cache, startframe); cache->flag &= ~PTCACHE_REDO_NEEDED; } - + CLAMP(cache_cfra, startframe, endframe); } @@ -4063,7 +4065,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ } } } - + /* 4. only write cache starting from second frame */ if (pid) { BKE_ptcache_validate(cache, (int)cache_cfra); @@ -4129,14 +4131,16 @@ void psys_check_boid_data(ParticleSystem *psys) if (!pa->boid) { bpa = MEM_callocN(psys->totpart * sizeof(BoidParticle), "Boid Data"); - LOOP_PARTICLES + LOOP_PARTICLES { pa->boid = bpa++; + } } } else if (pa->boid) { MEM_freeN(pa->boid); - LOOP_PARTICLES + LOOP_PARTICLES { pa->boid = NULL; + } } } diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 51d50b061de5..772cda7266e4 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -133,7 +133,7 @@ static void update_node_vb(PBVH *bvh, PBVHNode *node) BB vb; BB_reset(&vb); - + if (node->flag & PBVH_Leaf) { PBVHVertexIter vd; @@ -184,10 +184,10 @@ static int partition_indices(int *prim_indices, int lo, int hi, int axis, for (;; ) { for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) ; for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) ; - + if (!(i < j)) return i; - + SWAP(int, prim_indices[i], prim_indices[j]); i++; } @@ -217,7 +217,7 @@ static int partition_indices_material(PBVH *bvh, int lo, int hi) for (; grid_materials_match(first, &flagmats[indices[i]]); i++) ; for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) ; } - + if (!(i < j)) return i; @@ -389,7 +389,7 @@ static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc, /* Still need vb for searches */ update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count); - + if (bvh->looptri) build_mesh_leaf_node(bvh, bvh->nodes + node_index); else { @@ -607,11 +607,6 @@ void BKE_pbvh_build_grids(PBVH *bvh, CCGElem **grids, MEM_freeN(prim_bbc); } -void BKE_pbvh_set_ccgdm(PBVH *bvh, CCGDerivedMesh *ccgdm) -{ - bvh->ccgdm = ccgdm; -} - PBVH *BKE_pbvh_new(void) { PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh"); @@ -1293,7 +1288,7 @@ void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int * } pbvh_iter_end(&iter); - + const int tot = BLI_gset_len(face_set); if (tot == 0) { *r_totface = 0; @@ -1358,11 +1353,6 @@ void BKE_pbvh_get_grid_key(const PBVH *bvh, CCGKey *key) *key = bvh->gridkey; } -CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh) -{ - return bvh->ccgdm; -} - BMesh *BKE_pbvh_get_bmesh(PBVH *bvh) { @@ -1396,7 +1386,7 @@ void BKE_pbvh_node_mark_normals_update(PBVHNode *node) void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden) { BLI_assert(node->flag & PBVH_Leaf); - + if (fully_hidden) node->flag |= PBVH_FullyHidden; else @@ -1421,7 +1411,7 @@ void BKE_pbvh_node_num_verts( int *r_uniquevert, int *r_totvert) { int tot; - + switch (bvh->type) { case PBVH_GRIDS: tot = node->totprim * bvh->gridkey.grid_area; @@ -2059,7 +2049,7 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3], { float vmin[3], vmax[3]; PlaneAABBIsect ret = ISECT_INSIDE; - + for (int i = 0; i < 4; ++i) { for (int axis = 0; axis < 3; ++axis) { if (planes[i][axis] > 0) { @@ -2071,7 +2061,7 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3], vmax[axis] = bb_min[axis]; } } - + if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0) return ISECT_OUTSIDE; else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0) @@ -2087,7 +2077,7 @@ bool BKE_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data) /* BKE_pbvh_node_get_BB */ bb_min = node->vb.bmin; bb_max = node->vb.bmax; - + return test_planes_aabb(bb_min, bb_max, data) != ISECT_OUTSIDE; } @@ -2097,7 +2087,7 @@ bool BKE_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data) /* BKE_pbvh_node_get_BB */ bb_min = node->vb.bmin; bb_max = node->vb.bmax; - + return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE; } @@ -2322,22 +2312,22 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node, const int *vert_indices; int *grid_indices; int totgrid, gridsize, uniq_verts, totvert; - + vi->grid = NULL; vi->no = NULL; vi->fno = NULL; vi->mvert = NULL; - + BKE_pbvh_node_get_grids(bvh, node, &grid_indices, &totgrid, NULL, &gridsize, &grids); BKE_pbvh_node_num_verts(bvh, node, &uniq_verts, &totvert); BKE_pbvh_node_get_verts(bvh, node, &vert_indices, &verts); vi->key = &bvh->gridkey; - + vi->grids = grids; vi->grid_indices = grid_indices; vi->totgrid = (grids) ? totgrid : 1; vi->gridsize = gridsize; - + if (mode == PBVH_ITER_ALL) vi->totvert = totvert; else diff --git a/source/blender/blenkernel/intern/pbvh_intern.h b/source/blender/blenkernel/intern/pbvh_intern.h index afd539b2273b..4aef97bda47a 100644 --- a/source/blender/blenkernel/intern/pbvh_intern.h +++ b/source/blender/blenkernel/intern/pbvh_intern.h @@ -149,8 +149,6 @@ struct PBVH { * objects in sculpt mode with different sizes at the same time, so now storing that common gpu buffer * in an opaque pointer per pbvh. See T47637. */ struct GridCommonGPUBuffer *grid_common_gpu_buffer; - /* The ccgdm is required for CD_ORIGINDEX lookup in vertex paint + multires */ - struct CCGDerivedMesh *ccgdm; /* Only used during BVH build and update, * don't need to remain valid after */ diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index f96868e99ea5..7311b17134d7 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -121,7 +121,7 @@ /* could be made into a pointcache option */ #define DURIAN_POINTCACHE_LIB_OK 1 -static int ptcache_data_size[] = { +static int ptcache_data_size[] = { sizeof(unsigned int), // BPHYS_DATA_INDEX 3 * sizeof(float), // BPHYS_DATA_LOCATION 3 * sizeof(float), // BPHYS_DATA_VELOCITY @@ -151,7 +151,7 @@ static int ptcache_basic_header_read(PTCacheFile *pf) /* Custom functions should read these basic elements too! */ if (!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) error = 1; - + if (!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) error = 1; @@ -162,7 +162,7 @@ static int ptcache_basic_header_write(PTCacheFile *pf) /* Custom functions should write these basic elements too! */ if (!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) return 0; - + if (!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) return 0; @@ -240,7 +240,7 @@ void BKE_ptcache_make_particle_key(ParticleKey *key, int index, void **data, flo { PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, index, key->co); PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, index, key->vel); - + /* no rotation info, so make something nice up */ if (data[BPHYS_DATA_ROTATION]==NULL) { vec_to_quat(key->rot, key->vel, OB_NEGX, OB_POSZ); @@ -316,7 +316,7 @@ static void ptcache_particle_read(int index, void *psys_v, void **data, float cf if (data[BPHYS_DATA_SIZE]) { PTCACHE_DATA_TO(data, BPHYS_DATA_SIZE, 0, &pa->size); } - + if (data[BPHYS_DATA_TIMES]) { float times[3]; PTCACHE_DATA_TO(data, BPHYS_DATA_TIMES, 0, ×); @@ -494,7 +494,7 @@ static void ptcache_cloth_read(int index, void *cloth_v, void **data, float UNUS ClothModifierData *clmd= cloth_v; Cloth *cloth= clmd->clothObject; ClothVertex *vert = cloth->verts + index; - + if (old_data) { memcpy(vert->x, data, 3 * sizeof(float)); memcpy(vert->xconst, data + 3, 3 * sizeof(float)); @@ -560,7 +560,7 @@ static int ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra)) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; - + if (sds->fluid) { return sds->base_res[0]*sds->base_res[1]*sds->base_res[2]; } @@ -577,7 +577,7 @@ static void ptcache_smoke_error(void *smoke_v, const char *message) #define SMOKE_CACHE_VERSION "1.04" static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) -{ +{ SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; int ret = 0; @@ -589,7 +589,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_write(pf, &sds->active_fields, 1, sizeof(int)); ptcache_file_write(pf, &sds->res, 3, sizeof(int)); ptcache_file_write(pf, &sds->dx, 1, sizeof(float)); - + if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; @@ -636,7 +636,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_write(pf, &sds->active_color, 3, sizeof(float)); MEM_freeN(out); - + ret = 1; } @@ -679,7 +679,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_compressed_write(pf, (unsigned char *)tcv, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)tcw, in_len, out, mode); MEM_freeN(out); - + ret = 1; } @@ -691,7 +691,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; - + if (sds->fluid) { const size_t res = sds->res[0] * sds->res[1] * sds->res[2]; const unsigned int out_len = (unsigned int)res * sizeof(float); @@ -705,7 +705,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) sds->active_color[0] = 0.7f; sds->active_color[1] = 0.7f; sds->active_color[2] = 0.7f; - + smoke_export(sds->fluid, &dt, &dx, &dens, NULL, NULL, NULL, &heat, &heatold, &vx, &vy, &vz, NULL, NULL, NULL, &obstacles); ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len); @@ -758,7 +758,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) } } - return 1; + return 1; } static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) @@ -814,13 +814,13 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) smoke_reallocate_highres_fluid(sds, ch_dx, ch_res, 1); } } - + if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; unsigned char *obstacles; unsigned int out_len = (unsigned int)res * sizeof(float); - + smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles); ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len); @@ -1195,7 +1195,7 @@ static void ptcache_dynamicpaint_error(void *UNUSED(sd), const char *UNUSED(mess #define DPAINT_CACHE_VERSION "1.01" static int ptcache_dynamicpaint_write(PTCacheFile *pf, void *dp_v) -{ +{ DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v; int cache_compress = 1; @@ -1237,7 +1237,7 @@ static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v) { DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v; char version[4]; - + /* version header */ ptcache_file_read(pf, version, 1, sizeof(char) * 4); if (!STREQLEN(version, DPAINT_CACHE_VERSION, 4)) { @@ -1282,13 +1282,13 @@ static int ptcache_rigidbody_write(int index, void *rb_v, void **data, int UNUS { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { #ifdef WITH_BULLET RB_body_get_position(rbo->physics_object, rbo->pos); @@ -1305,15 +1305,15 @@ static void ptcache_rigidbody_read(int index, void *rb_v, void **data, float UNU { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { - + if (old_data) { memcpy(rbo->pos, data, 3 * sizeof(float)); memcpy(rbo->orn, data + 3, 4 * sizeof(float)); @@ -1329,23 +1329,23 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { ParticleKey keys[4]; ParticleKey result; float dfra; - + memset(keys, 0, sizeof(keys)); - + copy_v3_v3(keys[1].co, rbo->pos); copy_qt_qt(keys[1].rot, rbo->orn); - + if (old_data) { memcpy(keys[2].co, data, 3 * sizeof(float)); memcpy(keys[2].rot, data + 3, 4 * sizeof(float)); @@ -1353,13 +1353,13 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl else { BKE_ptcache_make_particle_key(&keys[2], 0, data, cfra2); } - + dfra = cfra2 - cfra1; - + /* note: keys[0] and keys[3] unused for type < 1 (crappy) */ psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, &result, true); interp_qt_qtqt(result.rot, keys[1].rot, keys[2].rot, (cfra - cfra1) / dfra); - + copy_v3_v3(rbo->pos, result.co); copy_qt_qt(rbo->orn, result.rot); } @@ -1368,7 +1368,7 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl static int ptcache_rigidbody_totpoint(void *rb_v, int UNUSED(cfra)) { RigidBodyWorld *rbw = rb_v; - + return rbw->numbodies; } @@ -1525,7 +1525,7 @@ void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeMo pid->ob= ob; pid->calldata= smd; - + pid->type= PTCACHE_TYPE_SMOKE_DOMAIN; pid->stack_index= sds->point_cache[0]->index; @@ -1609,9 +1609,9 @@ void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, Object *ob, DynamicPaintSu void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, Object *ob, RigidBodyWorld *rbw) { - + memset(pid, 0, sizeof(PTCacheID)); - + pid->ob= ob; pid->calldata= rbw; pid->type= PTCACHE_TYPE_RIGIDBODY; @@ -1620,29 +1620,29 @@ void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, Object *ob, RigidBodyWorld *r pid->ptcaches= &rbw->ptcaches; pid->totpoint= pid->totwrite= ptcache_rigidbody_totpoint; pid->error = ptcache_rigidbody_error; - + pid->write_point = ptcache_rigidbody_write; pid->read_point = ptcache_rigidbody_read; pid->interpolate_point = ptcache_rigidbody_interpolate; - + pid->write_stream = NULL; pid->read_stream = NULL; pid->write_openvdb_stream = NULL; pid->read_openvdb_stream = NULL; - + pid->write_extra_data = NULL; pid->read_extra_data = NULL; pid->interpolate_extra_data = NULL; - + pid->write_header = ptcache_basic_header_write; pid->read_header = ptcache_basic_header_read; - + pid->data_types= (1<info_types= 0; - + pid->stack_index = pid->cache->index; - + pid->default_step = 1; pid->max_step = 1; pid->file_type = PTCACHE_FILE_PTCACHE; @@ -1665,7 +1665,7 @@ void BKE_ptcache_ids_from_object(Main *bmain, ListBase *lb, Object *ob, Scene *s for (psys=ob->particlesystem.first; psys; psys=psys->next) { if (psys->part==NULL) continue; - + /* check to make sure point cache is actually used by the particles */ if (ELEM(psys->part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) continue; @@ -1673,7 +1673,7 @@ void BKE_ptcache_ids_from_object(Main *bmain, ListBase *lb, Object *ob, Scene *s /* hair needs to be included in id-list for cache edit mode to work */ /* if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DYNAMICS)==0) */ /* continue; */ - + if (psys->part->type == PART_FLUID) continue; @@ -1709,7 +1709,7 @@ void BKE_ptcache_ids_from_object(Main *bmain, ListBase *lb, Object *ob, Scene *s } } } - + if (scene && ob->rigidbody_object && scene->rigidbody_world) { pid = MEM_callocN(sizeof(PTCacheID), "PTCacheID"); BKE_ptcache_id_from_rigidbody(pid, ob, scene->rigidbody_world); @@ -1799,20 +1799,20 @@ static int ptcache_path(PTCacheID *pid, char *filename) BLI_split_file_part(blendfilename, file, sizeof(file)); i = strlen(file); - + /* remove .blend */ if (i > 6) file[i-6] = '\0'; - + BLI_snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */ BLI_path_abs(filename, blendfilename); return BLI_add_slash(filename); /* new strlen() */ } - + /* use the temp path. this is weak but better then not using point cache at all */ /* temporary directory is assumed to exist and ALWAYS has a trailing slash */ BLI_snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH, BKE_tempdir_session()); - + return BLI_add_slash(filename); /* new strlen() */ } @@ -1823,9 +1823,9 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p char *newname; filename[0] = '\0'; newname = filename; - + if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return 0; /* save blend file before using disk pointcache */ - + /* start with temp dir */ if (do_path) { len = ptcache_path(pid, filename); @@ -1841,8 +1841,8 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p } } else { - int temp = (int)strlen(pid->cache->name); - strcpy(newname, pid->cache->name); + int temp = (int)strlen(pid->cache->name); + strcpy(newname, pid->cache->name); newname+=temp; len += temp; } @@ -1864,7 +1864,7 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p } len += 16; } - + return len; /* make sure the above string is always 16 chars */ } @@ -1881,7 +1881,7 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) return NULL; #endif if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return NULL; /* save blend file before using disk pointcache */ - + ptcache_filename(pid, filename, cfra, 1, 1); if (mode==PTCACHE_FILE_READ) { @@ -1975,7 +1975,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns out_len= LZO_OUT_LEN(in_len); if (mode == 1) { LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS); - + r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem); if (!(r == LZO_E_OK) || (out_len >= in_len)) compressed = 0; @@ -1985,7 +1985,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns #endif #ifdef WITH_LZMA if (mode == 2) { - + r = LzmaCompress(out, &out_len, in, in_len, //assume sizeof(char)==1.... props, &sizeOfIt, 5, 1 << 24, 3, 0, 2, 32, 2); @@ -1995,7 +1995,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns compressed = 2; } #endif - + ptcache_file_write(pf, &compressed, 1, sizeof(unsigned char)); if (compressed) { unsigned int size = out_len; @@ -2031,18 +2031,18 @@ static int ptcache_file_data_read(PTCacheFile *pf) if ((pf->data_types & (1<cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_data_write(PTCacheFile *pf) -{ +{ int i; for (i=0; idata_types & (1<cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_header_begin_read(PTCacheFile *pf) @@ -2050,12 +2050,12 @@ static int ptcache_file_header_begin_read(PTCacheFile *pf) unsigned int typeflag=0; int error=0; char bphysics[8]; - + pf->data_types = 0; - + if (fread(bphysics, sizeof(char), 8, pf->fp) != 8) error = 1; - + if (!error && !STREQLEN(bphysics, "BPHYSICS", 8)) error = 1; @@ -2064,7 +2064,7 @@ static int ptcache_file_header_begin_read(PTCacheFile *pf) pf->type = (typeflag & PTCACHE_TYPEFLAG_TYPEMASK); pf->flag = (typeflag & PTCACHE_TYPEFLAG_FLAGMASK); - + /* if there was an error set file as it was */ if (error) fseek(pf->fp, 0, SEEK_SET); @@ -2075,13 +2075,13 @@ static int ptcache_file_header_begin_write(PTCacheFile *pf) { const char *bphysics = "BPHYSICS"; unsigned int typeflag = pf->type + pf->flag; - + if (fwrite(bphysics, sizeof(char), 8, pf->fp) != 8) return 0; if (!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp)) return 0; - + return 1; } @@ -2362,14 +2362,14 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) if (error && G.debug & G_DEBUG) printf("Error reading from disk cache\n"); - + return pm; } static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) { PTCacheFile *pf = NULL; unsigned int i, error = 0; - + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, pm->frame); pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, pm->frame); @@ -2384,10 +2384,10 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) pf->totpoint = pm->totpoint; pf->type = pid->type; pf->flag = 0; - + if (pm->extradata.first) pf->flag |= PTCACHE_TYPEFLAG_EXTRADATA; - + if (pid->cache->compression) pf->flag |= PTCACHE_TYPEFLAG_COMPRESS; @@ -2443,7 +2443,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) } ptcache_file_close(pf); - + if (error && G.debug & G_DEBUG) printf("Error writing to disk cache\n"); @@ -2492,7 +2492,7 @@ static int ptcache_read_stream(PTCacheID *pid, int cfra) } ptcache_file_close(pf); - + return error == 0; } @@ -2537,7 +2537,7 @@ static int ptcache_read(PTCacheID *pid, int cfra) } else { pm = pid->cache->mem_cache.first; - + while (pm && pm->frame != cfra) pm = pm->next; } @@ -2562,7 +2562,7 @@ static int ptcache_read(PTCacheID *pid, int cfra) index = pm->cur[BPHYS_DATA_INDEX]; pid->read_point(*index, pid->calldata, pm->cur, (float)pm->frame, NULL); - + BKE_ptcache_mem_pointers_incr(pm); } @@ -2591,7 +2591,7 @@ static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2) } else { pm = pid->cache->mem_cache.first; - + while (pm && pm->frame != cfra2) pm = pm->next; } @@ -2729,7 +2729,7 @@ static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint) { PTCacheFile *pf = NULL; int error = 0; - + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, cfra); pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, cfra); @@ -2801,7 +2801,7 @@ static int ptcache_write(PTCacheID *pid, int cfra, int overwrite) while (fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra)) fra--; - + pm2 = ptcache_disk_frame_to_mem(pid, fra); } else @@ -2949,7 +2949,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) unsigned int sta, end; /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -2977,117 +2977,116 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) /* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */ switch (mode) { - case PTCACHE_CLEAR_ALL: - case PTCACHE_CLEAR_BEFORE: - case PTCACHE_CLEAR_AFTER: - if (pid->cache->flag & PTCACHE_DISK_CACHE) { - ptcache_path(pid, path); - - dir = opendir(path); - if (dir==NULL) - return; - - len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */ - /* append underscore terminator to ensure we don't match similar names - * from objects whose names start with the same prefix - */ - if (len < sizeof(filename) - 2) { - BLI_strncpy(filename + len, "_", sizeof(filename) - 2 - len); - len += 1; - } - - BLI_snprintf(ext, sizeof(ext), "_%02u%s", pid->stack_index, fext); - - while ((de = readdir(dir)) != NULL) { - if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ - if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ - if (mode == PTCACHE_CLEAR_ALL) { - pid->cache->last_exact = MIN2(pid->cache->startframe, 0); - BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); - BLI_delete(path_full, false, false); - } - else { - /* read the number of the file */ - const int frame = ptcache_frame_from_filename(de->d_name, ext); - - if (frame != -1) { - if ((mode == PTCACHE_CLEAR_BEFORE && frame < cfra) || - (mode == PTCACHE_CLEAR_AFTER && frame > cfra)) - { - - BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); - BLI_delete(path_full, false, false); - if (pid->cache->cached_frames && frame >=sta && frame <= end) - pid->cache->cached_frames[frame-sta] = 0; + case PTCACHE_CLEAR_ALL: + case PTCACHE_CLEAR_BEFORE: + case PTCACHE_CLEAR_AFTER: + if (pid->cache->flag & PTCACHE_DISK_CACHE) { + ptcache_path(pid, path); + + dir = opendir(path); + if (dir==NULL) + return; + + len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */ + /* append underscore terminator to ensure we don't match similar names + * from objects whose names start with the same prefix + */ + if (len < sizeof(filename) - 2) { + BLI_strncpy(filename + len, "_", sizeof(filename) - 2 - len); + len += 1; + } + + BLI_snprintf(ext, sizeof(ext), "_%02u%s", pid->stack_index, fext); + + while ((de = readdir(dir)) != NULL) { + if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ + if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ + if (mode == PTCACHE_CLEAR_ALL) { + pid->cache->last_exact = MIN2(pid->cache->startframe, 0); + BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); + BLI_delete(path_full, false, false); + } + else { + /* read the number of the file */ + const int frame = ptcache_frame_from_filename(de->d_name, ext); + + if (frame != -1) { + if ((mode == PTCACHE_CLEAR_BEFORE && frame < cfra) || + (mode == PTCACHE_CLEAR_AFTER && frame > cfra)) + { + BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); + BLI_delete(path_full, false, false); + if (pid->cache->cached_frames && frame >=sta && frame <= end) + pid->cache->cached_frames[frame-sta] = 0; + } } } } } } - } - closedir(dir); + closedir(dir); - if (mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames) - memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); - } - else { - PTCacheMem *pm= pid->cache->mem_cache.first; - PTCacheMem *link= NULL; - - if (mode == PTCACHE_CLEAR_ALL) { - /*we want startframe if the cache starts before zero*/ - pid->cache->last_exact = MIN2(pid->cache->startframe, 0); - for (; pm; pm=pm->next) { - ptcache_data_free(pm); - ptcache_extra_free(pm); - } - BLI_freelistN(&pid->cache->mem_cache); - - if (pid->cache->cached_frames) + if (mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames) memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); } else { - while (pm) { - if ((mode == PTCACHE_CLEAR_BEFORE && pm->frame < cfra) || - (mode == PTCACHE_CLEAR_AFTER && pm->frame > cfra)) - { - link = pm; - if (pid->cache->cached_frames && pm->frame >=sta && pm->frame <= end) - pid->cache->cached_frames[pm->frame-sta] = 0; + PTCacheMem *pm= pid->cache->mem_cache.first; + PTCacheMem *link= NULL; + + if (mode == PTCACHE_CLEAR_ALL) { + /*we want startframe if the cache starts before zero*/ + pid->cache->last_exact = MIN2(pid->cache->startframe, 0); + for (; pm; pm=pm->next) { ptcache_data_free(pm); ptcache_extra_free(pm); - pm = pm->next; - BLI_freelinkN(&pid->cache->mem_cache, link); } - else - pm = pm->next; + BLI_freelistN(&pid->cache->mem_cache); + + if (pid->cache->cached_frames) + memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); + } + else { + while (pm) { + if ((mode == PTCACHE_CLEAR_BEFORE && pm->frame < cfra) || + (mode == PTCACHE_CLEAR_AFTER && pm->frame > cfra)) + { + link = pm; + if (pid->cache->cached_frames && pm->frame >=sta && pm->frame <= end) + pid->cache->cached_frames[pm->frame-sta] = 0; + ptcache_data_free(pm); + ptcache_extra_free(pm); + pm = pm->next; + BLI_freelinkN(&pid->cache->mem_cache, link); + } + else + pm = pm->next; + } } } - } - break; - - case PTCACHE_CLEAR_FRAME: - if (pid->cache->flag & PTCACHE_DISK_CACHE) { - if (BKE_ptcache_id_exist(pid, cfra)) { - ptcache_filename(pid, filename, cfra, 1, 1); /* no path */ - BLI_delete(filename, false, false); + break; + + case PTCACHE_CLEAR_FRAME: + if (pid->cache->flag & PTCACHE_DISK_CACHE) { + if (BKE_ptcache_id_exist(pid, cfra)) { + ptcache_filename(pid, filename, cfra, 1, 1); /* no path */ + BLI_delete(filename, false, false); + } } - } - else { - PTCacheMem *pm = pid->cache->mem_cache.first; + else { + PTCacheMem *pm = pid->cache->mem_cache.first; - for (; pm; pm=pm->next) { - if (pm->frame == cfra) { - ptcache_data_free(pm); - ptcache_extra_free(pm); - BLI_freelinkN(&pid->cache->mem_cache, pm); - break; + for (; pm; pm=pm->next) { + if (pm->frame == cfra) { + ptcache_data_free(pm); + ptcache_extra_free(pm); + BLI_freelinkN(&pid->cache->mem_cache, pm); + break; + } } } - } - if (pid->cache->cached_frames && cfra >= sta && cfra <= end) - pid->cache->cached_frames[cfra-sta] = 0; - break; + if (pid->cache->cached_frames && cfra >= sta && cfra <= end) + pid->cache->cached_frames[cfra-sta] = 0; + break; } BKE_ptcache_update_info(pid); @@ -3102,10 +3101,10 @@ int BKE_ptcache_id_exist(PTCacheID *pid, int cfra) if (pid->cache->cached_frames && pid->cache->cached_frames[cfra-pid->cache->startframe]==0) return 0; - + if (pid->cache->flag & PTCACHE_DISK_CACHE) { char filename[MAX_PTCACHE_FILE]; - + ptcache_filename(pid, filename, cfra, 1, 1); return BLI_exists(filename); @@ -3145,7 +3144,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra if (timescale) { time= BKE_scene_frame_get(scene); nexttime = BKE_scene_frame_get_from_ctime(scene, CFRA + 1.0f); - + *timescale= MAX2(nexttime - time, 0.0f); } @@ -3183,7 +3182,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra if (pid->cache->flag & PTCACHE_DISK_CACHE) { /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -3191,9 +3190,9 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra unsigned int len; /* store the length of the string */ ptcache_path(pid, path); - + len = ptcache_filename(pid, filename, (int)cfra, 0, 0); /* no path */ - + dir = opendir(path); if (dir==NULL) return; @@ -3201,7 +3200,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra const char *fext = ptcache_file_extension(pid); BLI_snprintf(ext, sizeof(ext), "_%02u%s", pid->stack_index, fext); - + while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ @@ -3309,7 +3308,7 @@ int BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode) /* particles or cloth in that case -jahka */ else if (psys->clmd) { BKE_ptcache_id_from_cloth(&pid, ob, psys->clmd); - if (mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) + if (mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) reset |= BKE_ptcache_id_reset(scene, &pid, mode); else skip = 1; @@ -3366,19 +3365,19 @@ void BKE_ptcache_remove(void) char path[MAX_PTCACHE_PATH]; char path_full[MAX_PTCACHE_PATH]; int rmdir = 1; - + ptcache_path(NULL, path); if (BLI_exists(path)) { /* The pointcache dir exists? - remove all pointcache */ - DIR *dir; + DIR *dir; struct dirent *de; dir = opendir(path); if (dir==NULL) return; - + while ((de = readdir(dir)) != NULL) { if (FILENAME_IS_CURRPAR(de->d_name)) { /* do nothing */ @@ -3397,7 +3396,7 @@ void BKE_ptcache_remove(void) else { rmdir = 0; /* path dosnt exist */ } - + if (rmdir) { BLI_delete(path, true, false); } @@ -3507,7 +3506,7 @@ PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcach return ptcaches_new->first; } -/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on +/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on * every user action changing stuff, and then it runs a complete bake??? (ton) */ /* Baking */ @@ -3553,7 +3552,7 @@ void BKE_ptcache_bake(PTCacheBaker *baker) int startframe = MAXFRAME, endframe = baker->anim_init ? scene->r.sfra : CFRA; int bake = baker->bake; int render = baker->render; - + G.is_break = false; /* set caches to baking mode and figure out start frame */ @@ -3745,7 +3744,7 @@ void BKE_ptcache_bake(PTCacheBaker *baker) scene->r.framelen = frameleno; CFRA = cfrao; - + if (bake) { /* already on cfra unless baking */ BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay); } @@ -3827,7 +3826,7 @@ void BKE_ptcache_toggle_disk_cache(PTCacheID *pid) cache->flag ^= PTCACHE_DISK_CACHE; BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); cache->flag ^= PTCACHE_DISK_CACHE; - + cache->last_exact = last_exact; BKE_ptcache_id_time(pid, NULL, 0.0f, NULL, NULL, NULL); @@ -3847,7 +3846,7 @@ void BKE_ptcache_disk_cache_rename(PTCacheID *pid, const char *name_src, const c char old_name[80]; int len; /* store the length of the string */ /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char old_filename[MAX_PTCACHE_FILE]; @@ -3906,7 +3905,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) int end = -1; /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -3916,9 +3915,9 @@ void BKE_ptcache_load_external(PTCacheID *pid) return; ptcache_path(pid, path); - + len = ptcache_filename(pid, filename, 1, 0, 0); /* no path */ - + dir = opendir(path); if (dir==NULL) return; @@ -3929,7 +3928,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) BLI_snprintf(ext, sizeof(ext), "_%02d%s", cache->index, fext); else BLI_strncpy(ext, fext, sizeof(ext)); - + while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ @@ -3985,7 +3984,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) if (pf) { while (ptcache_file_read(pf, old_data, 1, elemsize)) cache->totpoint++; - + ptcache_file_close(pf); } } @@ -4063,7 +4062,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) } bytes += sizeof(PTCacheMem); - + totframes++; } diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c index b163f623d215..cb297744ab88 100644 --- a/source/blender/blenkernel/intern/property.c +++ b/source/blender/blenkernel/intern/property.c @@ -50,10 +50,10 @@ void BKE_bproperty_free(bProperty *prop) { - + if (prop->poin && prop->poin != &prop->data) MEM_freeN(prop->poin); MEM_freeN(prop); - + } void BKE_bproperty_free_list(ListBase *lb) @@ -68,7 +68,7 @@ void BKE_bproperty_free_list(ListBase *lb) bProperty *BKE_bproperty_copy(const bProperty *prop) { bProperty *propn; - + propn = MEM_dupallocN(prop); if (prop->poin && prop->poin != &prop->data) { propn->poin = MEM_dupallocN(prop->poin); @@ -90,19 +90,19 @@ void BKE_bproperty_copy_list(ListBase *lbn, const ListBase *lbo) BLI_addtail(lbn, propn); prop = prop->next; } - - + + } void BKE_bproperty_init(bProperty *prop) { /* also use when property changes type */ - + if (prop->poin && prop->poin != &prop->data) MEM_freeN(prop->poin); prop->poin = NULL; - + prop->data = 0; - + switch (prop->type) { case GPROP_BOOL: case GPROP_INT: @@ -125,7 +125,7 @@ bProperty *BKE_bproperty_new(int type) prop->type = type; BKE_bproperty_init(prop); - + strcpy(prop->name, "prop"); return prop; @@ -156,7 +156,7 @@ int BKE_bproperty_cmp(bProperty *prop, const char *str) { // extern int Gdfra; /* sector.c */ float fvalue, ftest; - + switch (prop->type) { case GPROP_BOOL: if (BLI_strcasecmp(str, "true") == 0) { @@ -168,7 +168,7 @@ int BKE_bproperty_cmp(bProperty *prop, const char *str) else return 1; } /* no break, do GPROP_int too! */ - + case GPROP_INT: return prop->data - atoi(str); @@ -185,7 +185,7 @@ int BKE_bproperty_cmp(bProperty *prop, const char *str) case GPROP_STRING: return strcmp(prop->poin, str); } - + return 0; } #endif @@ -211,7 +211,7 @@ void BKE_bproperty_set(bProperty *prop, const char *str) strcpy(prop->poin, str); /* TODO - check size? */ break; } - + } void BKE_bproperty_add(bProperty *prop, const char *str) diff --git a/source/blender/blenkernel/intern/python_component.c b/source/blender/blenkernel/intern/python_component.c index 7744acf41564..803395cc1b43 100644 --- a/source/blender/blenkernel/intern/python_component.c +++ b/source/blender/blenkernel/intern/python_component.c @@ -537,7 +537,7 @@ PythonComponent *BKE_python_component_create_file(char *import, ReportList *repo } strcpy(filename, modulename); - BLI_ensure_extension(filename, FILE_MAX, ".py"); + BLI_path_extension_ensure(filename, FILE_MAX, ".py"); if (BLI_findstring(&maggie->text, filename, offsetof(ID, name) + 2)) { BKE_reportf(reports, RPT_ERROR_INVALID_INPUT, "File %s already exists.", filename); diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c index 67b076c0153b..a9b36a856026 100644 --- a/source/blender/blenkernel/intern/report.c +++ b/source/blender/blenkernel/intern/report.c @@ -270,10 +270,10 @@ char *BKE_reports_string(ReportList *reports, ReportType level) void BKE_reports_print(ReportList *reports, ReportType level) { char *cstring = BKE_reports_string(reports, level); - + if (cstring == NULL) return; - + puts(cstring); fflush(stdout); MEM_freeN(cstring); @@ -282,12 +282,12 @@ void BKE_reports_print(ReportList *reports, ReportType level) Report *BKE_reports_last_displayable(ReportList *reports) { Report *report; - + for (report = reports->list.last; report; report = report->prev) { if (ELEM(report->type, RPT_ERROR, RPT_WARNING, RPT_INFO)) return report; } - + return NULL; } diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index ecb8814dd70a..bfc617949359 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -286,7 +286,7 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) int totvert; int tottri; const MLoop *mloop; - + dm = rigidbody_get_mesh(ob); /* ensure mesh validity, then grab data */ @@ -309,7 +309,7 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) /* init mesh data for collision shape */ mdata = RB_trimesh_data_new(tottri, totvert); - + RB_trimesh_add_vertices(mdata, (float *)mvert, totvert, sizeof(MVert)); /* loop over all faces, adding them as triangles to the collision shape @@ -328,7 +328,7 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) RB_trimesh_add_triangle_indices(mdata, i, UNPACK3(vtri)); } } - + RB_trimesh_finish(mdata); /* construct collision shape @@ -519,21 +519,21 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) const MLoopTri *lt = NULL; int totvert, tottri = 0; const MLoop *mloop = NULL; - + /* ensure mesh validity, then grab data */ if (dm == NULL) return; - + mvert = dm->getVertArray(dm); totvert = dm->getNumVerts(dm); lt = dm->getLoopTriArray(dm); tottri = dm->getNumLoopTri(dm); mloop = dm->getLoopArray(dm); - + if (totvert > 0 && tottri > 0) { BKE_mesh_calc_volume(mvert, totvert, lt, tottri, mloop, &volume, NULL); } - + /* cleanup temp data */ if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { dm->release(dm); @@ -602,21 +602,21 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) const MLoopTri *looptri; int totvert, tottri; const MLoop *mloop; - + /* ensure mesh validity, then grab data */ if (dm == NULL) return; - + mvert = dm->getVertArray(dm); totvert = dm->getNumVerts(dm); looptri = dm->getLoopTriArray(dm); tottri = dm->getNumLoopTri(dm); mloop = dm->getLoopArray(dm); - + if (totvert > 0 && tottri > 0) { BKE_mesh_calc_volume(mvert, totvert, looptri, tottri, mloop, NULL, r_center); } - + /* cleanup temp data */ if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { dm->release(dm); @@ -700,7 +700,36 @@ static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool /* --------------------- */ -static void rigidbody_constraint_set_limits(RigidBodyCon *rbc, void (*set_limits)(rbConstraint*,int,float,float)) +static void rigidbody_constraint_init_spring( + RigidBodyCon *rbc, void (*set_spring)(rbConstraint *, int, int), + void (*set_stiffness)(rbConstraint *, int, float), void (*set_damping)(rbConstraint *, int, float)) +{ + set_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X); + set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x); + set_damping(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x); + + set_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y); + set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y); + set_damping(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y); + + set_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z); + set_stiffness(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z); + set_damping(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z); + + set_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->flag & RBC_FLAG_USE_SPRING_ANG_X); + set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_stiffness_ang_x); + set_damping(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_damping_ang_x); + + set_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y); + set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_stiffness_ang_y); + set_damping(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_damping_ang_y); + + set_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z); + set_stiffness(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_stiffness_ang_z); + set_damping(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z); +} + +static void rigidbody_constraint_set_limits(RigidBodyCon *rbc, void (*set_limits)(rbConstraint *, int, float, float)) { if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper); @@ -824,35 +853,24 @@ static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, b RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper); break; case RBC_TYPE_6DOF_SPRING: - rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2); - - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x); + if (rbc->spring_type == RBC_SPRING_TYPE2) { + rbc->physics_constraint = RB_constraint_new_6dof_spring2(loc, rot, rb1, rb2); - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y); + rigidbody_constraint_init_spring(rbc, RB_constraint_set_spring_6dof_spring2, RB_constraint_set_stiffness_6dof_spring2, RB_constraint_set_damping_6dof_spring2); - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z); + RB_constraint_set_equilibrium_6dof_spring2(rbc->physics_constraint); - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->flag & RBC_FLAG_USE_SPRING_ANG_X); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_stiffness_ang_x); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_damping_ang_x); - - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_stiffness_ang_y); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_damping_ang_y); + rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring2); + } + else { + rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2); - RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z); - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_stiffness_ang_z); - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z); + rigidbody_constraint_init_spring(rbc, RB_constraint_set_spring_6dof_spring, RB_constraint_set_stiffness_6dof_spring, RB_constraint_set_damping_6dof_spring); - RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint); + RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint); - rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring); + rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof); + } break; case RBC_TYPE_6DOF: rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2); @@ -1071,6 +1089,8 @@ RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short ty rbc->flag |= RBC_FLAG_ENABLED; rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS; + rbc->spring_type = RBC_SPRING_TYPE2; + rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */ rbc->num_solver_iterations = 10; /* 10 is Bullet default */ @@ -1332,7 +1352,7 @@ static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, bool /* XXX TODO For rebuild: remove all constraints first. * Otherwise we can end up deleting objects that are still * referenced by constraints, corrupting bullet's internal list. - * + * * Memory management needs redesign here, this is just a dirty workaround. */ if (rebuild && rbw->constraints) { @@ -1394,7 +1414,7 @@ static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, bool rigidbody_update_sim_ob(scene, rbw, ob, rbo); } } - + /* update constraints */ if (rbw->constraints == NULL) /* no constraints, move on */ return; diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c index 22885517fe46..711c4ed8c264 100644 --- a/source/blender/blenkernel/intern/sca.c +++ b/source/blender/blenkernel/intern/sca.c @@ -60,13 +60,13 @@ void free_sensor(bSensor *sens) if (sens->links) MEM_freeN(sens->links); if (sens->data) MEM_freeN(sens->data); MEM_freeN(sens); - + } void free_sensors(ListBase *lb) { bSensor *sens; - + while ((sens = BLI_pophead(lb))) { free_sensor(sens); } @@ -75,7 +75,7 @@ void free_sensors(ListBase *lb) bSensor *copy_sensor(bSensor *sens, const int UNUSED(flag)) { bSensor *sensn; - + sensn= MEM_dupallocN(sens); sensn->flag |= SENS_NEW; if (sens->data) { @@ -83,14 +83,14 @@ bSensor *copy_sensor(bSensor *sens, const int UNUSED(flag)) } if (sens->links) sensn->links= MEM_dupallocN(sens->links); - + return sensn; } void copy_sensors(ListBase *lbn, const ListBase *lbo, const int flag) { bSensor *sens, *sensn; - + lbn->first= lbn->last= NULL; sens= lbo->first; while (sens) { @@ -108,11 +108,11 @@ void init_sensor(bSensor *sens) bJoystickSensor *js; bRaySensor *rs; bMovementSensor *movs; - + if (sens->data) MEM_freeN(sens->data); sens->data= NULL; sens->pulse = 0; - + switch (sens->type) { case SENS_ALWAYS: sens->pulse = 0; @@ -186,12 +186,12 @@ bSensor *new_sensor(int type) sens= MEM_callocN(sizeof(bSensor), "Sensor"); sens->type= type; sens->flag= SENS_SHOW; - + init_sensor(sens); - + strcpy(sens->name, "sensor"); // XXX make_unique_prop_names(sens->name); - + return sens; } @@ -201,7 +201,7 @@ void unlink_controller(bController *cont) { bSensor *sens; Object *ob; - + /* check for controller pointers in sensors */ ob= G.main->object.first; while (ob) { @@ -217,7 +217,7 @@ void unlink_controller(bController *cont) void unlink_controllers(ListBase *lb) { bController *cont; - + for (cont= lb->first; cont; cont= cont->next) unlink_controller(cont); } @@ -229,13 +229,13 @@ void free_controller(bController *cont) /* the controller itself */ if (cont->data) MEM_freeN(cont->data); MEM_freeN(cont); - + } void free_controllers(ListBase *lb) { bController *cont; - + while ((cont = BLI_pophead(lb))) { if (cont->slinks) MEM_freeN(cont->slinks); @@ -246,7 +246,7 @@ void free_controllers(ListBase *lb) bController *copy_controller(bController *cont, const int UNUSED(flag)) { bController *contn; - + cont->mynew=contn= MEM_dupallocN(cont); contn->flag |= CONT_NEW; if (cont->data) { @@ -256,14 +256,14 @@ bController *copy_controller(bController *cont, const int UNUSED(flag)) if (cont->links) contn->links= MEM_dupallocN(cont->links); contn->slinks= NULL; contn->totslinks= 0; - + return contn; } void copy_controllers(ListBase *lbn, const ListBase *lbo, const int flag) { bController *cont, *contn; - + lbn->first= lbn->last= NULL; cont= lbo->first; while (cont) { @@ -276,10 +276,10 @@ void copy_controllers(ListBase *lbn, const ListBase *lbo, const int flag) void init_controller(bController *cont) { /* also use when controller changes type, leave actuators... */ - + if (cont->data) MEM_freeN(cont->data); cont->data= NULL; - + switch (cont->type) { case CONT_EXPRESSION: cont->data= MEM_callocN(sizeof(bExpressionCont), "expcont"); @@ -299,10 +299,10 @@ bController *new_controller(int type) cont->flag= CONT_SHOW; init_controller(cont); - + strcpy(cont->name, "cont"); // XXX make_unique_prop_names(cont->name); - + return cont; } @@ -312,7 +312,7 @@ void unlink_actuator(bActuator *act) { bController *cont; Object *ob; - + /* check for actuator pointers in controllers */ ob= G.main->object.first; while (ob) { @@ -328,7 +328,7 @@ void unlink_actuator(bActuator *act) void unlink_actuators(ListBase *lb) { bActuator *act; - + for (act= lb->first; act; act= act->next) unlink_actuator(act); } @@ -361,7 +361,7 @@ void free_actuator(bActuator *act) void free_actuators(ListBase *lb) { bActuator *act; - + while ((act = BLI_pophead(lb))) { free_actuator(act); } @@ -370,13 +370,13 @@ void free_actuators(ListBase *lb) bActuator *copy_actuator(bActuator *act, const int flag) { bActuator *actn; - + act->mynew=actn= MEM_dupallocN(act); actn->flag |= ACT_NEW; if (act->data) { actn->data= MEM_dupallocN(act->data); } - + switch (act->type) { case ACT_ACTION: { @@ -401,7 +401,7 @@ bActuator *copy_actuator(bActuator *act, const int flag) void copy_actuators(ListBase *lbn, const ListBase *lbo, const int flag) { bActuator *act, *actn; - + lbn->first= lbn->last= NULL; act= lbo->first; while (act) { @@ -423,10 +423,10 @@ void init_actuator(bActuator *act) bMouseActuator *ma; bEditObjectActuator *eoa; bVibrationActuator *via; - + if (act->data) MEM_freeN(act->data); act->data= NULL; - + switch (act->type) { case ACT_ACTION: act->data= MEM_callocN(sizeof(bActionActuator), "actionact"); @@ -536,12 +536,12 @@ bActuator *new_actuator(int type) act= MEM_callocN(sizeof(bActuator), "Actuator"); act->type= type; act->flag= ACT_SHOW; - + init_actuator(act); - + strcpy(act->name, "act"); // XXX make_unique_prop_names(act->name); - + return act; } @@ -551,7 +551,7 @@ void clear_sca_new_poins_ob(Object *ob) bSensor *sens; bController *cont; bActuator *act; - + sens= ob->sensors.first; while (sens) { sens->flag &= ~SENS_NEW; @@ -574,7 +574,7 @@ void clear_sca_new_poins_ob(Object *ob) void clear_sca_new_poins(void) { Object *ob; - + ob= G.main->object.first; while (ob) { clear_sca_new_poins_ob(ob); @@ -588,7 +588,7 @@ void set_sca_new_poins_ob(Object *ob) bController *cont; bActuator *act; int a; - + sens= ob->sensors.first; while (sens) { if (sens->flag & SENS_NEW) { @@ -610,8 +610,8 @@ void set_sca_new_poins_ob(Object *ob) } cont= cont->next; } - - + + act= ob->actuators.first; while (act) { if (act->flag & ACT_NEW) { @@ -662,7 +662,7 @@ void set_sca_new_poins_ob(Object *ob) void set_sca_new_poins(void) { Object *ob; - + ob= G.main->object.first; while (ob) { set_sca_new_poins_ob(ob); @@ -885,7 +885,7 @@ void sca_move_controller(bController *cont_to_move, Object *ob, int move_up) /* locate the controller that has the same state mask but is earlier in the list */ tmp = cont->prev; while (tmp) { - if (tmp->state_mask & cont->state_mask) + if (tmp->state_mask & cont->state_mask) break; tmp = tmp->prev; } @@ -899,7 +899,7 @@ void sca_move_controller(bController *cont_to_move, Object *ob, int move_up) else if (val == 2 && cont->next) { tmp = cont->next; while (tmp) { - if (tmp->state_mask & cont->state_mask) + if (tmp->state_mask & cont->state_mask) break; tmp = tmp->next; } @@ -952,7 +952,7 @@ void sca_move_actuator(bActuator *act_to_move, Object *ob, int move_up) void link_logicbricks(void **poin, void ***ppoin, short *tot, short size) { void **old_links= NULL; - + int ibrick; /* check if the bricks are already linked */ @@ -966,7 +966,7 @@ void link_logicbricks(void **poin, void ***ppoin, short *tot, short size) (*tot) ++; *ppoin = MEM_callocN((*tot)*size, "new link"); - + for (ibrick=0; ibrick < *(tot) - 1; ibrick++) { (*ppoin)[ibrick] = old_links[ibrick]; } @@ -1191,4 +1191,3 @@ const char *sca_state_name_get(Object *ob, short bit) } return NULL; } - diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 323a98e53663..d48cf1909c6c 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -133,10 +133,10 @@ static void remove_sequencer_fcurves(Scene *sce) if (adt && adt->action) { FCurve *fcu, *nextfcu; - + for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) { nextfcu = fcu->next; - + if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) { action_groups_remove_channel(adt->action, fcu); free_fcurve(fcu); @@ -501,14 +501,14 @@ void BKE_scene_free(Scene *sce) BLI_freelistN(&sce->transform_spaces); BLI_freelistN(&sce->r.layers); BLI_freelistN(&sce->r.views); - + BKE_toolsettings_free(sce->toolsettings); sce->toolsettings = NULL; - + DAG_scene_free(sce); if (sce->depsgraph) DEG_graph_free(sce->depsgraph); - + MEM_SAFE_FREE(sce->stats); MEM_SAFE_FREE(sce->fps_info); @@ -531,7 +531,7 @@ void BKE_scene_init(Scene *sce) BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id)); sce->lay = sce->layact = 1; - + sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE; sce->r.cfra = 1; sce->r.sfra = 1; @@ -571,7 +571,7 @@ void BKE_scene_init(Scene *sce) sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT; sce->r.gauss = 1.0; - + /* deprecated but keep for upwards compat */ sce->r.postgamma = 1.0; sce->r.posthue = 0.0; @@ -628,7 +628,7 @@ void BKE_scene_init(Scene *sce) sce->r.border.ymax = 1.0f; sce->r.preview_start_resolution = 64; - + sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE; sce->r.unit_line_thickness = 1.0f; @@ -813,22 +813,22 @@ void BKE_scene_init(Scene *sce) copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f); sce->preview = NULL; - + /* GP Sculpt brushes */ { GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt; GP_EditBrush_Data *gp_brush; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH]; gp_brush->size = 25; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS]; gp_brush->size = 25; gp_brush->strength = 0.5f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH]; gp_brush->size = 25; gp_brush->strength = 0.5f; @@ -838,28 +838,28 @@ void BKE_scene_init(Scene *sce) gp_brush->size = 50; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH]; gp_brush->size = 25; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST]; gp_brush->size = 50; gp_brush->strength = 0.3f; // XXX? gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH]; gp_brush->size = 50; gp_brush->strength = 0.5f; // XXX? gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE]; gp_brush->size = 25; gp_brush->strength = 0.5f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; } - + /* GP Stroke Placement */ sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE; sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE; @@ -911,10 +911,10 @@ void BKE_scene_set_background(Main *bmain, Scene *scene) Group *group; GroupObject *go; int flag; - + /* check for cyclic sets, for reading old files but also for definite security (py?) */ BKE_scene_validate_setscene(bmain, scene); - + /* can happen when switching modes in other scenes */ if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT)) scene->obedit = NULL; @@ -940,12 +940,12 @@ void BKE_scene_set_background(Main *bmain, Scene *scene) for (base = scene->base.first; base; base = base->next) { ob = base->object; ob->lay = base->lay; - + /* group patch... */ base->flag &= ~(OB_FROMGROUP); flag = ob->flag & (OB_FROMGROUP); base->flag |= flag; - + /* not too nice... for recovering objects with lost data */ //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE; ob->flag = base->flag; @@ -972,7 +972,7 @@ int BKE_scene_base_iter_next(Main *bmain, EvaluationContext *eval_ctx, SceneBase Scene **scene, int val, Base **base, Object **ob) { bool run_again = true; - + /* init */ if (val == 0) { iter->phase = F_START; @@ -1026,19 +1026,19 @@ int BKE_scene_base_iter_next(Main *bmain, EvaluationContext *eval_ctx, SceneBase } } } - + if (*base == NULL) { iter->phase = F_START; } else { if (iter->phase != F_DUPLI) { if ( (*base)->object->transflag & OB_DUPLI) { - /* groups cannot be duplicated for mballs yet, - * this enters eternal loop because of + /* groups cannot be duplicated for mballs yet, + * this enters eternal loop because of * makeDispListMBall getting called inside of group_duplilist */ if ((*base)->object->dup_group == NULL) { iter->duplilist = object_duplilist_ex(bmain, eval_ctx, (*scene), (*base)->object, false); - + iter->dupob = iter->duplilist->first; if (!iter->dupob) { @@ -1071,13 +1071,13 @@ int BKE_scene_base_iter_next(Main *bmain, EvaluationContext *eval_ctx, SceneBase else if (iter->phase == F_DUPLI) { iter->phase = F_SCENE; (*base)->flag &= ~OB_FROMDUPLI; - + if (iter->dupli_refob) { /* Restore last object's real matrix. */ copy_m4_m4(iter->dupli_refob->obmat, iter->omat); iter->dupli_refob = NULL; } - + free_object_duplilist(iter->duplilist); iter->duplilist = NULL; run_again = true; @@ -1098,7 +1098,7 @@ int BKE_scene_base_iter_next(Main *bmain, EvaluationContext *eval_ctx, SceneBase Object *BKE_scene_camera_find(Scene *sc) { Base *base; - + for (base = sc->base.first; base; base = base->next) if (base->object->type == OB_CAMERA) return base->object; @@ -1203,6 +1203,16 @@ char *BKE_scene_find_last_marker_name(Scene *scene, int frame) return best_marker ? best_marker->name : NULL; } +int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int cfra) +{ + const int fps = round_db_to_int(FPS * interval_in_seconds); + const int second_prev = cfra - mod_i(cfra, fps); + const int second_next = second_prev + fps; + const int delta_prev = cfra - second_prev; + const int delta_next = second_next - cfra; + return (delta_prev < delta_next) ? second_prev : second_next; +} + Base *BKE_scene_base_add(Scene *sce, Object *ob) { @@ -1224,7 +1234,7 @@ void BKE_scene_base_unlink(Scene *sce, Base *base) /* remove rigid body object from world before removing object */ if (base->object->rigidbody_object) BKE_rigidbody_remove_object(sce, base->object); - + BLI_remlink(&sce->base, base); if (sce->basact == base) sce->basact = NULL; @@ -1256,7 +1266,7 @@ bool BKE_scene_validate_setscene(Main *bmain, Scene *sce) if (sce->set == NULL) return true; totscene = BLI_listbase_count(&bmain->scene); - + for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) { /* more iterations than scenes means we have a cycle */ if (a > totscene) { @@ -1283,7 +1293,7 @@ float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame) float ctime = frame; ctime += scene->r.subframe; ctime *= scene->r.framelen; - + return ctime; } @@ -1298,7 +1308,7 @@ void BKE_scene_frame_set(struct Scene *scene, double cfra) } #ifdef WITH_LEGACY_DEPSGRAPH -/* drivers support/hacks +/* drivers support/hacks * - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render * - these are always run since the depsgraph can't handle non-object data * - these happen after objects are all done so that we can read in their final transform values, @@ -1308,7 +1318,7 @@ static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene) { SceneRenderLayer *srl; float ctime = BKE_scene_frame_get(scene); - + /* scene itself */ if (scene->adt && scene->adt->drivers.first) { BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS); @@ -1319,16 +1329,16 @@ static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene) if (scene->world) { ID *wid = (ID *)scene->world; AnimData *adt = BKE_animdata_from_id(wid); - + if (adt && adt->drivers.first) BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS); } - + /* nodes */ if (scene->nodetree) { ID *nid = (ID *)scene->nodetree; AnimData *adt = BKE_animdata_from_id(nid); - + if (adt && adt->drivers.first) BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS); } @@ -1337,7 +1347,7 @@ static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene) if (scene->world && scene->world->nodetree) { ID *nid = (ID *)scene->world->nodetree; AnimData *adt = BKE_animdata_from_id(nid); - + if (adt && adt->drivers.first) BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS); } @@ -1363,32 +1373,32 @@ static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene) static void scene_depsgraph_hack(Main *bmain, EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent) { Base *base; - + scene->customdata_mask = scene_parent->customdata_mask; - + /* sets first, we allow per definition current scene to have * dependencies on sets, but not the other way around. */ if (scene->set) scene_depsgraph_hack(bmain, eval_ctx, scene->set, scene_parent); - + for (base = scene->base.first; base; base = base->next) { Object *ob = base->object; - + if (ob->depsflag) { int recalc = 0; // printf("depshack %s\n", ob->id.name + 2); - + if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC) recalc |= OB_RECALC_OB; if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC) recalc |= OB_RECALC_DATA; - + ob->recalc |= recalc; BKE_object_handle_update(bmain, eval_ctx, scene_parent, ob); - + if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) { GroupObject *go; - + for (go = ob->dup_group->gobject.first; go; go = go->next) { if (go->ob) go->ob->recalc |= recalc; @@ -1781,7 +1791,7 @@ static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bma /* update masking curves */ BKE_mask_update_scene(bmain, scene); - + } #endif /* WITH_LEGACY_DEPSGRAPH */ @@ -1867,9 +1877,9 @@ void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *sc DAG_ids_flush_tagged(bmain); /* removed calls to quick_cache, see pointcache.c */ - + /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later - * when trying to find materials with drivers that need evaluating [#32017] + * when trying to find materials with drivers that need evaluating [#32017] */ BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false); BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false); @@ -1896,7 +1906,7 @@ void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *sc { AnimData *adt = BKE_animdata_from_id(&scene->id); float ctime = BKE_scene_frame_get(scene); - + if (adt && (adt->recalc & ADT_RECALC_ANIM)) BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0); } @@ -1974,7 +1984,7 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, /* update animated image textures for particles, modifiers, gpu, etc, * call this at the start so modifiers with textures don't lag 1 frame */ BKE_image_update_frame(bmain, sce->r.cfra); - + #ifdef WITH_LEGACY_DEPSGRAPH /* rebuild rigid body worlds before doing the actual frame update * this needs to be done on start frame but animation playback usually starts one frame later @@ -1984,9 +1994,9 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, scene_rebuild_rbw_recursive(sce, ctime); } #endif - + BKE_sound_set_cfra(sce->r.cfra); - + /* clear animation overrides */ /* XXX TODO... */ @@ -2028,7 +2038,7 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, #endif /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later - * when trying to find materials with drivers that need evaluating [#32017] + * when trying to find materials with drivers that need evaluating [#32017] */ BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false); BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false); @@ -2040,7 +2050,7 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, scene_do_rb_simulation_recursive(sce, ctime); } #endif - + /* BKE_object_handle_update() on all objects, groups and sets */ #ifdef WITH_LEGACY_DEPSGRAPH if (use_new_eval) { @@ -2346,7 +2356,7 @@ int BKE_render_num_threads(const RenderData *rd) threads = rd->threads; else threads = BLI_system_thread_count(); - + return max_ii(threads, 1); } diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c index 995d22c9ba58..3c615221564d 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -64,7 +64,7 @@ static void spacetype_free(SpaceType *st) ARegionType *art; PanelType *pt; HeaderType *ht; - + for (art = st->regiontypes.first; art; art = art->next) { BLI_freelistN(&art->drawcalls); @@ -83,7 +83,7 @@ static void spacetype_free(SpaceType *st) BLI_freelistN(&art->paneltypes); BLI_freelistN(&art->headertypes); } - + BLI_freelistN(&st->regiontypes); BLI_freelistN(&st->toolshelf); @@ -92,18 +92,18 @@ static void spacetype_free(SpaceType *st) void BKE_spacetypes_free(void) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { spacetype_free(st); } - + BLI_freelistN(&spacetypes); } SpaceType *BKE_spacetype_from_id(int spaceid) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { if (st->spaceid == spaceid) return st; @@ -114,11 +114,11 @@ SpaceType *BKE_spacetype_from_id(int spaceid) ARegionType *BKE_regiontype_from_id_or_first(SpaceType *st, int regionid) { ARegionType *art; - + for (art = st->regiontypes.first; art; art = art->next) if (art->regionid == regionid) return art; - + printf("Error, region type %d missing in - name:\"%s\", id:%d\n", regionid, st->name, st->spaceid); return st->regiontypes.first; } @@ -126,7 +126,7 @@ ARegionType *BKE_regiontype_from_id_or_first(SpaceType *st, int regionid) ARegionType *BKE_regiontype_from_id(SpaceType *st, int regionid) { ARegionType *art; - + for (art = st->regiontypes.first; art; art = art->next) { if (art->regionid == regionid) { return art; @@ -144,7 +144,7 @@ const ListBase *BKE_spacetypes_list(void) void BKE_spacetype_register(SpaceType *st) { SpaceType *stype; - + /* sanity check */ stype = BKE_spacetype_from_id(st->spaceid); if (stype) { @@ -152,7 +152,7 @@ void BKE_spacetype_register(SpaceType *st) spacetype_free(stype); MEM_freeN(stype); } - + BLI_addtail(&spacetypes, st); } @@ -167,20 +167,20 @@ void BKE_spacedata_freelist(ListBase *lb) { SpaceLink *sl; ARegion *ar; - + for (sl = lb->first; sl; sl = sl->next) { SpaceType *st = BKE_spacetype_from_id(sl->spacetype); - + /* free regions for pushed spaces */ for (ar = sl->regionbase.first; ar; ar = ar->next) BKE_area_region_free(st, ar); BLI_freelistN(&sl->regionbase); - - if (st && st->free) + + if (st && st->free) st->free(sl); } - + BLI_freelistN(lb); } @@ -188,7 +188,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) { ARegion *newar = MEM_dupallocN(ar); Panel *pa, *newpa, *patab; - + newar->prev = newar->next = NULL; BLI_listbase_clear(&newar->handlers); BLI_listbase_clear(&newar->uiblocks); @@ -198,7 +198,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) newar->swinid = 0; newar->regiontimer = NULL; newar->headerstr = NULL; - + /* use optional regiondata callback */ if (ar->regiondata) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); @@ -216,7 +216,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) if (ar->v2d.tab_offset) newar->v2d.tab_offset = MEM_dupallocN(ar->v2d.tab_offset); - + BLI_listbase_clear(&newar->panels); BLI_duplicatelist(&newar->panels, &ar->panels); @@ -236,7 +236,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) pa = pa->next; } } - + return newar; } @@ -245,10 +245,10 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) static void region_copylist(SpaceType *st, ListBase *lb1, ListBase *lb2) { ARegion *ar; - + /* to be sure */ BLI_listbase_clear(lb1); - + for (ar = lb2->first; ar; ar = ar->next) { ARegion *arnew = BKE_area_region_copy(st, ar); BLI_addtail(lb1, arnew); @@ -260,17 +260,17 @@ static void region_copylist(SpaceType *st, ListBase *lb1, ListBase *lb2) void BKE_spacedata_copylist(ListBase *lb1, ListBase *lb2) { SpaceLink *sl; - + BLI_listbase_clear(lb1); /* to be sure */ - + for (sl = lb2->first; sl; sl = sl->next) { SpaceType *st = BKE_spacetype_from_id(sl->spacetype); - + if (st && st->duplicate) { SpaceLink *slnew = st->duplicate(sl); - + BLI_addtail(lb1, slnew); - + region_copylist(st, &slnew->regionbase, &sl->regionbase); } } @@ -282,14 +282,14 @@ void BKE_spacedata_copylist(ListBase *lb1, ListBase *lb2) void BKE_spacedata_draw_locks(int set) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { ARegionType *art; - + for (art = st->regiontypes.first; art; art = art->next) { - if (set) + if (set) art->do_lock = art->lock; - else + else art->do_lock = false; } } @@ -317,16 +317,16 @@ void BKE_area_region_free(SpaceType *st, ARegion *ar) if (st) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); - + if (art && art->free) art->free(ar); - + if (ar->regiondata) printf("regiondata free error\n"); } else if (ar->type && ar->type->free) ar->type->free(ar); - + if (ar->v2d.tab_offset) { MEM_freeN(ar->v2d.tab_offset); ar->v2d.tab_offset = NULL; @@ -370,14 +370,14 @@ void BKE_screen_area_free(ScrArea *sa) { SpaceType *st = BKE_spacetype_from_id(sa->spacetype); ARegion *ar; - + for (ar = sa->regionbase.first; ar; ar = ar->next) BKE_area_region_free(st, ar); BLI_freelistN(&sa->regionbase); - + BKE_spacedata_freelist(&sa->spacedata); - + BLI_freelistN(&sa->actionzones); } @@ -388,17 +388,17 @@ void BKE_screen_free(bScreen *sc) ARegion *ar; /* No animdata here. */ - + for (ar = sc->regionbase.first; ar; ar = ar->next) BKE_area_region_free(NULL, ar); BLI_freelistN(&sc->regionbase); - + for (sa = sc->areabase.first; sa; sa = san) { san = sa->next; BKE_screen_area_free(sa); } - + BLI_freelistN(&sc->vertbase); BLI_freelistN(&sc->edgebase); BLI_freelistN(&sc->areabase); @@ -433,7 +433,7 @@ ARegion *BKE_area_find_region_type(ScrArea *sa, int type) { if (sa) { ARegion *ar; - + for (ar = sa->regionbase.first; ar; ar = ar->next) { if (ar->regiontype == type) return ar; diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index 0eca7a005157..e3fc494584cb 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -127,7 +127,7 @@ static ImBuf *prepare_effect_imbufs(const SeqRenderData *context, ImBuf *ibuf1, else { out = IMB_allocImBuf(x, y, 32, IB_rect); } - + if (out->rect_float) { if (ibuf1 && !ibuf1->rect_float) { BKE_sequencer_imbuf_to_sequencer_space(scene, ibuf1, true); @@ -140,7 +140,7 @@ static ImBuf *prepare_effect_imbufs(const SeqRenderData *context, ImBuf *ibuf1, if (ibuf3 && !ibuf3->rect_float) { BKE_sequencer_imbuf_to_sequencer_space(scene, ibuf3, true); } - + IMB_colormanagement_assign_float_colorspace(out, scene->sequencer_colorspace_settings.name); } else { @@ -369,7 +369,7 @@ static void do_alphaunder_effect_byte( tempc[1] = (fac * rt1[1] + rt2[1]); tempc[2] = (fac * rt1[2] + rt2[2]); tempc[3] = (fac * rt1[3] + rt2[3]); - + premul_float_to_straight_uchar(rt, tempc); } } @@ -384,10 +384,10 @@ static void do_alphaunder_effect_byte( while (x--) { straight_uchar_to_premul_float(rt1, cp1); straight_uchar_to_premul_float(rt2, cp2); - + if (rt2[3] <= 0.0f && fac4 >= 1.0f) *((unsigned int *) rt) = *((unsigned int *) cp1); else if (rt2[3] >= 1.0f) *((unsigned int *) rt) = *((unsigned int *) cp2); - else { + else { fac = (fac4 * (1.0f - rt2[3])); if (fac <= 0) *((unsigned int *)rt) = *((unsigned int *)cp2); @@ -396,7 +396,7 @@ static void do_alphaunder_effect_byte( tempc[1] = (fac * rt1[1] + rt2[1]); tempc[2] = (fac * rt1[2] + rt2[2]); tempc[3] = (fac * rt1[3] + rt2[3]); - + premul_float_to_straight_uchar(rt, tempc); } } @@ -628,7 +628,7 @@ static float gamma_range_table[RE_GAMMA_TABLE_SIZE + 1]; static float gamfactor_table[RE_GAMMA_TABLE_SIZE]; static float inv_gamma_range_table[RE_GAMMA_TABLE_SIZE + 1]; static float inv_gamfactor_table[RE_GAMMA_TABLE_SIZE]; -static float color_domain_table[RE_GAMMA_TABLE_SIZE + 1]; +static float color_domain_table[RE_GAMMA_TABLE_SIZE + 1]; static float color_step; static float inv_color_step; static float valid_gamma; @@ -642,7 +642,7 @@ static void makeGammaTables(float gamma) valid_gamma = gamma; valid_inv_gamma = 1.0f / gamma; color_step = 1.0f / RE_GAMMA_TABLE_SIZE; - inv_color_step = (float) RE_GAMMA_TABLE_SIZE; + inv_color_step = (float) RE_GAMMA_TABLE_SIZE; /* We could squeeze out the two range tables to gain some memory */ for (i = 0; i < RE_GAMMA_TABLE_SIZE; i++) { @@ -674,7 +674,7 @@ static float gammaCorrect(float c) { int i; float res; - + i = floorf(c * inv_color_step); /* Clip to range [0, 1]: outside, just do the complete calculation. * We may have some performance problems here. Stretching up the LUT @@ -685,7 +685,7 @@ static float gammaCorrect(float c) else if (i >= RE_GAMMA_TABLE_SIZE) res = powf(c, valid_gamma); else res = gamma_range_table[i] + ((c - color_domain_table[i]) * gamfactor_table[i]); - + return res; } @@ -710,17 +710,17 @@ static void gamtabs(float gamma) { float val, igamma = 1.0f / gamma; int a; - + /* gamtab: in short, out short */ for (a = 0; a < 65536; a++) { val = a; val /= 65535.0f; - + if (gamma == 2.0f) val = sqrtf(val); else if (gamma != 1.0f) val = powf(val, igamma); - + gamtab[a] = (65535.99f * val); } /* inverse gamtab1 : in byte, out short */ @@ -1317,7 +1317,7 @@ BLI_INLINE void apply_blend_function_byte( rt1 = rect1; rt2 = rect2; rt = out; - while (y--) { + while (y--) { for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = (unsigned int) achannel * facf0; @@ -1331,7 +1331,7 @@ BLI_INLINE void apply_blend_function_byte( if (y == 0) { break; } - y--; + y--; for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = (unsigned int) achannel * facf1; @@ -1356,7 +1356,7 @@ BLI_INLINE void apply_blend_function_float( rt1 = rect1; rt2 = rect2; rt = out; - while (y--) { + while (y--) { for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = achannel * facf0; @@ -1370,7 +1370,7 @@ BLI_INLINE void apply_blend_function_float( if (y == 0) { break; } - y--; + y--; for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = achannel * facf1; @@ -1771,9 +1771,10 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f /* case DO_CROSS_WIPE: */ /* BOX WIPE IS NOT WORKING YET */ #if 0 - case DO_BOX_WIPE: - if (!wipe->forward) - facf0 = 1.0f - facf0; /* Go the other direction */ + case DO_BOX_WIPE: + if (!wipe->forward) { + facf0 = 1.0f - facf0; /* Go the other direction */ + } width = (int)(wipe->edgeWidth * ((xo + yo) / 2.0)); hwidth = (float)width / 2.0; @@ -1806,8 +1807,9 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f output = in_band(hwidth, hyp2, 1, 1) * in_band(hwidth, hyp, 1, 1); } - if (!wipe->forward) - facf0 = 1.0f - facf0; /* Go the other direction */ + if (!wipe->forward) { + facf0 = 1.0f - facf0; /* Go the other direction */ + } angle = -1 / angle; b1 = posy / 2 - (-angle) * posx / 2; b3 = (yo - posy / 2) - (-angle) * (xo - posx / 2); @@ -1852,7 +1854,7 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f else output = in_band(hwidth, fabsf(temp2 - pointdist), 1, 1); if (!wipe->forward) output = 1 - output; - + break; } if (output < 0) output = 0; @@ -2053,7 +2055,7 @@ static void init_transform_effect(Sequence *seq) transform->yIni = 0.0f; transform->rotIni = 0.0f; - + transform->interpolation = 1; transform->percent = 1; transform->uniform_scale = 0; @@ -2085,7 +2087,7 @@ static void transform_image( xo = x; yo = y; - + /* Rotate */ s = sinf(rotate); c = cosf(rotate); @@ -2128,7 +2130,7 @@ static void do_transform(Scene *scene, Sequence *seq, float UNUSED(facf0), int x { TransformVars *transform = (TransformVars *) seq->effectdata; float scale_x, scale_y, translate_x, translate_y, rotate_radians; - + /* Scale */ if (transform->uniform_scale) { scale_x = scale_y = transform->ScalexIni; @@ -2292,7 +2294,7 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i index = (x + (height - 1 - y) * width) * 4; copy_v4_v4(temp + index, curColor2); } - + /* Do the main body */ for (y = halfWidth; y < height - halfWidth; y++) { fy = 0; @@ -2461,12 +2463,12 @@ static ImBuf *do_glow_effect( static void init_solid_color(Sequence *seq) { SolidColorVars *cv; - + if (seq->effectdata) MEM_freeN(seq->effectdata); seq->effectdata = MEM_callocN(sizeof(SolidColorVars), "solidcolor"); - + cv = (SolidColorVars *)seq->effectdata; cv->col[0] = cv->col[1] = cv->col[2] = 0.5; } @@ -2520,7 +2522,7 @@ static ImBuf *do_solid_color( col1[2] = facf1 * cv->col[2] * 255; rect = (unsigned char *)out->rect; - + for (y = 0; y < out->y; y++) { for (x = 0; x < out->x; x++, rect += 4) { rect[0] = col0[0]; @@ -2553,7 +2555,7 @@ static ImBuf *do_solid_color( col1[2] = facf1 * cv->col[2]; rect_float = out->rect_float; - + for (y = 0; y < out->y; y++) { for (x = 0; x < out->x; x++, rect_float += 4) { rect_float[0] = col0[0]; @@ -2622,7 +2624,7 @@ static ImBuf *do_multicam( else { out = i; } - + return out; } @@ -2697,7 +2699,7 @@ static ImBuf *do_adjustment( else { out = i; } - + return out; } @@ -2876,7 +2878,7 @@ void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, bool for facf *= seq->seq1->len; } facf *= v->globalSpeed; - + if (facf >= seq->seq1->len) { facf = seq->seq1->len - 1; } diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c index ed8553370419..7e4069305f6d 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -746,10 +746,10 @@ void BKE_sequence_calc_disp(Scene *scene, Sequence *seq) seq->startstill = 0; if (seq->endofs && seq->endstill) seq->endstill = 0; - + seq->startdisp = seq->start + seq->startofs - seq->startstill; seq->enddisp = seq->start + seq->len - seq->endofs + seq->endstill; - + seq->handsize = 10.0; /* 10 frames */ if (seq->enddisp - seq->startdisp < 10) { seq->handsize = (float)(0.5 * (seq->enddisp - seq->startdisp)); @@ -1011,7 +1011,7 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r BKE_sequence_tx_set_final_right(seq, prev_enddisp); BKE_sequence_single_fix(seq); } - + BKE_sequence_calc(scene, seq); } @@ -1275,7 +1275,7 @@ static void multibuf(ImBuf *ibuf, const float fmul) rt_float[1] *= fmul; rt_float[2] *= fmul; rt_float[3] *= fmul; - + rt_float += 4; } } @@ -1306,9 +1306,9 @@ static float give_stripelem_index(Sequence *seq, float cfra) else if (cfra >= end) nr = end - sta; else nr = cfra - sta; } - + if (seq->strobe < 1.0f) seq->strobe = 1.0f; - + if (seq->strobe > 1.0f) { nr -= fmodf((double)nr, (double)seq->strobe); } @@ -1329,7 +1329,7 @@ StripElem *BKE_sequencer_give_stripelem(Sequence *seq, int cfra) if (nr == -1 || se == NULL) return NULL; - + se += nr + seq->anim_startofs; } return se; @@ -1426,7 +1426,7 @@ static int get_shown_sequences(ListBase *seqbasep, int cfra, int chanshown, Sequ } } } - + chanshown = b; for (; b > 0; b--) { @@ -1656,7 +1656,7 @@ static bool seq_proxy_get_fname(Editing *ed, Sequence *seq, int cfra, int render return false; } - /* MOVIE tracks (only exception: custom files) are now handled + /* MOVIE tracks (only exception: custom files) are now handled * internally by ImBuf module for various reasons: proper time code * support, quicker index build, using one file instead * of a full directory of jpeg files, etc. Trying to support old @@ -2097,7 +2097,7 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value) } else { seq->flag &= ~SEQ_USE_PROXY; - } + } } /*********************** color balance *************************/ @@ -2197,7 +2197,7 @@ static void color_balance_byte_byte(StripColorBalance *cb_, unsigned char *rect, else p[c] = t; } - + premul_float_to_straight_uchar(cp, p); cp += 4; @@ -2549,7 +2549,7 @@ static ImBuf *input_preprocess(const SeqRenderData *context, Sequence *seq, floa if (seq->flag & SEQ_FLIPX) { IMB_flipx(ibuf); } - + if (seq->flag & SEQ_FLIPY) { IMB_flipy(ibuf); } @@ -2753,7 +2753,7 @@ static ImBuf *seq_render_effect_strip_impl( if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) { sh.get_default_fac(seq, cfra, &fac, &facf); - + if ((scene->r.mode & R_FIELDS) == 0) facf = fac; } @@ -3072,7 +3072,7 @@ static ImBuf *seq_render_movieclip_strip(const SeqRenderData *context, Sequence } memset(&user, 0, sizeof(MovieClipUser)); - + BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs + seq->clip->start_frame); user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL; @@ -3284,7 +3284,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq BKE_scene_camera_switch_update(scene); camera = scene->camera; } - + if (have_comp == false && camera == NULL) { goto finally; } @@ -3666,13 +3666,13 @@ static bool seq_must_swap_input_in_blend_mode(Sequence *seq) { bool swap_input = false; - /* bad hack, to fix crazy input ordering of + /* bad hack, to fix crazy input ordering of * those two effects */ if (ELEM(seq->blend_mode, SEQ_TYPE_ALPHAOVER, SEQ_TYPE_ALPHAUNDER, SEQ_TYPE_OVERDROP)) { swap_input = true; } - + return swap_input; } @@ -3749,7 +3749,7 @@ static ImBuf *seq_render_strip_stack( if (out) { return out; } - + if (count == 1) { Sequence *seq = seq_arr[0]; @@ -3874,7 +3874,7 @@ ImBuf *BKE_sequencer_give_ibuf(const SeqRenderData *context, float cfra, int cha { Editing *ed = BKE_sequencer_editing_get(context->scene, false); ListBase *seqbasep; - + if (ed == NULL) return NULL; if ((chanshown < 0) && !BLI_listbase_is_empty(&ed->metastack)) { @@ -3925,23 +3925,23 @@ static pthread_cond_t wakeup_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t frame_done_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t frame_done_cond = PTHREAD_COND_INITIALIZER; -static volatile bool seq_thread_shutdown = true; +static volatile bool seq_thread_shutdown = true; static volatile int seq_last_given_monoton_cfra = 0; static int monoton_cfra = 0; typedef struct PrefetchThread { struct PrefetchThread *next, *prev; - + Scene *scene; struct PrefetchQueueElem *current; pthread_t pthread; int running; - + } PrefetchThread; typedef struct PrefetchQueueElem { struct PrefetchQueueElem *next, *prev; - + int rectx; int recty; float cfra; @@ -3971,7 +3971,7 @@ void BKE_sequencer_give_ibuf_prefetch_request(const SeqRenderData *context, floa pthread_mutex_lock(&queue_lock); BLI_addtail(&prefetch_wait, e); pthread_mutex_unlock(&queue_lock); - + pthread_mutex_lock(&wakeup_lock); pthread_cond_signal(&wakeup_cond); pthread_mutex_unlock(&wakeup_lock); @@ -4057,7 +4057,7 @@ ImBuf *BKE_sequencer_give_ibuf_threaded(const SeqRenderData *context, float cfra pthread_mutex_unlock(&frame_done_lock); } } - + return e ? e->ibuf : NULL; } @@ -4173,30 +4173,30 @@ void BKE_sequencer_free_imbuf(Scene *scene, ListBase *seqbase, bool for_render) BKE_sequencer_free_imbuf(scene, &seq->seqbase, for_render); } if (seq->type == SEQ_TYPE_SCENE) { - /* FIXME: recurs downwards, + /* FIXME: recurs downwards, * but do recurs protection somehow! */ } } - + } static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change) { Sequence *subseq; bool free_imbuf = false; - + /* recurs downwards to see if this seq depends on the changed seq */ - + if (seq == NULL) return false; - + if (seq == changed_seq) free_imbuf = true; - + for (subseq = seq->seqbase.first; subseq; subseq = subseq->next) if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change)) free_imbuf = true; - + if (seq->seq1) if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change)) free_imbuf = true; @@ -4206,7 +4206,7 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2)) if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change)) free_imbuf = true; - + if (free_imbuf) { if (ibuf_change) { if (seq->type == SEQ_TYPE_MOVIE) { @@ -4216,11 +4216,11 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha BKE_sequence_effect_speed_rebuild_map(scene, seq, true); } } - + if (len_change) BKE_sequence_calc(scene, seq); } - + return free_imbuf; } @@ -4228,9 +4228,9 @@ void BKE_sequencer_update_changed_seq_and_deps(Scene *scene, Sequence *changed_s { Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq; - + if (ed == NULL) return; - + for (seq = ed->seqbase.first; seq; seq = seq->next) update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change); } @@ -4487,9 +4487,9 @@ Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame) Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq, *best_seq = NULL; int best_machine = -1; - + if (!ed) return NULL; - + for (seq = ed->seqbasep->first; seq; seq = seq->next) { if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame) continue; @@ -4948,7 +4948,7 @@ static void seq_free_animdata(Scene *scene, Sequence *seq) while (fcu) { if (STREQLEN(fcu->rna_path, str, str_len)) { FCurve *next_fcu = fcu->next; - + BLI_remlink(&scene->adt->action->curves, fcu); free_fcurve(fcu); @@ -5202,7 +5202,7 @@ Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoad seq = BKE_sequence_alloc(seqbasep, seq_load->start_frame, seq_load->channel); seq->type = SEQ_TYPE_IMAGE; seq->blend_mode = SEQ_TYPE_CROSS; /* so alpha adjustment fade to the strip below */ - + /* basic defaults */ seq->strip = strip = MEM_callocN(sizeof(Strip), "strip"); @@ -5390,7 +5390,7 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad seq->anim_preseek = IMB_anim_get_preseek(anim_arr[0]); BLI_strncpy(seq->name + 2, "Movie", SEQ_NAME_MAXSTR - 2); BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq); - + /* adjust scene's frame rate settings to match */ if (seq_load->flag & SEQ_LOAD_SYNC_FPS) { IMB_anim_get_fps(anim_arr[0], &scene->r.frs_sec, &scene->r.frs_sec_base, true); @@ -5517,6 +5517,7 @@ static Sequence *seq_dupli(const Scene *scene_src, Scene *scene_dst, Sequence *s if (scene_src == scene_dst) { if (dupe_flag & SEQ_DUPE_UNIQUE_NAME) { + /* TODO this is broken in case of Meta strips recursive duplication... Not trivial to fix. */ BKE_sequence_base_unique_name_recursive(&scene_dst->ed->seqbase, seqn); } diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index bf22b106cf8d..e28b4ccc23d3 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -163,7 +163,7 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) OUT_OF_MEMORY(); return; } - + /* Setup nearest */ nearest.index = -1; nearest.dist_sq = FLT_MAX; diff --git a/source/blender/blenkernel/intern/sketch.c b/source/blender/blenkernel/intern/sketch.c index 6f5c264f658e..0bf7a9f278ed 100644 --- a/source/blender/blenkernel/intern/sketch.c +++ b/source/blender/blenkernel/intern/sketch.c @@ -374,65 +374,65 @@ void sk_filterStroke(SK_Stroke *stk, int start, int end) marked = MEM_callocN(nb_points, "marked array"); marked[start] = 1; marked[end] = 1; - + work = 1; - + /* while still reducing */ while (work) { int ls, le; work = 0; - + ls = start; le = start + 1; - + /* while not over interval */ while (ls < end) { int max_i = 0; short v1[2]; float max_dist = 16; /* more than 4 pixels */ - + /* find the next marked point */ while (marked[le] == 0) { le++; } - + /* perpendicular vector to ls-le */ - v1[1] = old_points[le].p2d[0] - old_points[ls].p2d[0]; - v1[0] = old_points[ls].p2d[1] - old_points[le].p2d[1]; - + v1[1] = old_points[le].p2d[0] - old_points[ls].p2d[0]; + v1[0] = old_points[ls].p2d[1] - old_points[le].p2d[1]; + for (i = ls + 1; i < le; i++) { float mul; float dist; short v2[2]; - - v2[0] = old_points[i].p2d[0] - old_points[ls].p2d[0]; + + v2[0] = old_points[i].p2d[0] - old_points[ls].p2d[0]; v2[1] = old_points[i].p2d[1] - old_points[ls].p2d[1]; - + if (v2[0] == 0 && v2[1] == 0) { continue; } mul = (float)(v1[0] * v2[0] + v1[1] * v2[1]) / (float)(v2[0] * v2[0] + v2[1] * v2[1]); - + dist = mul * mul * (v2[0] * v2[0] + v2[1] * v2[1]); - + if (dist > max_dist) { max_dist = dist; max_i = i; } } - + if (max_i != 0) { work = 1; marked[max_i] = 1; } - + ls = le; le = ls + 1; } } - + /* adding points after range */ for (i = start; i <= end; i++) { diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c index 2ab892a02339..c1a085a3b15e 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -1810,7 +1810,7 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], E int zn = z - new_shift[2]; int index; float max_den; - + /* skip if cell already belongs to new area */ if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && zn <= max[2]) continue; diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index c3527af90ca6..47e567aaca15 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -2864,7 +2864,7 @@ static void mesh_to_softbody(Scene *scene, Object *ob) BodySpring *bs; int a, totedge; int defgroup_index, defgroup_index_mass, defgroup_index_spring; - + if (ob->softflag & OB_SB_EDGES) totedge= me->totedge; else totedge= 0; @@ -3766,4 +3766,3 @@ void sbObjectStep(Scene *scene, Object *ob, float cfra, float (*vertexCos)[3], i sb->last_frame = framenr; } - diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index 7ad8f03dfee7..d21055ada6aa 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -146,7 +146,7 @@ void BKE_sound_free(bSound *sound) } BKE_sound_free_waveform(sound); - + #endif /* WITH_AUDASPACE */ if (sound->spinlock) { BLI_spin_end(sound->spinlock); @@ -757,15 +757,19 @@ int BKE_sound_scene_playing(struct Scene *scene) void BKE_sound_free_waveform(bSound *sound) { - SoundWaveform *waveform = sound->waveform; - if (waveform) { - if (waveform->data) { - MEM_freeN(waveform->data); + if ((sound->tags & SOUND_TAGS_WAVEFORM_NO_RELOAD) == 0) { + SoundWaveform *waveform = sound->waveform; + if (waveform) { + if (waveform->data) { + MEM_freeN(waveform->data); + } + MEM_freeN(waveform); } - MEM_freeN(waveform); - } - sound->waveform = NULL; + sound->waveform = NULL; + } + /* This tag is only valid once. */ + sound->tags &= ~SOUND_TAGS_WAVEFORM_NO_RELOAD; } void BKE_sound_read_waveform(bSound *sound, short *stop) @@ -775,7 +779,7 @@ void BKE_sound_read_waveform(bSound *sound, short *stop) if (info.length > 0) { int length = info.length * SOUND_WAVE_SAMPLES_PER_SECOND; - + waveform->data = MEM_mallocN(length * sizeof(float) * 3, "SoundWaveform.samples"); waveform->length = AUD_readSound(sound->playback_handle, waveform->data, length, SOUND_WAVE_SAMPLES_PER_SECOND, stop); } @@ -794,16 +798,16 @@ void BKE_sound_read_waveform(bSound *sound, short *stop) } MEM_freeN(waveform); BLI_spin_lock(sound->spinlock); - sound->flags &= ~SOUND_FLAGS_WAVEFORM_LOADING; + sound->tags &= ~SOUND_TAGS_WAVEFORM_LOADING; BLI_spin_unlock(sound->spinlock); return; } - + BKE_sound_free_waveform(sound); - + BLI_spin_lock(sound->spinlock); sound->waveform = waveform; - sound->flags &= ~SOUND_FLAGS_WAVEFORM_LOADING; + sound->tags &= ~SOUND_TAGS_WAVEFORM_LOADING; BLI_spin_unlock(sound->spinlock); } diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index 8e46cabff026..221c600f502a 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -202,7 +202,7 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, /* mask is allocated after regular layers */ ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers); } - + if (flags & CCG_CALC_NORMALS) ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset); else @@ -285,11 +285,11 @@ static void get_face_uv_map_vert(UvVertMap *vmap, struct MPoly *mpoly, struct ML for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) { if (v->separate) nv = v; - if (v->f == fi) + if (v->poly_index == fi) break; } - fverts[j] = SET_UINT_IN_POINTER(mpoly[nv->f].loopstart + nv->tfindex); + fverts[j] = SET_UINT_IN_POINTER(mpoly[nv->poly_index].loopstart + nv->loop_of_poly_index); } } @@ -297,7 +297,6 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, { MPoly *mpoly = dm->getPolyArray(dm); MLoop *mloop = dm->getLoopArray(dm); - MVert *mvert = dm->getVertArray(dm); int totvert = dm->getNumVerts(dm); int totface = dm->getNumPolys(dm); int i, seam; @@ -309,18 +308,17 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, BLI_array_declare(fverts); #endif EdgeSet *eset; - float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss); float uv[3] = {0.0f, 0.0f, 0.0f}; /* only first 2 values are written into */ limit[0] = limit[1] = STD_UV_CONNECT_LIMIT; /* previous behavior here is without accounting for winding, however this causes stretching in * UV map in really simple cases with mirror + subsurf, see second part of T44530. Also, initially - * intention is to treat merged vertices from mirror modifier as seams, see code below with ME_VERT_MERGED + * intention is to treat merged vertices from mirror modifier as seams. * This fixes a very old regression (2.49 was correct here) */ vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true); if (!vmap) return 0; - + ccgSubSurf_initFullSync(ss); /* create vertices */ @@ -332,12 +330,12 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, if (v->separate) break; - seam = (v != NULL) || ((mvert + i)->flag & ME_VERT_MERGED); + seam = (v != NULL); for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i); v; v = v->next) { if (v->separate) { CCGVert *ssv; - int loopid = mpoly[v->f].loopstart + v->tfindex; + int loopid = mpoly[v->poly_index].loopstart + v->loop_of_poly_index; CCGVertHDL vhdl = SET_INT_IN_POINTER(loopid); copy_v2_v2(uv, mloopuv[loopid].uv); @@ -370,18 +368,11 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, for (j = 0, j_next = nverts - 1; j < nverts; j_next = j++) { unsigned int v0 = GET_UINT_FROM_POINTER(fverts[j_next]); unsigned int v1 = GET_UINT_FROM_POINTER(fverts[j]); - MVert *mv0 = mvert + (ml[j_next].v); - MVert *mv1 = mvert + (ml[j].v); if (BLI_edgeset_add(eset, v0, v1)) { CCGEdge *e, *orige = ccgSubSurf_getFaceEdge(origf, j_next); CCGEdgeHDL ehdl = SET_INT_IN_POINTER(mp->loopstart + j_next); - float crease; - - if ((mv0->flag & mv1->flag) & ME_VERT_MERGED) - crease = creaseFactor; - else - crease = ccgSubSurf_getEdgeCrease(orige); + float crease = ccgSubSurf_getEdgeCrease(orige); ccgSubSurf_syncEdge(ss, ehdl, fverts[j_next], fverts[j], crease, &e); } @@ -618,12 +609,12 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) if (wtable->len <= faceLen) { void *tmp = MEM_callocN(sizeof(FaceVertWeightEntry) * (faceLen + 1), "weight table alloc 2"); - + if (wtable->len) { memcpy(tmp, wtable->weight_table, sizeof(FaceVertWeightEntry) * wtable->len); MEM_freeN(wtable->weight_table); } - + wtable->weight_table = tmp; wtable->len = faceLen + 1; } @@ -638,7 +629,7 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) for (y = 0; y < gridCuts + 2; y++) { fx = 0.5f - (float)x / (float)(gridCuts + 1) / 2.0f; fy = 0.5f - (float)y / (float)(gridCuts + 1) / 2.0f; - + fac2 = faceLen - 4; w1 = (1.0f - fx) * (1.0f - fy) + (-fac2 * fx * fy * fac); w2 = (1.0f - fx + fac2 * fx * -fac) * (fy); @@ -652,7 +643,7 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) w[j] = fac2; } } - + w[i] = w1; w[(i - 1 + faceLen) % faceLen] = w2; w[(i + 1) % faceLen] = w4; @@ -674,7 +665,7 @@ static void free_ss_weights(WeightTable *wtable) if (wtable->weight_table[i].valid) MEM_freeN(wtable->weight_table[i].w); } - + if (wtable->weight_table) MEM_freeN(wtable->weight_table); } @@ -1105,7 +1096,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med) /* numVerts = ccgSubSurf_getFaceNumVerts(f); */ /*UNUSED*/ gridSideEdges = gridSize - 1; - gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; + gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; offset = edgeNum - ccgdm->faceMap[i].startEdge; grid = offset / (gridSideEdges + gridInternalEdges); @@ -1219,7 +1210,7 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly, int edgeSize = ccgSubSurf_getEdgeSize(ss); int totface = ccgSubSurf_getNumFaces(ss); int i, j, x, y; - + for (i = 0; i < totface; i++) { CCGFace *f = ccgdm->faceMap[i].face; @@ -1228,14 +1219,14 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly, int hidden_gridsize = BKE_ccg_gridsize(md->level); int factor = BKE_ccg_factor(level, md->level); BLI_bitmap *hidden = md->hidden; - + if (!hidden) continue; - + for (y = 0; y < gridSize; y++) { for (x = 0; x < gridSize; x++) { int vndx, offset; - + vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); offset = (y * factor) * hidden_gridsize + (x * factor); if (BLI_BITMAP_TEST(hidden, offset)) @@ -1259,11 +1250,11 @@ void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly, int edgeSize = ccgSubSurf_getEdgeSize(ss); int totface = ccgSubSurf_getNumFaces(ss); int i, j, x, y, factor, gpm_gridsize; - + for (i = 0; i < totface; i++) { CCGFace *f = ccgdm->faceMap[i].face; const MPoly *p = &mpoly[i]; - + for (j = 0; j < p->totloop; j++) { const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j]; if (!gpm->data) @@ -1271,11 +1262,11 @@ void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly, factor = BKE_ccg_factor(level, gpm->level); gpm_gridsize = BKE_ccg_gridsize(gpm->level); - + for (y = 0; y < gridSize; y++) { for (x = 0; x < gridSize; x++) { int vndx, offset; - + vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); offset = y * factor * gpm_gridsize + x * factor; paint_mask[vndx] = gpm->data[offset]; @@ -1314,7 +1305,7 @@ static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert) vd = ccgSubSurf_getFaceCenterData(f); ccgDM_to_MVert(&mvert[i++], &key, vd); - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++) { vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x); @@ -1631,7 +1622,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) CCGEdge **edgeMap2; CCGVert **vertMap2; int index, totvert, totedge, totface; - + totvert = ccgSubSurf_getNumVerts(ss); vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap"); for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) { @@ -1662,7 +1653,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f); copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f)); - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++) { copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x)); @@ -1917,7 +1908,7 @@ static void ccgDM_NormalFast(float *a, float *b, float *c, float *d, float no[3] no[0] = b_dY * a_cZ - b_dZ * a_cY; no[1] = b_dZ * a_cX - b_dX * a_cZ; no[2] = b_dX * a_cY - b_dY * a_cX; - + normalize_v3(no); } @@ -1927,7 +1918,7 @@ static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d) float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2]; float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2]; float no[3]; - + no[0] = b_dY * a_cZ - b_dZ * a_cY; no[1] = b_dZ * a_cX - b_dX * a_cZ; no[2] = b_dX * a_cY - b_dY * a_cX; @@ -2022,7 +2013,7 @@ static void ccgDM_buffer_copy_normal( ccgDM_NormalFast(a, b, c, d, f_no); normal_float_to_short_v3(f_no_s, f_no); - + copy_v3_v3_short(&varray[start], f_no_s); copy_v3_v3_short(&varray[start + 4], f_no_s); copy_v3_v3_short(&varray[start + 8], f_no_s); @@ -2166,7 +2157,7 @@ static void ccgDM_buffer_copy_vertex( 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++) { CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S); for (y = 0; y < gridFaces; y++) { @@ -2598,7 +2589,7 @@ static GPUDrawObject *ccgDM_GPUObjectNew(DerivedMesh *dm) BLI_assert(dm_totmat != 0); matinfo = MEM_callocN(sizeof(*matinfo) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new"); - + if (faceFlags) { for (i = 0; i < totface; i++) { CCGFace *f = ccgdm->faceMap[i].face; @@ -2621,7 +2612,7 @@ static GPUDrawObject *ccgDM_GPUObjectNew(DerivedMesh *dm) tot_internal_edges += numVerts * gridFaces * (2 * gridFaces - 1); } } - + /* create the GPUDrawObject */ gdo = MEM_callocN(sizeof(GPUDrawObject), "GPUDrawObject"); gdo->totvert = 0; /* used to count indices, doesn't really matter for ccgsubsurf */ @@ -3309,7 +3300,7 @@ static void ccgDM_drawMappedFacesMat(DerivedMesh *dm, int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f)); int origIndex = ccgDM_getFaceMapIndex(ss, f); int new_matnr; - + numVerts = ccgSubSurf_getFaceNumVerts(f); /* get flags */ @@ -3379,7 +3370,7 @@ static void ccgDM_drawMappedFacesMat(DerivedMesh *dm, for (x = 0; x < gridFaces; x++) { vda = CCG_grid_elem(&key, faceGridData, x, y); vdb = CCG_grid_elem(&key, faceGridData, x, y + 1); - + PASSATTRIB(0, 0, 0); glNormal3fv(CCG_elem_no(&key, vda)); glVertex3fv(CCG_elem_co(&key, vda)); @@ -3427,7 +3418,7 @@ static void ccgDM_drawMappedFacesMat(DerivedMesh *dm, glVertex3fv(bco); PASSATTRIB(0, 0, 0); glVertex3fv(aco); - + a++; } } @@ -3800,13 +3791,13 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, if (setMaterial) { int mat_nr = faceFlags ? faceFlags[origIndex].mat_nr + 1 : 1; - + if (mat_nr != prev_mat_nr) { setMaterial(mat_nr, NULL); /* XXX, no faceFlags no material */ prev_mat_nr = mat_nr; } } - + if (setDrawOptions && (index != ORIGINDEX_NONE)) draw_option = setDrawOptions(userData, index); @@ -3853,7 +3844,7 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, for (x = 0; x < gridFaces; x++) { a = CCG_grid_elem(&key, faceGridData, x, y + 0); b = CCG_grid_elem(&key, faceGridData, x, y + 1); - + if (cp) glColor4ubv(&cp[0]); glNormal3fv(CCG_elem_no(&key, a)); glVertex3fv(CCG_elem_co(&key, a)); @@ -3891,7 +3882,7 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm, float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1); ccgDM_glNormalFast(a, b, c, d); - + if (cp) glColor4ubv(&cp[4]); glVertex3fv(d); if (cp) glColor4ubv(&cp[8]); @@ -4042,7 +4033,7 @@ static void ccgDM_release(DerivedMesh *dm) { ccgdm->multires.mmd = NULL; } - + if (ccgdm->multires.mmd) { if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED) multires_modifier_update_mdisps(dm); @@ -4335,7 +4326,7 @@ static void ccgdm_create_grids(DerivedMesh *dm) if (ccgdm->gridData) return; - + numGrids = ccgDM_getNumGrids(dm); numFaces = ccgSubSurf_getNumFaces(ss); /*gridSize = ccgDM_getGridSize(dm);*/ /*UNUSED*/ @@ -4401,7 +4392,7 @@ static void ccgDM_getGridKey(DerivedMesh *dm, CCGKey *key) static DMFlagMat *ccgDM_getGridFlagMats(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - + ccgdm_create_grids(dm); return ccgdm->gridFlagMats; } @@ -4409,7 +4400,7 @@ static DMFlagMat *ccgDM_getGridFlagMats(DerivedMesh *dm) static BLI_bitmap **ccgDM_getGridHidden(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - + ccgdm_create_grids(dm); return ccgdm->gridHidden; } @@ -4501,8 +4492,9 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) if (ob->sculpt->pbvh) { /* Note that we have to clean up exisitng pbvh instead of updating it in case it does not match current * grid_pbvh status. */ + const PBVHType pbvh_type = BKE_pbvh_type(ob->sculpt->pbvh); if (grid_pbvh) { - if (BKE_pbvh_get_ccgdm(ob->sculpt->pbvh) != NULL) { + if (pbvh_type == PBVH_GRIDS) { /* pbvh's grids, gridadj and gridfaces points to data inside ccgdm * but this can be freed on ccgdm release, this updates the pointers * when the ccgdm gets remade, the assumption is that the topology @@ -4516,7 +4508,7 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) ob->sculpt->pbvh = NULL; } } - else if (BKE_pbvh_get_ccgdm(ob->sculpt->pbvh) != NULL) { + else if (pbvh_type == PBVH_GRIDS) { BKE_pbvh_free(ob->sculpt->pbvh); ob->sculpt->pbvh = NULL; } @@ -4525,10 +4517,6 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) } if (ccgdm->pbvh) { - /* For grid pbvh, keep track of ccgdm */ - if (grid_pbvh) { - BKE_pbvh_set_ccgdm(ccgdm->pbvh, ccgdm); - } return ccgdm->pbvh; } @@ -4580,10 +4568,6 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) pbvh_show_mask_set(ccgdm->pbvh, ob->sculpt->show_mask); } - /* For grid pbvh, keep track of ccgdm. */ - if (grid_pbvh && ccgdm->pbvh) { - BKE_pbvh_set_ccgdm(ccgdm->pbvh, ccgdm); - } return ccgdm->pbvh; } @@ -5204,7 +5188,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived( if (levels == 0) return dm; - + ss = _getSubSurf(NULL, levels, 3, useSimple | CCG_USE_ARENA | CCG_CALC_NORMALS); ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple, useSubsurfUv); @@ -5297,9 +5281,9 @@ struct DerivedMesh *subsurf_make_derived_from_derived( void subsurf_calculate_limit_positions(Mesh *me, float (*r_positions)[3]) { - /* Finds the subsurf limit positions for the verts in a mesh - * and puts them in an array of floats. Please note that the - * calculated vert positions is incorrect for the verts + /* Finds the subsurf limit positions for the verts in a mesh + * and puts them in an array of floats. Please note that the + * calculated vert positions is incorrect for the verts * on the boundary of the mesh. */ CCGSubSurf *ss = _getSubSurf(NULL, 1, 3, CCG_USE_ARENA); diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c index b74143b5c074..043fc813b958 100644 --- a/source/blender/blenkernel/intern/suggestions.c +++ b/source/blender/blenkernel/intern/suggestions.c @@ -164,7 +164,7 @@ void texttool_suggest_prefix(const char *prefix, const int prefix_len) suggestions.lastmatch = suggestions.last; return; } - + first = last = NULL; for (match = suggestions.first; match; match = match->next) { cmp = BLI_strncasecmp(prefix, match->name, prefix_len); diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index a51d581dbbad..38e5ebc961cc 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -231,15 +231,15 @@ void BKE_text_init(Text *ta) tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = (char *) MEM_mallocN(1, "textline_string"); tmp->format = NULL; - + tmp->line[0] = 0; tmp->len = 0; - + tmp->next = NULL; tmp->prev = NULL; - + BLI_addhead(&ta->lines, tmp); - + ta->curl = ta->lines.first; ta->curc = 0; ta->sell = ta->lines.first; @@ -272,18 +272,18 @@ int txt_extended_ascii_as_utf8(char **str) added++; i += bad_char + 1; } - + if (added != 0) { char *newstr = MEM_mallocN(length + added + 1, "text_line"); ptrdiff_t mi = 0; i = 0; - + while ((*str)[i]) { if ((bad_char = BLI_utf8_invalid_byte((*str) + i, length - i)) == -1) { memcpy(newstr + mi, (*str) + i, length - i + 1); break; } - + memcpy(newstr + mi, (*str) + i, bad_char); BLI_str_utf8_from_unicode((*str)[i + bad_char], newstr + mi + bad_char); @@ -294,7 +294,7 @@ int txt_extended_ascii_as_utf8(char **str) MEM_freeN(*str); *str = newstr; } - + return added; } @@ -391,7 +391,7 @@ bool BKE_text_reload(Text *text) BLI_strncpy(filepath_abs, text->name, FILE_MAX); BLI_path_abs(filepath_abs, BKE_main_blendfile_path_from_global()); - + buffer = BLI_file_read_text_as_mem(filepath_abs, 0, &buffer_len); if (buffer == NULL) { return false; @@ -426,7 +426,7 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const BLI_strncpy(filepath_abs, file, FILE_MAX); if (relpath) /* can be NULL (bg mode) */ BLI_path_abs(filepath_abs, relpath); - + buffer = BLI_file_read_text_as_mem(filepath_abs, 0, &buffer_len); if (buffer == NULL) { return false; @@ -456,9 +456,9 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const else { ta->mtime = 0; } - + text_from_buf(ta, buffer, buffer_len); - + MEM_freeN(buffer); return ta; @@ -607,7 +607,7 @@ static void make_new_line(TextLine *line, char *newline) { if (line->line) MEM_freeN(line->line); if (line->format) MEM_freeN(line->format); - + line->line = newline; line->len = strlen(newline); line->format = NULL; @@ -618,16 +618,16 @@ static TextLine *txt_new_line(const char *str) TextLine *tmp; if (!str) str = ""; - + tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = MEM_mallocN(strlen(str) + 1, "textline_string"); tmp->format = NULL; - + strcpy(tmp->line, str); - + tmp->len = strlen(str); tmp->next = tmp->prev = NULL; - + return tmp; } @@ -638,29 +638,29 @@ static TextLine *txt_new_linen(const char *str, int n) tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = MEM_mallocN(n + 1, "textline_string"); tmp->format = NULL; - + BLI_strncpy(tmp->line, (str) ? str : "", n + 1); - + tmp->len = strlen(tmp->line); tmp->next = tmp->prev = NULL; - + return tmp; } void txt_clean_text(Text *text) -{ +{ TextLine **top, **bot; if (!text->lines.first) { if (text->lines.last) text->lines.first = text->lines.last; else text->lines.first = text->lines.last = txt_new_line(NULL); } - + if (!text->lines.last) text->lines.last = text->lines.first; top = (TextLine **) &text->lines.first; bot = (TextLine **) &text->lines.last; - + while ((*top)->prev) *top = (*top)->prev; while ((*bot)->next) *bot = (*bot)->next; @@ -798,7 +798,7 @@ void txt_move_up(Text *text, const bool sel) int column = txt_utf8_offset_to_column((*linep)->line, *charp); *linep = (*linep)->prev; *charp = txt_utf8_column_to_offset((*linep)->line, column); - + } else { txt_move_bol(text, sel); @@ -890,7 +890,7 @@ void txt_move_left(Text *text, const bool sel) if (text->flags & TXT_TABSTOSPACES) { tabsize = txt_calc_tab_left(*linep, *charp); } - + if (tabsize) { (*charp) -= tabsize; } @@ -926,7 +926,7 @@ void txt_move_right(Text *text, const bool sel) if (text->flags & TXT_TABSTOSPACES) { tabsize = txt_calc_tab_right(*linep, *charp); } - + if (tabsize) { (*charp) += tabsize; } @@ -934,7 +934,7 @@ void txt_move_right(Text *text, const bool sel) (*charp) += BLI_str_utf8_size((*linep)->line + *charp); } } - + if (!sel) txt_pop_sel(text); } @@ -950,7 +950,7 @@ void txt_jump_left(Text *text, const bool sel, const bool use_init_step) BLI_str_cursor_step_utf8((*linep)->line, (*linep)->len, charp, STRCUR_DIR_PREV, STRCUR_JUMP_DELIM, use_init_step); - + if (!sel) txt_pop_sel(text); } @@ -962,11 +962,11 @@ void txt_jump_right(Text *text, const bool sel, const bool use_init_step) if (sel) txt_curs_sel(text, &linep, &charp); else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); } if (!*linep) return; - + BLI_str_cursor_step_utf8((*linep)->line, (*linep)->len, charp, STRCUR_DIR_NEXT, STRCUR_JUMP_DELIM, use_init_step); - + if (!sel) txt_pop_sel(text); } @@ -978,7 +978,7 @@ void txt_move_bol(Text *text, const bool sel) if (sel) txt_curs_sel(text, &linep, &charp); else txt_curs_cur(text, &linep, &charp); if (!*linep) return; - + *charp = 0; if (!sel) txt_pop_sel(text); @@ -1043,7 +1043,7 @@ void txt_move_to(Text *text, unsigned int line, unsigned int ch, const bool sel) if (sel) txt_curs_sel(text, &linep, &charp); else txt_curs_cur(text, &linep, &charp); if (!*linep) return; - + *linep = text->lines.first; for (i = 0; i < line; i++) { if ((*linep)->next) *linep = (*linep)->next; @@ -1052,7 +1052,7 @@ void txt_move_to(Text *text, unsigned int line, unsigned int ch, const bool sel) if (ch > (unsigned int)((*linep)->len)) ch = (unsigned int)((*linep)->len); *charp = ch; - + if (!sel) txt_pop_sel(text); } @@ -1064,7 +1064,7 @@ static void txt_curs_swap(Text *text) { TextLine *tmpl; int tmpc; - + tmpl = text->curl; text->curl = text->sell; text->sell = tmpl; @@ -1081,7 +1081,7 @@ static void txt_pop_first(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1092,7 +1092,7 @@ static void txt_pop_last(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1106,7 +1106,7 @@ void txt_order_cursors(Text *text, const bool reverse) { if (!text->curl) return; if (!text->sell) return; - + /* Flip so text->curl is before/after text->sell */ if (reverse == false) { if ((txt_get_span(text->curl, text->sell) < 0) || @@ -1138,7 +1138,7 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) if (!text->sell) return; if (!txt_has_sel(text)) return; - + txt_order_cursors(text, false); if (!undoing) { @@ -1154,15 +1154,15 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) buf[text->curc + (text->sell->len - text->selc)] = 0; make_new_line(text->curl, buf); - + tmpl = text->sell; while (tmpl != text->curl) { tmpl = tmpl->prev; if (!tmpl) break; - + txt_delete_line(text, tmpl->next); } - + text->sell = text->curl; text->selc = text->curc; } @@ -1171,7 +1171,7 @@ void txt_sel_all(Text *text) { text->curl = text->lines.first; text->curc = 0; - + text->sell = text->lines.last; text->selc = text->sell->len; } @@ -1192,7 +1192,7 @@ void txt_sel_clear(Text *text) void txt_sel_line(Text *text) { if (!text->curl) return; - + text->curc = 0; text->sell = text->curl; text->selc = text->sell->len; @@ -1215,7 +1215,7 @@ char *txt_to_buf(Text *text) linef = text->lines.first; charf = 0; - + linel = text->lines.last; charl = linel->len; @@ -1223,7 +1223,7 @@ char *txt_to_buf(Text *text) length = charl - charf; buf = MEM_mallocN(length + 2, "text buffer"); - + BLI_strncpy(buf, linef->line + charf, length + 1); buf[length] = 0; } @@ -1231,37 +1231,37 @@ char *txt_to_buf(Text *text) length = linef->len - charf; length += charl; length += 2; /* For the 2 '\n' */ - + tmp = linef->next; while (tmp && tmp != linel) { length += tmp->len + 1; tmp = tmp->next; } - + buf = MEM_mallocN(length + 1, "cut buffer"); strncpy(buf, linef->line + charf, linef->len - charf); length = linef->len - charf; - + buf[length++] = '\n'; - + tmp = linef->next; while (tmp && tmp != linel) { strncpy(buf + length, tmp->line, tmp->len); length += tmp->len; - + buf[length++] = '\n'; - + tmp = tmp->next; } strncpy(buf + length, linel->line, charl); length += charl; - + /* python compiler wants an empty end line */ buf[length++] = '\n'; buf[length] = 0; } - + return buf; } @@ -1271,11 +1271,11 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) const char *s = NULL; if (!text->curl || !text->sell) return 0; - + txt_order_cursors(text, false); tl = startl = text->sell; - + if (match_case) s = strstr(&tl->line[text->selc], findstr); else s = BLI_strcasestr(&tl->line[text->selc], findstr); while (!s) { @@ -1292,7 +1292,7 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) if (tl == startl) break; } - + if (s) { int newl = txt_get_span(text->lines.first, tl); int newc = (int)(s - tl->line); @@ -1313,10 +1313,10 @@ char *txt_sel_to_buf(Text *text) if (!text->curl) return NULL; if (!text->sell) return NULL; - + if (text->curl == text->sell) { linef = linel = text->curl; - + if (text->curc < text->selc) { charf = text->curc; charl = text->selc; @@ -1336,7 +1336,7 @@ char *txt_sel_to_buf(Text *text) else { linef = text->curl; linel = text->sell; - + charf = text->curc; charl = text->selc; } @@ -1345,39 +1345,39 @@ char *txt_sel_to_buf(Text *text) length = charl - charf; buf = MEM_mallocN(length + 1, "sel buffer"); - + BLI_strncpy(buf, linef->line + charf, length + 1); } else { length += linef->len - charf; length += charl; length++; /* For the '\n' */ - + tmp = linef->next; while (tmp && tmp != linel) { length += tmp->len + 1; tmp = tmp->next; } - + buf = MEM_mallocN(length + 1, "sel buffer"); - + strncpy(buf, linef->line + charf, linef->len - charf); length = linef->len - charf; - + buf[length++] = '\n'; - + tmp = linef->next; while (tmp && tmp != linel) { strncpy(buf + length, tmp->line, tmp->len); length += tmp->len; - + buf[length++] = '\n'; - + tmp = tmp->next; } strncpy(buf + length, linel->line, charl); length += charl; - + buf[length] = 0; } @@ -1395,11 +1395,11 @@ void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer) if (!in_buffer) return; txt_delete_sel(text, utxt); - + len = strlen(in_buffer); buffer = BLI_strdupn(in_buffer, len); len += txt_extended_ascii_as_utf8(&buffer); - + if (!undoing) { txt_undo_add_blockop(text, utxt, UNDO_IBLOCK, buffer); } @@ -1409,7 +1409,7 @@ void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer) while (buffer[i] && buffer[i] != '\n') { txt_add_raw_char(text, utxt, BLI_str_utf8_as_unicode_step(buffer, &i)); } - + if (buffer[i] == '\n') { txt_split_curline(text, utxt); i++; @@ -1494,16 +1494,16 @@ void txt_print_undo(Text *text) int op; const char *ops; int linep, charp; - + dump_buffer(text); - + printf("---< Undo Buffer >---\n"); - + printf("UndoPosition is %d\n", utxt->pos); - + while (i <= utxt->pos) { op = utxt->buf[i]; - + if (op == UNDO_INSERT_1) { ops = "Insert ascii "; } @@ -1561,7 +1561,7 @@ void txt_print_undo(Text *text) else { ops = "Unknown"; } - + printf("Op (%o) at %d = %s", op, i, ops); if (op >= UNDO_INSERT_1 && op <= UNDO_DEL_4) { i++; @@ -1602,14 +1602,14 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf(" (length %d) <", linep); - + while (linep > 0) { putchar(utxt->buf[i]); linep--; i++; } - + linep = utxt->buf[i]; i++; linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; @@ -1626,7 +1626,7 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf("to <%d, %d> ", linep, charp); charp = utxt->buf[i]; i++; @@ -1636,17 +1636,17 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf("from <%d, %d>", linep, charp); } - + printf(" %d\n", i); i++; } } #endif -static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short value) +static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short value) { undo_buf[*undo_pos] = (value) & 0xff; (*undo_pos)++; @@ -1654,7 +1654,7 @@ static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short (*undo_pos)++; } -static void txt_undo_store_uint32(char *undo_buf, int *undo_pos, unsigned int value) +static void txt_undo_store_uint32(char *undo_buf, int *undo_pos, unsigned int value) { undo_buf[*undo_pos] = (value) & 0xff; (*undo_pos)++; @@ -1738,7 +1738,7 @@ static void txt_undo_add_charop(Text *text, TextUndoBuf *utxt, int op_start, uns { char utf8[BLI_UTF8_MAX]; size_t i, utf8_size = BLI_str_utf8_from_unicode(c, utf8); - + if (utf8_size < 4 && 0) { if (!max_undo_test(utxt, 2 + 6 + utf8_size + 1)) { return; @@ -1772,7 +1772,7 @@ static void txt_undo_add_charop(Text *text, TextUndoBuf *utxt, int op_start, uns /* 1 byte */ utxt->buf[utxt->pos] = op_start + 3; } - + txt_undo_end(text, utxt); } @@ -1871,10 +1871,10 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s { unsigned int unicode; char utf8[BLI_UTF8_MAX + 1]; - + switch (bytes) { case 1: /* ascii */ - unicode = undo_buf[*undo_pos]; (*undo_pos)--; + unicode = undo_buf[*undo_pos]; (*undo_pos)--; break; case 2: /* 2-byte symbol */ utf8[2] = '\0'; @@ -1898,7 +1898,7 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1947,10 +1947,10 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s { unsigned int unicode; char utf8[BLI_UTF8_MAX + 1]; - + switch (bytes) { case 1: /* ascii */ - unicode = undo_buf[*undo_pos]; (*undo_pos)++; + unicode = undo_buf[*undo_pos]; (*undo_pos)++; break; case 2: /* 2-byte symbol */ utf8[0] = undo_buf[*undo_pos]; (*undo_pos)++; @@ -1974,7 +1974,7 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1988,7 +1988,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) unsigned short curc, selc; unsigned short charp; char *buf; - + if (utxt->pos < 0) { return; } @@ -1996,21 +1996,21 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) utxt->pos--; undoing = 1; - + switch (op) { case UNDO_INSERT_1: case UNDO_INSERT_2: case UNDO_INSERT_3: case UNDO_INSERT_4: utxt->pos -= op - UNDO_INSERT_1 + 1; - + /* get and restore the cursors */ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + txt_delete_char(text, utxt); - + utxt->pos--; break; @@ -2020,12 +2020,12 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) case UNDO_BS_4: charp = op - UNDO_BS_1 + 1; uni_char = txt_undo_read_unicode(utxt->buf, &utxt->pos, charp); - + /* get and restore the cursors */ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + txt_add_char(text, utxt, uni_char); utxt->pos--; @@ -2071,7 +2071,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) /* move cur to location that needs buff inserted */ txt_move_to(text, curln, curc, 0); - + txt_insert_buf(text, utxt, buf); MEM_freeN(buf); @@ -2080,7 +2080,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) txt_move_to(text, selln, selc, 1); utxt->pos--; - + break; } case UNDO_IBLOCK: @@ -2088,7 +2088,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) int i; /* length of the string in the buffer */ linep = txt_undo_read_uint32(utxt->buf, &utxt->pos); - + /* txt_backspace_char removes utf8-characters, not bytes */ buf = MEM_mallocN(linep + 1, "iblock buffer"); for (i = 0; i < linep; i++) { @@ -2098,29 +2098,29 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) buf[i] = 0; linep = BLI_strlen_utf8(buf); MEM_freeN(buf); - + /* skip over the length that was stored again */ utxt->pos -= 4; /* get and restore the cursors */ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc); - + txt_move_to(text, curln, curc, 0); txt_move_to(text, selln, selc, 1); - + if ((curln == selln) && (curc == selc)) { /* disable tabs to spaces since moving right may involve skipping multiple spaces */ prev_flags = text->flags; text->flags &= ~TXT_TABSTOSPACES; - + for (i = 0; i < linep; i++) txt_move_right(text, 1); - + text->flags = prev_flags; } - + txt_delete_selected(text, utxt); - + utxt->pos--; break; } @@ -2133,7 +2133,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc); txt_move_to(text, curln, curc, 0); txt_move_to(text, selln, selc, 1); - + if (op == UNDO_INDENT) { txt_unindent(text, utxt); } @@ -2149,7 +2149,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) else if (op == UNDO_MOVE_LINES_DOWN) { txt_move_lines(text, utxt, TXT_MOVE_LINE_UP); } - + utxt->pos--; break; case UNDO_UNINDENT: @@ -2198,10 +2198,10 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) default: //XXX error("Undo buffer error - resetting"); utxt->pos = -1; - + break; } - + undoing = 0; } @@ -2214,15 +2214,15 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) unsigned int uni_uchar; unsigned int curln, selln; unsigned short curc, selc; - + utxt->pos++; op = utxt->buf[utxt->pos]; - + if (!op) { utxt->pos--; return; } - + undoing = 1; switch (op) { @@ -2231,12 +2231,12 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) case UNDO_INSERT_3: case UNDO_INSERT_4: utxt->pos++; - + /* get and restore the cursors */ txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + charp = op - UNDO_INSERT_1 + 1; uni_uchar = txt_redo_read_unicode(utxt->buf, &utxt->pos, charp); @@ -2255,7 +2255,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) txt_move_to(text, curln, curc, 1); utxt->pos += op - UNDO_BS_1 + 1; - + /* move right so we backspace the correct char */ txt_move_right(text, 0); txt_backspace_char(text, utxt); @@ -2272,7 +2272,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + utxt->pos += op - UNDO_DEL_1 + 1; txt_delete_char(text, utxt); @@ -2289,12 +2289,12 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) /* length of the block */ linep = txt_redo_read_uint32(utxt->buf, &utxt->pos); - + utxt->pos += linep; /* skip over the length that was stored again */ utxt->pos += 4; - + txt_delete_sel(text, utxt); break; @@ -2314,7 +2314,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) memcpy(buf, &utxt->buf[utxt->pos], linep); utxt->pos += linep; buf[linep] = 0; - + txt_insert_buf(text, utxt, buf); MEM_freeN(buf); @@ -2322,7 +2322,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) utxt->pos += 4; break; - + case UNDO_INDENT: case UNDO_COMMENT: case UNDO_UNCOMMENT: @@ -2391,15 +2391,15 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) default: //XXX error("Undo buffer error - resetting"); utxt->pos = -1; - + break; } - + undoing = 0; } /**************************/ -/* Line editing functions */ +/* Line editing functions */ /**************************/ void txt_split_curline(Text *text, TextUndoBuf *utxt) @@ -2412,13 +2412,13 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) txt_delete_sel(text, utxt); if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, '\n'); - + /* Make the two half strings */ left = MEM_mallocN(text->curc + 1, "textline_string"); if (text->curc) memcpy(left, text->curl->line, text->curc); left[text->curc] = 0; - + right = MEM_mallocN(text->curl->len - text->curc + 1, "textline_string"); memcpy(right, text->curl->line + text->curc, text->curl->len - text->curc + 1); @@ -2426,7 +2426,7 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) if (text->curl->format) MEM_freeN(text->curl->format); /* Make the new TextLine */ - + ins = MEM_mallocN(sizeof(TextLine), "textline"); ins->line = left; ins->format = NULL; @@ -2435,14 +2435,14 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) text->curl->line = right; text->curl->format = NULL; text->curl->len = text->curl->len - text->curc; - + BLI_insertlinkbefore(&text->lines, text->curl, ins); - + text->curc = 0; - + txt_make_dirty(text); txt_clean_text(text); - + txt_pop_sel(text); } @@ -2451,7 +2451,7 @@ static void txt_delete_line(Text *text, TextLine *line) if (!text->curl) return; BLI_remlink(&text->lines, line); - + if (line->line) MEM_freeN(line->line); if (line->format) MEM_freeN(line->format); @@ -2464,21 +2464,21 @@ static void txt_delete_line(Text *text, TextLine *line) static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb) { char *tmp, *s; - + if (!linea || !lineb) return; tmp = MEM_mallocN(linea->len + lineb->len + 1, "textline_string"); - + s = tmp; s += BLI_strcpy_rlen(s, linea->line); s += BLI_strcpy_rlen(s, lineb->line); (void)s; make_new_line(linea, tmp); - + txt_delete_line(text, lineb); - + txt_make_dirty(text); txt_clean_text(text); } @@ -2486,16 +2486,16 @@ static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb) void txt_duplicate_line(Text *text, TextUndoBuf *utxt) { TextLine *textline; - + if (!text->curl) return; - + if (text->curl == text->sell) { textline = txt_new_line(text->curl->line); BLI_insertlinkafter(&text->lines, text->curl, textline); - + txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_op(text, utxt, UNDO_DUPLICATE); } } @@ -2522,7 +2522,7 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) else { /* Just deleting a char */ size_t c_len = 0; c = BLI_str_utf8_as_unicode_and_size(text->curl->line + text->curc, &c_len); - + memmove(text->curl->line + text->curc, text->curl->line + text->curc + c_len, text->curl->len - text->curc - c_len + 1); text->curl->len -= c_len; @@ -2532,7 +2532,7 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_DEL_1, c); } @@ -2546,9 +2546,9 @@ void txt_delete_word(Text *text, TextUndoBuf *utxt) void txt_backspace_char(Text *text, TextUndoBuf *utxt) { unsigned int c = '\n'; - + if (!text->curl) return; - + if (txt_has_sel(text)) { /* deleting a selection */ txt_delete_sel(text, utxt); txt_make_dirty(text); @@ -2556,10 +2556,10 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) } else if (text->curc == 0) { /* Appending two lines */ if (!text->curl->prev) return; - + text->curl = text->curl->prev; text->curc = text->curl->len; - + txt_combine_lines(text, text->curl, text->curl->next); txt_pop_sel(text); } @@ -2567,7 +2567,7 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) size_t c_len = 0; const char *prev = BLI_str_prev_char_utf8(text->curl->line + text->curc); c = BLI_str_utf8_as_unicode_and_size(prev, &c_len); - + /* source and destination overlap, don't use memcpy() */ memmove(text->curl->line + text->curc - c_len, text->curl->line + text->curc, @@ -2581,7 +2581,7 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_BS_1, c); } @@ -2618,7 +2618,7 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, txt_split_curline(text, utxt); return true; } - + /* insert spaces rather than tabs */ if (add == '\t' && replace_tabs) { txt_convert_tab_to_spaces(text, utxt); @@ -2626,23 +2626,23 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, } txt_delete_sel(text, utxt); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, add); add_len = BLI_str_utf8_from_unicode(add, ch); - + tmp = MEM_mallocN(text->curl->len + add_len + 1, "textline_string"); - + memcpy(tmp, text->curl->line, text->curc); memcpy(tmp + text->curc, ch, add_len); memcpy(tmp + text->curc + add_len, text->curl->line + text->curc, text->curl->len - text->curc + 1); make_new_line(text->curl, tmp); - + text->curc += add_len; txt_pop_sel(text); - + txt_make_dirty(text); txt_clean_text(text); @@ -2677,10 +2677,10 @@ bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add) if (text->curc == text->curl->len || txt_has_sel(text) || add == '\n') { return txt_add_char(text, utxt, add); } - + del = BLI_str_utf8_as_unicode_and_size(text->curl->line + text->curc, &del_size); add_size = BLI_str_utf8_from_unicode(add, ch); - + if (add_size > del_size) { char *tmp = MEM_mallocN(text->curl->len + add_size - del_size + 1, "textline_string"); memcpy(tmp, text->curl->line, text->curc); @@ -2692,11 +2692,11 @@ bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add) char *tmp = text->curl->line; memmove(tmp + text->curc + add_size, tmp + text->curc + del_size, text->curl->len - text->curc - del_size + 1); } - + memcpy(text->curl->line + text->curc, ch, add_size); text->curc += add_size; text->curl->len += add_size - del_size; - + txt_pop_sel(text); txt_make_dirty(text); txt_clean_text(text); @@ -2751,7 +2751,7 @@ static void txt_select_prefix(Text *text, const char *add) txt_make_dirty(text); txt_clean_text(text); } - + if (text->curl == text->sell) { text->selc += indentlen; break; @@ -2768,7 +2768,7 @@ static void txt_select_prefix(Text *text, const char *add) text->curl = text->curl->prev; num--; } - + /* caller must handle undo */ } @@ -2818,10 +2818,10 @@ static void txt_select_unprefix( (*r_line_index_mask_len) += 1; } } - + txt_make_dirty(text); txt_clean_text(text); - + if (text->curl == text->sell) { if (changed) text->selc = MAX2(text->selc - indentlen, 0); @@ -2832,7 +2832,7 @@ static void txt_select_unprefix( num++; } - + } if (unindented_first) @@ -2901,7 +2901,7 @@ void txt_unindent(Text *text, TextUndoBuf *utxt) const char *prefix = (text->flags & TXT_TABSTOSPACES) ? tab_to_spaces : "\t"; ListBase line_index_mask; int line_index_mask_len; - + if (ELEM(NULL, text->curl, text->sell)) { return; } @@ -2922,13 +2922,13 @@ void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction) BLI_assert(ELEM(direction, TXT_MOVE_LINE_UP, TXT_MOVE_LINE_DOWN)); if (!text->curl || !text->sell) return; - + txt_order_cursors(text, false); line_other = (direction == TXT_MOVE_LINE_DOWN) ? text->sell->next : text->curl->prev; - + if (!line_other) return; - + BLI_remlink(&text->lines, line_other); if (direction == TXT_MOVE_LINE_DOWN) { @@ -2940,7 +2940,7 @@ void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) { txt_undo_add_op(text, utxt, (direction == TXT_MOVE_LINE_DOWN) ? UNDO_MOVE_LINES_DOWN : UNDO_MOVE_LINES_UP); } @@ -2970,7 +2970,7 @@ int txt_setcurr_tab_spaces(Text *text, int space) /* if we find a ':' on this line, then add a tab but not if it is: * 1) in a comment * 2) within an identifier - * 3) after the cursor (text->curc), i.e. when creating space before a function def [#25414] + * 3) after the cursor (text->curc), i.e. when creating space before a function def [#25414] */ int a; bool is_indent = false; diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index 3228a20c21c2..3481e696d5a4 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -78,9 +78,9 @@ TexMapping *BKE_texture_mapping_add(int type) { TexMapping *texmap = MEM_callocN(sizeof(TexMapping), "TexMapping"); - + BKE_texture_mapping_default(texmap, type); - + return texmap; } @@ -134,7 +134,7 @@ void BKE_texture_mapping_init(TexMapping *texmap) if (fabsf(size[2]) < 1e-5f) size[2] = signf(size[2]) * 1e-5f; } - + size_to_mat4(smat, texmap->size); /* rotation */ @@ -175,9 +175,9 @@ void BKE_texture_mapping_init(TexMapping *texmap) ColorMapping *BKE_texture_colormapping_add(void) { ColorMapping *colormap = MEM_callocN(sizeof(ColorMapping), "ColorMapping"); - + BKE_texture_colormapping_default(colormap); - + return colormap; } @@ -229,7 +229,7 @@ void BKE_texture_free(Tex *tex) BKE_texture_ocean_free(tex->ot); tex->ot = NULL; } - + BKE_icon_id_delete((ID *)tex); BKE_previewimg_free(&tex->preview); } @@ -298,30 +298,30 @@ void BKE_texture_default(Tex *tex) tex->pd->radius = 0.3f; tex->pd->falloff_type = TEX_PD_FALLOFF_STD; } - + if (tex->vd) { tex->vd->resol[0] = tex->vd->resol[1] = tex->vd->resol[2] = 0; tex->vd->interp_type = TEX_VD_LINEAR; tex->vd->file_format = TEX_VD_SMOKE; } - + if (tex->ot) { tex->ot->output = TEX_OCN_DISPLACEMENT; tex->ot->object = NULL; } - + tex->iuser.fie_ima = 2; tex->iuser.ok = 1; tex->iuser.frames = 100; tex->iuser.sfra = 1; - + tex->preview = NULL; } void BKE_texture_type_set(Tex *tex, int type) { switch (type) { - + case TEX_VOXELDATA: if (tex->vd == NULL) tex->vd = BKE_texture_voxeldata_add(); @@ -339,7 +339,7 @@ void BKE_texture_type_set(Tex *tex, int type) tex->ot = BKE_texture_ocean_add(); break; } - + tex->type = type; } @@ -350,9 +350,9 @@ Tex *BKE_texture_add(Main *bmain, const char *name) Tex *tex; tex = BKE_libblock_alloc(bmain, ID_TE, name, 0); - + BKE_texture_default(tex); - + return tex; } @@ -436,11 +436,11 @@ void BKE_texture_mtex_default(MTex *mtex) MTex *BKE_texture_mtex_add(void) { MTex *mtex; - + mtex = MEM_callocN(sizeof(MTex), "BKE_texture_mtex_add"); - + BKE_texture_mtex_default(mtex); - + return mtex; } @@ -455,7 +455,7 @@ MTex *BKE_texture_mtex_add_id(ID *id, int slot) if (mtex_ar == NULL) { return NULL; } - + if (slot == -1) { /* find first free */ int i; @@ -561,11 +561,11 @@ Tex *BKE_texture_localize(Tex *tex) * ... Once f*** nodes are fully converted to that too :( */ Tex *texn; - + texn = BKE_libblock_copy_nolib(&tex->id, false); - + /* image texture: BKE_texture_free also doesn't decrease */ - + if (texn->coba) texn->coba = MEM_dupallocN(texn->coba); if (texn->env) { texn->env = BKE_texture_envmap_copy(texn->env, LIB_ID_CREATE_NO_USER_REFCOUNT); @@ -580,13 +580,13 @@ Tex *BKE_texture_localize(Tex *tex) if (texn->ot) { texn->ot = BKE_texture_ocean_copy(tex->ot, LIB_ID_CREATE_NO_USER_REFCOUNT); } - + texn->preview = NULL; - + if (tex->nodetree) { texn->nodetree = ntreeLocalize(tex->nodetree); } - + return texn; } @@ -602,10 +602,10 @@ Tex *give_current_object_texture(Object *ob) { Material *ma, *node_ma; Tex *tex = NULL; - + if (ob == NULL) return NULL; if (ob->totcol == 0 && !(ob->type == OB_LAMP)) return NULL; - + if (ob->type == OB_LAMP) { tex = give_current_lamp_texture(ob->data); } @@ -617,7 +617,7 @@ Tex *give_current_object_texture(Object *ob) tex = give_current_material_texture(ma); } - + return tex; } @@ -646,7 +646,7 @@ void set_current_lamp_texture(Lamp *la, Tex *newtex) la->mtex[act] = BKE_texture_mtex_add(); la->mtex[act]->texco = TEXCO_GLOB; } - + la->mtex[act]->tex = newtex; id_us_plus(&newtex->id); } @@ -695,7 +695,7 @@ bNode *give_current_material_texture_node(Material *ma) { if (ma && ma->use_nodes && ma->nodetree) return nodeGetActiveID(ma->nodetree, ID_TE); - + return NULL; } @@ -704,7 +704,7 @@ Tex *give_current_material_texture(Material *ma) MTex *mtex = NULL; Tex *tex = NULL; bNode *node; - + if (ma && ma->use_nodes && ma->nodetree) { /* first check texture, then material, this works together * with a hack that clears the active ID flag for textures on @@ -721,7 +721,7 @@ Tex *give_current_material_texture(Material *ma) mtex = ma->mtex[(int)(ma->texact)]; if (mtex) tex = mtex->tex; } - + return tex; } @@ -817,7 +817,7 @@ void set_current_material_texture(Material *ma, Tex *newtex) ma->mtex[act]->texco = TEXCO_ORCO; } } - + ma->mtex[act]->tex = newtex; id_us_plus(&newtex->id); } @@ -846,12 +846,12 @@ Tex *give_current_world_texture(World *world) { MTex *mtex = NULL; Tex *tex = NULL; - + if (!world) return NULL; - + mtex = world->mtex[(int)(world->texact)]; if (mtex) tex = mtex->tex; - + return tex; } @@ -867,7 +867,7 @@ void set_current_world_texture(World *wo, Tex *newtex) wo->mtex[act] = BKE_texture_mtex_add(); wo->mtex[act]->texco = TEXCO_VIEW; } - + wo->mtex[act]->tex = newtex; id_us_plus(&newtex->id); } @@ -897,12 +897,12 @@ Tex *give_current_particle_texture(ParticleSettings *part) { MTex *mtex = NULL; Tex *tex = NULL; - + if (!part) return NULL; - + mtex = part->mtex[(int)(part->texact)]; if (mtex) tex = mtex->tex; - + return tex; } @@ -919,7 +919,7 @@ void set_current_particle_texture(ParticleSettings *part, Tex *newtex) part->mtex[act]->texco = TEXCO_ORCO; part->mtex[act]->blendtype = MTEX_MUL; } - + part->mtex[act]->tex = newtex; id_us_plus(&newtex->id); } @@ -934,7 +934,7 @@ void set_current_particle_texture(ParticleSettings *part, Tex *newtex) EnvMap *BKE_texture_envmap_add(void) { EnvMap *env; - + env = MEM_callocN(sizeof(EnvMap), "envmap"); env->type = ENV_CUBE; env->stype = ENV_ANIM; @@ -946,7 +946,7 @@ EnvMap *BKE_texture_envmap_add(void) env->lodfactor = 1.0f; return env; -} +} /* ------------------------------------------------------------------------- */ @@ -954,7 +954,7 @@ EnvMap *BKE_texture_envmap_copy(const EnvMap *env, const int flag) { EnvMap *envn; int a; - + envn = MEM_dupallocN(env); envn->ok = 0; for (a = 0; a < 6; a++) { @@ -972,7 +972,7 @@ EnvMap *BKE_texture_envmap_copy(const EnvMap *env, const int flag) void BKE_texture_envmap_free_data(EnvMap *env) { unsigned int part; - + for (part = 0; part < 6; part++) { if (env->cube[part]) IMB_freeImBuf(env->cube[part]); @@ -985,10 +985,10 @@ void BKE_texture_envmap_free_data(EnvMap *env) void BKE_texture_envmap_free(EnvMap *env) { - + BKE_texture_envmap_free_data(env); MEM_freeN(env); - + } /* ------------------------------------------------------------------------- */ @@ -1025,7 +1025,7 @@ PointDensity *BKE_texture_pointdensity_add(void) PointDensity *pd = MEM_callocN(sizeof(PointDensity), "pointdensity"); BKE_texture_pointdensity_init_data(pd); return pd; -} +} PointDensity *BKE_texture_pointdensity_copy(const PointDensity *pd, const int UNUSED(flag)) { @@ -1075,13 +1075,13 @@ void BKE_texture_voxeldata_free_data(VoxelData *vd) } } - + void BKE_texture_voxeldata_free(VoxelData *vd) { BKE_texture_voxeldata_free_data(vd); MEM_freeN(vd); } - + VoxelData *BKE_texture_voxeldata_add(void) { VoxelData *vd; @@ -1096,10 +1096,10 @@ VoxelData *BKE_texture_voxeldata_add(void) vd->object = NULL; vd->cachedframe = -1; vd->ok = 0; - + return vd; } - + VoxelData *BKE_texture_voxeldata_copy(VoxelData *vd) { VoxelData *vdn; @@ -1115,18 +1115,18 @@ VoxelData *BKE_texture_voxeldata_copy(VoxelData *vd) OceanTex *BKE_texture_ocean_add(void) { OceanTex *ot; - + ot = MEM_callocN(sizeof(struct OceanTex), "ocean texture"); ot->output = TEX_OCN_DISPLACEMENT; ot->object = NULL; - + return ot; } OceanTex *BKE_texture_ocean_copy(const OceanTex *ot, const int UNUSED(flag)) { OceanTex *otn = MEM_dupallocN(ot); - + return otn; } diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index f9d34534a450..830732f4ce2f 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -213,14 +213,18 @@ static void tracking_tracks_copy(ListBase *tracks_dst, const ListBase *tracks_sr /* copy the whole list of plane tracks (need whole MovieTracking structures due to embedded pointers to tracks). * WARNING: implies tracking_[dst/src] and their tracks have already been copied. */ static void tracking_plane_tracks_copy( - ListBase *plane_tracks_dst, const ListBase *plane_tracks_src, GHash *tracks_mapping, const int flag) + ListBase *plane_tracks_list_dst, const ListBase *plane_tracks_list_src, + GHash *tracks_mapping, const int flag) { MovieTrackingPlaneTrack *plane_track_dst, *plane_track_src; - BLI_listbase_clear(plane_tracks_dst); + BLI_listbase_clear(plane_tracks_list_dst); - for (plane_track_src = plane_tracks_src->first; plane_track_src != NULL; plane_track_src = plane_track_src->next) { - plane_track_dst = MEM_dupallocN(plane_tracks_src); + for (plane_track_src = plane_tracks_list_src->first; + plane_track_src != NULL; + plane_track_src = plane_track_src->next) + { + plane_track_dst = MEM_dupallocN(plane_track_src); if (plane_track_src->markers) { plane_track_dst->markers = MEM_dupallocN(plane_track_src->markers); } @@ -231,7 +235,7 @@ static void tracking_plane_tracks_copy( if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus(&plane_track_dst->image->id); } - BLI_addtail(plane_tracks_dst, plane_track_dst); + BLI_addtail(plane_tracks_list_dst, plane_track_dst); } } diff --git a/source/blender/blenkernel/intern/tracking_solver.c b/source/blender/blenkernel/intern/tracking_solver.c index c21883c6eb88..a5d354492291 100644 --- a/source/blender/blenkernel/intern/tracking_solver.c +++ b/source/blender/blenkernel/intern/tracking_solver.c @@ -518,7 +518,7 @@ bool BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieT BKE_tracking_dopesheet_tag_update(tracking); object = BKE_tracking_object_get_named(tracking, context->object_name); - + if (context->is_camera) reconstruction = &tracking->reconstruction; else diff --git a/source/blender/blenkernel/intern/undo_system.c b/source/blender/blenkernel/intern/undo_system.c index ba7d432fab30..0ebfb4065e41 100644 --- a/source/blender/blenkernel/intern/undo_system.c +++ b/source/blender/blenkernel/intern/undo_system.c @@ -254,6 +254,7 @@ void BKE_undosys_stack_clear_active(UndoStack *ustack) static bool undosys_stack_push_main(UndoStack *ustack, const char *name, struct Main *bmain) { UNDO_NESTED_ASSERT(false); + BLI_assert(ustack->step_init == NULL); CLOG_INFO(&LOG, 1, "'%s'", name); bContext *C_temp = CTX_create(); CTX_data_main_set(C_temp, bmain); @@ -434,7 +435,13 @@ bool BKE_undosys_step_push_with_type(UndoStack *ustack, bContext *C, const char Main *bmain = G.main; if (bmain->is_memfile_undo_written == false) { const char *name_internal = "MemFile Internal"; - if (undosys_stack_push_main(ustack, name_internal, bmain)) { + /* Don't let 'step_init' cause issues when adding memfile undo step. */ + void *step_init = ustack->step_init; + ustack->step_init = NULL; + const bool ok = undosys_stack_push_main(ustack, name_internal, bmain); + /* Restore 'step_init'. */ + ustack->step_init = step_init; + if (ok) { UndoStep *us = ustack->steps.last; BLI_assert(STREQ(us->name, name_internal)); us->skip = true; @@ -857,7 +864,7 @@ ID *BKE_undosys_ID_map_lookup_with_prev(const UndoIDPtrMap *map, ID *id_src, ID return id_prev_match[1]; } else { - ID *id_dst = BKE_undosys_ID_map_lookup(map, id_src); + ID *id_dst = (id_src->lib == NULL) ? BKE_undosys_ID_map_lookup(map, id_src) : id_src; id_prev_match[0] = id_src; id_prev_match[1] = id_dst; return id_dst; diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index 5736c9331bf5..545ca41c9c01 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -72,7 +72,7 @@ void BKE_world_free(World *wrld) } GPU_material_free(&wrld->gpumaterial); - + BKE_icon_id_delete((struct ID *)wrld); BKE_previewimg_free(&wrld->preview); } @@ -101,7 +101,7 @@ void BKE_world_init(World *wrld) wrld->aobias = 0.05f; wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY; wrld->ao_approx_error = 0.25f; - + wrld->preview = NULL; wrld->miststa = 5.0f; wrld->mistdist = 25.0f; @@ -168,9 +168,9 @@ World *BKE_world_localize(World *wrld) World *wrldn; int a; - + wrldn = BKE_libblock_copy_nolib(&wrld->id, false); - + for (a = 0; a < MAX_MTEX; a++) { if (wrld->mtex[a]) { wrldn->mtex[a] = MEM_mallocN(sizeof(MTex), __func__); @@ -180,11 +180,11 @@ World *BKE_world_localize(World *wrld) if (wrld->nodetree) wrldn->nodetree = ntreeLocalize(wrld->nodetree); - + wrldn->preview = NULL; - + BLI_listbase_clear(&wrldn->gpumaterial); - + return wrldn; } diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c index 029407235206..7e989b6588f7 100644 --- a/source/blender/blenkernel/intern/writeavi.c +++ b/source/blender/blenkernel/intern/writeavi.c @@ -164,7 +164,7 @@ static void filepath_avi(char *string, RenderData *rd, bool preview, const char BLI_make_existing_file(string); if (rd->scemode & R_EXTENSION) { - if (!BLI_testextensie(string, ".avi")) { + if (!BLI_path_extension_check(string, ".avi")) { BLI_path_frame_range(string, sfra, efra, 4); strcat(string, ".avi"); } @@ -203,7 +203,7 @@ static int start_avi(void *context_v, Scene *UNUSED(scene), RenderData *rd, int BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file"); return 0; } - + AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_WIDTH, &x); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_HEIGHT, &y); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_QUALITY, &quality); @@ -213,7 +213,7 @@ static int start_avi(void *context_v, Scene *UNUSED(scene), RenderData *rd, int avi->odd_fields = 0; /* avi->interlace = rd->mode & R_FIELDS; */ /* avi->odd_fields = (rd->mode & R_ODDFIELD) ? 1 : 0; */ - + printf("Created avi: %s\n", name); return 1; } @@ -225,7 +225,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, int x, y; char *cp, rt; AviMovie *avi = context_v; - + if (avi == NULL) return 0; @@ -236,7 +236,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, /* flip y and convert to abgr */ for (y = 0; y < recty; y++, rt1 += rectx, rt2 -= rectx) { memcpy(rt1, rt2, rectx * sizeof(int)); - + cp = (char *)rt1; for (x = rectx; x > 0; x--) { rt = cp[0]; @@ -248,7 +248,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, cp += 4; } } - + AVI_write_frame(avi, (frame - start_frame), AVI_FORMAT_RGB32, rectot, rectx * recty * 4); // printf("added frame %3d (frame %3d in avi): ", frame, frame-start_frame); diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c index bf702aa95b97..2bee16a30c80 100644 --- a/source/blender/blenkernel/intern/writeffmpeg.c +++ b/source/blender/blenkernel/intern/writeffmpeg.c @@ -231,7 +231,7 @@ static AVFrame *alloc_picture(int pix_fmt, int width, int height) AVFrame *f; uint8_t *buf; int size; - + /* allocate space for the struct */ f = av_frame_alloc(); if (!f) return NULL; @@ -515,7 +515,7 @@ static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char if (!rd->ffcodecdata.properties) { return; } - + prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name); if (!prop) { return; @@ -544,13 +544,13 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int st->id = 0; /* Set up the codec context */ - + c = st->codec; c->codec_id = codec_id; c->codec_type = AVMEDIA_TYPE_VIDEO; /* Get some values from the current render settings */ - + c->width = rectx; c->height = recty; @@ -567,7 +567,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int c->time_base.den = rd->frs_sec * 100000; c->time_base.num = ((double) rd->frs_sec_base) * 100000; } - + c->gop_size = context->ffmpeg_gop_size; c->max_b_frames = context->ffmpeg_max_b_frames; @@ -621,11 +621,11 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int /* Deprecated and not doing anything since July 2015, deleted in recent ffmpeg */ //c->me_method = ME_EPZS; - + codec = avcodec_find_encoder(c->codec_id); if (!codec) return NULL; - + /* Be sure to use the correct pixel format(e.g. RGB, YUV) */ if (codec->pix_fmts) { @@ -647,7 +647,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int c->qmin = 10; c->qmax = 51; } - + /* Keep lossless encodes in the RGB domain. */ if (codec_id == AV_CODEC_ID_HUFFYUV) { if (rd->im_format.planes == R_IMF_PLANES_RGBA) { @@ -685,7 +685,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int PRINT("Using global header\n"); c->flags |= CODEC_FLAG_GLOBAL_HEADER; } - + /* Determine whether we are encoding interlaced material or not */ if (rd->mode & R_FIELDS) { PRINT("Encoding interlaced video\n"); @@ -890,7 +890,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int name, context->ffmpeg_type, context->ffmpeg_codec, context->ffmpeg_audio_codec, context->ffmpeg_video_bitrate, context->ffmpeg_audio_bitrate, context->ffmpeg_gop_size, context->ffmpeg_autosplit, rectx, recty); - + exts = get_file_extensions(context->ffmpeg_type); if (!exts) { BKE_report(reports, RPT_ERROR, "No valid formats found"); @@ -978,7 +978,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int goto fail; } } - + if (context->ffmpeg_type == FFMPEG_DV) { fmt->audio_codec = AV_CODEC_ID_PCM_S16LE; if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) { @@ -986,7 +986,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int goto fail; } } - + if (fmt->video_codec != AV_CODEC_ID_NONE) { context->video_stream = alloc_video_stream(context, rd, fmt->video_codec, of, rectx, recty, error, sizeof(error)); PRINT("alloc video stream %p\n", context->video_stream); @@ -1072,14 +1072,14 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int static void flush_ffmpeg(FFMpegContext *context) { int ret = 0; - + AVCodecContext *c = context->video_stream->codec; /* get the delayed frames */ while (1) { int got_output; AVPacket packet = { 0 }; av_init_packet(&packet); - + ret = avcodec_encode_video2(c, &packet, NULL, &got_output); if (ret < 0) { fprintf(stderr, "Error encoding delayed frame %d\n", ret); @@ -1305,11 +1305,11 @@ static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit) PRINT("Flushing delayed frames...\n"); flush_ffmpeg(context); } - + if (context->outfile) { av_write_trailer(context->outfile); } - + /* Close the video codec */ if (context->video_stream != NULL && context->video_stream->codec != NULL) { @@ -1371,7 +1371,7 @@ void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_) { struct IDProperty *prop = (struct IDProperty *) prop_; IDProperty *group; - + if (!rd->ffcodecdata.properties) { return; } @@ -1390,17 +1390,17 @@ static IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, con IDPropertyTemplate val; int idp_type; char name[256]; - + val.i = 0; avcodec_get_context_defaults3(&c, NULL); if (!rd->ffcodecdata.properties) { - rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); + rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); } group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type); - + if (!group) { group = IDP_New(IDP_GROUP, &val, type); IDP_AddToGroup(rd->ffcodecdata.properties, group); @@ -1460,7 +1460,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char char *name; char *param; IDProperty *prop = NULL; - + avcodec_get_context_defaults3(&c, NULL); BLI_strncpy(name_, str, sizeof(name_)); @@ -1477,7 +1477,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *param++ = '\0'; while (*param == ' ') param++; } - + o = av_opt_find(&c, name, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ); if (!o) { PRINT("Ignoring unknown expert option %s\n", str); @@ -1498,7 +1498,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char else { prop = BKE_ffmpeg_property_add(rd, (char *) type, o, NULL); } - + if (!prop) { return 0; diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c index 4757186f546b..ebd6de6009ee 100644 --- a/source/blender/blenkernel/intern/writeframeserver.c +++ b/source/blender/blenkernel/intern/writeframeserver.c @@ -118,7 +118,7 @@ int BKE_frameserver_start(void *context_v, struct Scene *scene, RenderData *UNUS struct sockaddr_in addr; int arg = 1; FrameserverContext *context = context_v; - + (void)scene; /* unused */ if (!startup_socket_system()) { @@ -210,7 +210,7 @@ static int handle_request(FrameserverContext *context, RenderData *rd, char *req if (memcmp(req, "GET ", 4) != 0) { return -1; } - + p = req + 4; path = p; @@ -362,7 +362,7 @@ static void serve_ppm(FrameserverContext *context, int *pixels, int rectx, int r target[2] = src[2]; target[1] = src[1]; target[0] = src[0]; - + target += 3; src += 4; } diff --git a/source/blender/blenkernel/nla_private.h b/source/blender/blenkernel/nla_private.h index 2e38e33a3087..71937531dacb 100644 --- a/source/blender/blenkernel/nla_private.h +++ b/source/blender/blenkernel/nla_private.h @@ -38,13 +38,13 @@ /* used for list of strips to accumulate at current time */ typedef struct NlaEvalStrip { struct NlaEvalStrip *next, *prev; - + NlaTrack *track; /* track that this strip belongs to */ NlaStrip *strip; /* strip that's being used */ - + short track_index; /* the index of the track within the list */ short strip_mode; /* which end of the strip are we looking at */ - + float strip_time; /* time at which which strip is being evaluated */ } NlaEvalStrip; @@ -54,7 +54,7 @@ enum eNlaEvalStrip_StripMode { NES_TIME_BEFORE = -1, NES_TIME_WITHIN, NES_TIME_AFTER, - + /* transition-strip evaluations */ NES_TIME_TRANSITION_START, NES_TIME_TRANSITION_END, @@ -65,11 +65,11 @@ enum eNlaEvalStrip_StripMode { // TODO: maybe this will be used as the 'cache' stuff needed for editable values too? typedef struct NlaEvalChannel { struct NlaEvalChannel *next, *prev; - + PointerRNA ptr; /* pointer to struct containing property to use */ PropertyRNA *prop; /* RNA-property type to use (should be in the struct given) */ int index; /* array index (where applicable) */ - + float value; /* value of this channel */ } NlaEvalChannel; diff --git a/source/blender/blenlib/BLI_array_utils.h b/source/blender/blenlib/BLI_array_utils.h index 9a510bcfc3b7..da03063b2451 100644 --- a/source/blender/blenlib/BLI_array_utils.h +++ b/source/blender/blenlib/BLI_array_utils.h @@ -41,7 +41,7 @@ void _bli_array_permute( const unsigned int *index, void *arr_temp); #define BLI_array_permute(arr, arr_len, order) \ _bli_array_permute(arr, arr_len, sizeof(*(arr)), order, NULL) -#define BLI_array_permute_ex(arr, arr_len, index, arr_temp) \ +#define BLI_array_permute_ex(arr, arr_len, order, arr_temp) \ _bli_array_permute(arr, arr_len, sizeof(*(arr)), order, arr_temp) int _bli_array_findindex(const void *arr, unsigned int arr_len, size_t arr_stride, const void *p); diff --git a/source/blender/blenlib/BLI_boxpack_2d.h b/source/blender/blenlib/BLI_boxpack_2d.h index 80e89bdb04fe..d3f1109e18b9 100644 --- a/source/blender/blenlib/BLI_boxpack_2d.h +++ b/source/blender/blenlib/BLI_boxpack_2d.h @@ -50,4 +50,3 @@ typedef struct BoxPack { void BLI_box_pack_2d(BoxPack *boxarray, const unsigned int len, float *tot_width, float *tot_height); #endif /* __BLI_BOXPACK_2D_H__ */ - diff --git a/source/blender/blenlib/BLI_callbacks.h b/source/blender/blenlib/BLI_callbacks.h index 6eb451074885..3db7d2d87f18 100644 --- a/source/blender/blenlib/BLI_callbacks.h +++ b/source/blender/blenlib/BLI_callbacks.h @@ -49,6 +49,10 @@ typedef enum { BLI_CB_EVT_LOAD_POST, BLI_CB_EVT_SAVE_PRE, BLI_CB_EVT_SAVE_POST, + BLI_CB_EVT_UNDO_PRE, + BLI_CB_EVT_UNDO_POST, + BLI_CB_EVT_REDO_PRE, + BLI_CB_EVT_REDO_POST, BLI_CB_EVT_SCENE_UPDATE_PRE, BLI_CB_EVT_SCENE_UPDATE_POST, BLI_CB_EVT_GAME_PRE, diff --git a/source/blender/blenlib/BLI_compiler_compat.h b/source/blender/blenlib/BLI_compiler_compat.h index 0726e3bb3433..2b53975a106c 100644 --- a/source/blender/blenlib/BLI_compiler_compat.h +++ b/source/blender/blenlib/BLI_compiler_compat.h @@ -32,11 +32,7 @@ # define alloca _alloca #endif -#if defined(__cplusplus) && ((__cplusplus >= 201103L) || defined(_MSC_VER)) -# define HAS_CPP11_FEATURES -#endif - -#if (defined(__GNUC__) || defined(__clang__)) && defined(HAS_CPP11_FEATURES) +#if (defined(__GNUC__) || defined(__clang__)) && defined(__cplusplus) extern "C++" { /* Some magic to be sure we don't have reference in the type. */ template static inline T decltype_helper(T x) { return x; } diff --git a/source/blender/blenlib/BLI_dlrbTree.h b/source/blender/blenlib/BLI_dlrbTree.h index 05b67e358a40..6e47fd4ddb30 100644 --- a/source/blender/blenlib/BLI_dlrbTree.h +++ b/source/blender/blenlib/BLI_dlrbTree.h @@ -47,11 +47,11 @@ typedef struct DLRBT_Node { /* ListBase capabilities */ struct DLRBT_Node *next, *prev; - + /* Tree Associativity settings */ struct DLRBT_Node *left, *right; struct DLRBT_Node *parent; - + char tree_col; /* ... for nice alignment, next item should usually be a char too... */ } DLRBT_Node; @@ -75,18 +75,18 @@ typedef struct DLRBT_Tree { /* Callback Types --------------------------------- */ -/* return -1, 0, 1 for whether the given data is less than, equal to, or greater than the given node +/* return -1, 0, 1 for whether the given data is less than, equal to, or greater than the given node * - node: the node to compare to * - data: pointer to the relevant data or values stored in the bitpattern dependent on the function */ typedef short (*DLRBT_Comparator_FP)(void *node, void *data); -/* return a new node instance wrapping the given data +/* return a new node instance wrapping the given data * - data: pointer to the relevant data to create a subclass of node from */ typedef DLRBT_Node *(*DLRBT_NAlloc_FP)(void *data); -/* update an existing node instance accordingly to be in sync with the given data * +/* update an existing node instance accordingly to be in sync with the given data * * - node: the node to update * - data: pointer to the relevant data or values stored in the bitpattern dependent on the function */ @@ -130,28 +130,28 @@ short BLI_dlrbTree_contains(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, void * /* Node Operations (Managed) --------------------- */ -/* These methods automate the process of adding/removing nodes from the BST, +/* These methods automate the process of adding/removing nodes from the BST, * using the supplied data and callbacks */ /* Add the given data to the tree, and return the node added */ // NOTE: for duplicates, the update_cb is called (if available), and the existing node is returned -DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, +DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, DLRBT_NAlloc_FP new_cb, DLRBT_NUpdate_FP update_cb, void *data); /* Remove the given element from the tree and balance again */ -// FIXME: this is not implemented yet... +// FIXME: this is not implemented yet... // void BLI_dlrbTree_remove(DLRBT_Tree *tree, DLRBT_Node *node); /* Node Operations (Manual) --------------------- */ -/* These methods require custom code for creating BST nodes and adding them to the +/* These methods require custom code for creating BST nodes and adding them to the * tree in special ways, such that the node can then be balanced. * * It is recommended that these methods are only used where the other method is too cumbersome... */ -/* Balance the tree after the given node has been added to it +/* Balance the tree after the given node has been added to it * (using custom code, in the Binary Tree way). */ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node); diff --git a/source/blender/blenlib/BLI_dynlib.h b/source/blender/blenlib/BLI_dynlib.h index 310db9ea0514..747ce75dd727 100644 --- a/source/blender/blenlib/BLI_dynlib.h +++ b/source/blender/blenlib/BLI_dynlib.h @@ -40,4 +40,3 @@ char *BLI_dynlib_get_error_as_string(DynamicLibrary *lib); void BLI_dynlib_close(DynamicLibrary *lib); #endif /* __BLI_DYNLIB_H__ */ - diff --git a/source/blender/blenlib/BLI_dynstr.h b/source/blender/blenlib/BLI_dynstr.h index b26accc7f780..796dd2254047 100644 --- a/source/blender/blenlib/BLI_dynstr.h +++ b/source/blender/blenlib/BLI_dynstr.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_DYNSTR_H__ #define __BLI_DYNSTR_H__ diff --git a/source/blender/blenlib/BLI_edgehash.h b/source/blender/blenlib/BLI_edgehash.h index 417892012659..83b519fc7507 100644 --- a/source/blender/blenlib/BLI_edgehash.h +++ b/source/blender/blenlib/BLI_edgehash.h @@ -19,7 +19,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_EDGEHASH_H__ #define __BLI_EDGEHASH_H__ diff --git a/source/blender/blenlib/BLI_fileops_types.h b/source/blender/blenlib/BLI_fileops_types.h index 0ffa3276f1ff..06ffc8e5e798 100644 --- a/source/blender/blenlib/BLI_fileops_types.h +++ b/source/blender/blenlib/BLI_fileops_types.h @@ -66,4 +66,3 @@ struct dirlink { }; #endif /* __BLI_FILEOPS_TYPES_H__ */ - diff --git a/source/blender/blenlib/BLI_graph.h b/source/blender/blenlib/BLI_graph.h index f25db80e95ea..0b316d3c5bb4 100644 --- a/source/blender/blenlib/BLI_graph.h +++ b/source/blender/blenlib/BLI_graph.h @@ -51,9 +51,9 @@ typedef void (*AxialSymmetry)(struct BNode *root_node, struct BNode *node1, stru typedef struct BGraph { ListBase arcs; ListBase nodes; - + float length; - + /* function pointer to deal with custom fonctionnality */ FreeArc free_arc; FreeNode free_node; @@ -68,7 +68,7 @@ typedef struct BNode { int degree; struct BArc **arcs; - + int subgraph_index; int symmetry_level; @@ -114,17 +114,17 @@ typedef struct BArcIterator { NextNFct nextN; PreviousFct previous; StoppedFct stopped; - + float *p, *no; float size; - + int length; int index; } BArcIterator; /* Helper structure for radial symmetry */ typedef struct RadialArc { - struct BArc *arc; + struct BArc *arc; float n[3]; /* normalized vector joining the nodes of the arc */ } RadialArc; diff --git a/source/blender/blenlib/BLI_hash_mm3.h b/source/blender/blenlib/BLI_hash_mm3.h new file mode 100644 index 000000000000..93bf963c9a48 --- /dev/null +++ b/source/blender/blenlib/BLI_hash_mm3.h @@ -0,0 +1,40 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef __BLI_HASH_MM3_H__ +#define __BLI_HASH_MM3_H__ + +/** \file BLI_hash_mm3.h + * \ingroup bli + */ + +#include "BLI_sys_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t BLI_hash_mm3(const unsigned char *data, size_t len, uint32_t seed); + +#ifdef __cplusplus +} +#endif + +#endif /* __BLI_HASH_MM2A_H__ */ diff --git a/source/blender/blenlib/BLI_heap.h b/source/blender/blenlib/BLI_heap.h index 19e162d777f5..771b9dabe4de 100644 --- a/source/blender/blenlib/BLI_heap.h +++ b/source/blender/blenlib/BLI_heap.h @@ -17,7 +17,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_HEAP_H__ #define __BLI_HEAP_H__ diff --git a/source/blender/blenlib/BLI_jitter_2d.h b/source/blender/blenlib/BLI_jitter_2d.h index e2b1f21800c9..e79251fba9f6 100644 --- a/source/blender/blenlib/BLI_jitter_2d.h +++ b/source/blender/blenlib/BLI_jitter_2d.h @@ -37,4 +37,3 @@ void BLI_jitterate1(float (*jit1)[2], float (*jit2)[2], int num, float radius1); void BLI_jitterate2(float (*jit1)[2], float (*jit2)[2], int num, float radius2); #endif /* __BLI_JITTER_2D_H__ */ - diff --git a/source/blender/blenlib/BLI_kdtree.h b/source/blender/blenlib/BLI_kdtree.h index 18908f8c551a..689c07e05dbf 100644 --- a/source/blender/blenlib/BLI_kdtree.h +++ b/source/blender/blenlib/BLI_kdtree.h @@ -20,7 +20,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_KDTREE_H__ #define __BLI_KDTREE_H__ diff --git a/source/blender/blenlib/BLI_linklist.h b/source/blender/blenlib/BLI_linklist.h index 7eec54e67e17..214915163c72 100644 --- a/source/blender/blenlib/BLI_linklist.h +++ b/source/blender/blenlib/BLI_linklist.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_LINKLIST_H__ #define __BLI_LINKLIST_H__ diff --git a/source/blender/blenlib/BLI_linklist_stack.h b/source/blender/blenlib/BLI_linklist_stack.h index dd6d737f1116..b4c6751db52e 100644 --- a/source/blender/blenlib/BLI_linklist_stack.h +++ b/source/blender/blenlib/BLI_linklist_stack.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_LINKLIST_STACK_H__ #define __BLI_LINKLIST_STACK_H__ @@ -199,4 +199,3 @@ /** \} */ #endif /* __BLI_LINKLIST_STACK_H__ */ - diff --git a/source/blender/blenlib/BLI_math_color_blend.h b/source/blender/blenlib/BLI_math_color_blend.h index d966676e19e2..6ca8cecadbbb 100644 --- a/source/blender/blenlib/BLI_math_color_blend.h +++ b/source/blender/blenlib/BLI_math_color_blend.h @@ -106,4 +106,3 @@ MINLINE void blend_color_interpolate_float(float dst[4], const float src1[4], co #endif #endif /* __BLI_MATH_COLOR_BLEND_H__ */ - diff --git a/source/blender/blenlib/BLI_math_geom.h b/source/blender/blenlib/BLI_math_geom.h index ff80d15ea5d7..b3a95d65752d 100644 --- a/source/blender/blenlib/BLI_math_geom.h +++ b/source/blender/blenlib/BLI_math_geom.h @@ -385,7 +385,7 @@ void interp_barycentric_tri_v3(float data[3][3], float u, float v, float res[3]) /***************************** View & Projection *****************************/ -void lookat_m4(float mat[4][4], float vx, float vy, +void lookat_m4(float mat[4][4], float vx, float vy, float vz, float px, float py, float pz, float twist); void polarview_m4(float mat[4][4], float dist, float azimuth, float incidence, float twist); @@ -508,4 +508,3 @@ float cubic_tangent_factor_circle_v3(const float tan_l[3], const float tan_r[3]) #endif #endif /* __BLI_MATH_GEOM_H__ */ - diff --git a/source/blender/blenlib/BLI_math_matrix.h b/source/blender/blenlib/BLI_math_matrix.h index 173ef6861e6a..9d418749bd1a 100644 --- a/source/blender/blenlib/BLI_math_matrix.h +++ b/source/blender/blenlib/BLI_math_matrix.h @@ -17,7 +17,7 @@ * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. - + * The Original Code is: some of this file. * * ***** END GPL LICENSE BLOCK ***** @@ -283,4 +283,3 @@ void print_m4(const char *str, float M[4][4]); #endif #endif /* __BLI_MATH_MATRIX_H__ */ - diff --git a/source/blender/blenlib/BLI_math_rotation.h b/source/blender/blenlib/BLI_math_rotation.h index 1f206e5e2342..5b1568ab9029 100644 --- a/source/blender/blenlib/BLI_math_rotation.h +++ b/source/blender/blenlib/BLI_math_rotation.h @@ -235,4 +235,3 @@ bool mat3_from_axis_conversion_single( #endif #endif /* __BLI_MATH_ROTATION_H__ */ - diff --git a/source/blender/blenlib/BLI_math_solvers.h b/source/blender/blenlib/BLI_math_solvers.h index b01930228374..3c1cb90937dd 100644 --- a/source/blender/blenlib/BLI_math_solvers.h +++ b/source/blender/blenlib/BLI_math_solvers.h @@ -69,4 +69,3 @@ bool BLI_tridiagonal_solve_cyclic(const float *a, const float *b, const float *c #endif #endif /* __BLI_MATH_SOLVERS_H__ */ - diff --git a/source/blender/blenlib/BLI_math_statistics.h b/source/blender/blenlib/BLI_math_statistics.h index 484cc30cc46f..210d41bcf59d 100644 --- a/source/blender/blenlib/BLI_math_statistics.h +++ b/source/blender/blenlib/BLI_math_statistics.h @@ -67,4 +67,3 @@ void BLI_covariance_m3_v3n( #endif #endif /* __BLI_MATH_STATISTICS_H__ */ - diff --git a/source/blender/blenlib/BLI_math_vector.h b/source/blender/blenlib/BLI_math_vector.h index 3f6033115300..59c9341f75cb 100644 --- a/source/blender/blenlib/BLI_math_vector.h +++ b/source/blender/blenlib/BLI_math_vector.h @@ -169,6 +169,7 @@ MINLINE double dot_v3db_v3fl(const double a[3], const float b[3]) ATTR_WARN_UNUS MINLINE float cross_v2v2(const float a[2], const float b[2]) ATTR_WARN_UNUSED_RESULT; MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3]); +MINLINE void cross_v3_v3v3_hi_prec(float r[3], const float a[3], const float b[3]); MINLINE void add_newell_cross_v3_v3v3(float n[3], const float v_prev[3], const float v_curr[3]); @@ -353,6 +354,8 @@ void range_vn_u(unsigned int *array_tar, const int size, const unsigned int star void range_vn_fl(float *array_tar, const int size, const float start, const float step); void negate_vn(float *array_tar, const int size); void negate_vn_vn(float *array_tar, const float *array_src, const int size); +void mul_vn_vn(float *array_tar, const float *array_src, const int size); +void mul_vn_vnvn(float *array_tar, const float *array_src_a, const float *array_src_b, const int size); void mul_vn_fl(float *array_tar, const int size, const float f); void mul_vn_vn_fl(float *array_tar, const float *array_src, const int size, const float f); void add_vn_vn(float *array_tar, const float *array_src, const int size); diff --git a/source/blender/blenlib/BLI_mempool.h b/source/blender/blenlib/BLI_mempool.h index 45efb8d7ef10..dfa6fdd26259 100644 --- a/source/blender/blenlib/BLI_mempool.h +++ b/source/blender/blenlib/BLI_mempool.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_MEMPOOL_H__ #define __BLI_MEMPOOL_H__ diff --git a/source/blender/blenlib/BLI_path_util.h b/source/blender/blenlib/BLI_path_util.h index b59e7f99d592..b4329bf81acd 100644 --- a/source/blender/blenlib/BLI_path_util.h +++ b/source/blender/blenlib/BLI_path_util.h @@ -60,16 +60,6 @@ bool BLI_path_name_at_index( const char *__restrict path, const int index, int *__restrict r_offset, int *__restrict r_len) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; -#if 0 -typedef enum bli_rebase_state { - BLI_REBASE_NO_SRCDIR = 0, - BLI_REBASE_OK = 1, - BLI_REBASE_IDENTITY = 2 -} bli_rebase_state; - -int BLI_rebase_path(char *abs, size_t abs_len, char *rel, size_t rel_len, const char *base_dir, const char *src_dir, const char *dest_dir); -#endif - const char *BLI_last_slash(const char *string) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; int BLI_add_slash(char *string) ATTR_NONNULL(); void BLI_del_slash(char *string) ATTR_NONNULL(); @@ -81,12 +71,13 @@ bool BLI_path_program_extensions_add_win32(char *name, const size_t maxlen); #endif bool BLI_path_program_search(char *fullname, const size_t maxlen, const char *name); -bool BLI_testextensie(const char *str, const char *ext) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; -bool BLI_testextensie_n(const char *str, ...) ATTR_NONNULL(1) ATTR_SENTINEL(0); -bool BLI_testextensie_array(const char *str, const char **ext_array) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; -bool BLI_testextensie_glob(const char *str, const char *ext_fnmatch) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; -bool BLI_replace_extension(char *path, size_t maxlen, const char *ext) ATTR_NONNULL(); -bool BLI_ensure_extension(char *path, size_t maxlen, const char *ext) ATTR_NONNULL(); +bool BLI_path_extension_check(const char *str, const char *ext) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; +bool BLI_path_extension_check_n(const char *str, ...) ATTR_NONNULL(1) ATTR_SENTINEL(0); +bool BLI_path_extension_check_array(const char *str, const char **ext_array) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; +bool BLI_path_extension_check_glob(const char *str, const char *ext_fnmatch) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT; +bool BLI_path_extension_glob_validate(char *ext_fnmatch) ATTR_NONNULL(); +bool BLI_path_extension_replace(char *path, size_t maxlen, const char *ext) ATTR_NONNULL(); +bool BLI_path_extension_ensure(char *path, size_t maxlen, const char *ext) ATTR_NONNULL(); bool BLI_ensure_filename(char *filepath, size_t maxlen, const char *filename) ATTR_NONNULL(); int BLI_stringdec(const char *string, char *head, char *start, unsigned short *numlen); void BLI_stringenc(char *string, const char *head, const char *tail, unsigned short numlen, int pic); diff --git a/source/blender/blenlib/BLI_rand.h b/source/blender/blenlib/BLI_rand.h index 69b23b2473f7..5bb7ab391b90 100644 --- a/source/blender/blenlib/BLI_rand.h +++ b/source/blender/blenlib/BLI_rand.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_RAND_H__ #define __BLI_RAND_H__ diff --git a/source/blender/blenlib/BLI_scanfill.h b/source/blender/blenlib/BLI_scanfill.h index 4fca3fbc3ad1..f6b37fa2ec33 100644 --- a/source/blender/blenlib/BLI_scanfill.h +++ b/source/blender/blenlib/BLI_scanfill.h @@ -139,4 +139,3 @@ bool BLI_scanfill_calc_self_isect( #endif #endif - diff --git a/source/blender/blenlib/BLI_smallhash.h b/source/blender/blenlib/BLI_smallhash.h index 495fc94a53c7..d1bcf4e9dc64 100644 --- a/source/blender/blenlib/BLI_smallhash.h +++ b/source/blender/blenlib/BLI_smallhash.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_SMALLHASH_H__ #define __BLI_SMALLHASH_H__ diff --git a/source/blender/blenlib/BLI_sys_types.h b/source/blender/blenlib/BLI_sys_types.h index 80ee50621ca1..ccafa1cf3278 100644 --- a/source/blender/blenlib/BLI_sys_types.h +++ b/source/blender/blenlib/BLI_sys_types.h @@ -87,7 +87,7 @@ typedef unsigned short ushort; typedef unsigned long ulong; typedef unsigned char uchar; -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/source/blender/blenlib/BLI_task.h b/source/blender/blenlib/BLI_task.h index ad3254933090..9194caca007a 100644 --- a/source/blender/blenlib/BLI_task.h +++ b/source/blender/blenlib/BLI_task.h @@ -227,4 +227,3 @@ BLI_INLINE void BLI_parallel_range_settings_defaults( #endif #endif - diff --git a/source/blender/blenlib/BLI_threads.h b/source/blender/blenlib/BLI_threads.h index 96bb739f683a..81f8445783b1 100644 --- a/source/blender/blenlib/BLI_threads.h +++ b/source/blender/blenlib/BLI_threads.h @@ -26,7 +26,7 @@ */ #ifndef __BLI_THREADS_H__ -#define __BLI_THREADS_H__ +#define __BLI_THREADS_H__ /** \file BLI_threads.h * \ingroup bli @@ -74,7 +74,7 @@ void BLI_threaded_malloc_end(void); int BLI_system_thread_count(void); /* gets the number of threads the system can make use of */ void BLI_system_num_threads_override_set(int num); int BLI_system_num_threads_override_get(void); - + /* Global Mutex Locks * * One custom lock available now. can be extended. */ @@ -155,7 +155,7 @@ void BLI_ticket_mutex_lock(TicketMutex *ticket); void BLI_ticket_mutex_unlock(TicketMutex *ticket); /* Condition */ - + typedef pthread_cond_t ThreadCondition; void BLI_condition_init(ThreadCondition *cond); @@ -209,4 +209,3 @@ void BLI_thread_queue_nowait(ThreadQueue *queue); #endif #endif - diff --git a/source/blender/blenlib/BLI_utildefines.h b/source/blender/blenlib/BLI_utildefines.h index 666ff70d40e4..3996c34acdbc 100644 --- a/source/blender/blenlib/BLI_utildefines.h +++ b/source/blender/blenlib/BLI_utildefines.h @@ -556,13 +556,13 @@ extern bool BLI_memory_is_zero(const void *arr, const size_t arr_size); /* UNUSED macro, for function argument */ -#if defined(__GNUC__) || defined(__clang__) +#if defined(__GNUC__) || defined(__clang__) # define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) #else # define UNUSED(x) UNUSED_ ## x #endif -#if defined(__GNUC__) || defined(__clang__) +#if defined(__GNUC__) || defined(__clang__) # define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x #else # define UNUSED_FUNCTION(x) UNUSED_ ## x diff --git a/source/blender/blenlib/BLI_vfontdata.h b/source/blender/blenlib/BLI_vfontdata.h index 16fdfa8a4685..1cc1ef17486b 100644 --- a/source/blender/blenlib/BLI_vfontdata.h +++ b/source/blender/blenlib/BLI_vfontdata.h @@ -58,4 +58,3 @@ VChar *BLI_vfontchar_from_freetypefont(struct VFont *vfont, unsigned long charac VChar *BLI_vfontchar_copy(const VChar *vchar_src, const int flag); #endif - diff --git a/source/blender/blenlib/BLI_winstuff.h b/source/blender/blenlib/BLI_winstuff.h index 6fbbed01400a..cf29a8652df2 100644 --- a/source/blender/blenlib/BLI_winstuff.h +++ b/source/blender/blenlib/BLI_winstuff.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BLI_WINSTUFF_H__ #define __BLI_WINSTUFF_H__ @@ -138,4 +138,3 @@ int BLI_getInstallationDir(char *str); #endif #endif /* __BLI_WINSTUFF_H__ */ - diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt index f8fc2bfdcff5..e3f5773b1e4e 100644 --- a/source/blender/blenlib/CMakeLists.txt +++ b/source/blender/blenlib/CMakeLists.txt @@ -74,6 +74,7 @@ set(SRC intern/gsqueue.c intern/hash_md5.c intern/hash_mm2a.c + intern/hash_mm3.c intern/jitter_2d.c intern/lasso_2d.c intern/list_sort_impl.h @@ -129,6 +130,7 @@ set(SRC BLI_array_store.h BLI_array_store_utils.h BLI_array_utils.h + BLI_assert.h BLI_astar.h BLI_bitmap.h BLI_bitmap_draw_2d.h @@ -158,12 +160,14 @@ set(SRC BLI_hash.h BLI_hash_md5.h BLI_hash_mm2a.h + BLI_hash_mm3.h BLI_heap.h BLI_jitter_2d.h BLI_kdopbvh.h BLI_kdtree.h BLI_lasso_2d.h BLI_link_utils.h + BLI_linklist.h BLI_linklist_lockfree.h BLI_linklist_stack.h BLI_listbase.h diff --git a/source/blender/blenlib/PIL_time.h b/source/blender/blenlib/PIL_time.h index 6e347339980f..088b275738e1 100644 --- a/source/blender/blenlib/PIL_time.h +++ b/source/blender/blenlib/PIL_time.h @@ -34,7 +34,7 @@ #define __PIL_TIME_H__ #ifdef __cplusplus -extern "C" { +extern "C" { #endif extern diff --git a/source/blender/blenlib/intern/BLI_dial_2d.c b/source/blender/blenlib/intern/BLI_dial_2d.c index d31367c5e87e..1f4c59ac2fb7 100644 --- a/source/blender/blenlib/intern/BLI_dial_2d.c +++ b/source/blender/blenlib/intern/BLI_dial_2d.c @@ -30,21 +30,21 @@ struct Dial { /* center of the dial */ float center[2]; - - /* threshold of the dial. Distance of current position has to be greater + + /* threshold of the dial. Distance of current position has to be greater * than the threshold to be used in any calculations */ float threshold_squared; - + /* the direction of the first dial position exceeding the threshold. This * is later used as the basis against which rotation angle is calculated */ float initial_direction[2]; /* cache the last angle to detect rotations bigger than -/+ PI */ float last_angle; - + /* number of full rotations */ int rotations; - + /* has initial_direction been initialized */ bool initialized; }; @@ -53,17 +53,17 @@ struct Dial { Dial *BLI_dial_initialize(const float start_position[2], float threshold) { Dial *dial = MEM_callocN(sizeof(Dial), "dial"); - + copy_v2_v2(dial->center, start_position); dial->threshold_squared = threshold * threshold; - + return dial; } float BLI_dial_angle(Dial *dial, const float current_position[2]) { float current_direction[2]; - + sub_v2_v2v2(current_direction, current_position, dial->center); /* only update when we have enough precision, by having the mouse adequately away from center */ @@ -77,14 +77,14 @@ float BLI_dial_angle(Dial *dial, const float current_position[2]) copy_v2_v2(dial->initial_direction, current_direction); dial->initialized = true; } - + /* calculate mouse angle between initial and final mouse position */ cosval = dot_v2v2(current_direction, dial->initial_direction); sinval = cross_v2v2(current_direction, dial->initial_direction); - + /* clamp to avoid nans in acos */ angle = atan2f(sinval, cosval); - + /* change of sign, we passed the 180 degree threshold. This means we need to add a turn. * to distinguish between transition from 0 to -1 and -PI to +PI, use comparison with PI/2 */ if ((angle * dial->last_angle < 0.0f) && @@ -96,9 +96,9 @@ float BLI_dial_angle(Dial *dial, const float current_position[2]) dial->rotations++; } dial->last_angle = angle; - + return angle + 2.0f * (float)M_PI * dial->rotations; } - + return dial->last_angle; } diff --git a/source/blender/blenlib/intern/BLI_dynstr.c b/source/blender/blenlib/intern/BLI_dynstr.c index bce6614beb5f..d3fc8ae0ed5e 100644 --- a/source/blender/blenlib/intern/BLI_dynstr.c +++ b/source/blender/blenlib/intern/BLI_dynstr.c @@ -58,7 +58,7 @@ typedef struct DynStrElem DynStrElem; struct DynStrElem { DynStrElem *next; - + char *str; }; @@ -81,7 +81,7 @@ DynStr *BLI_dynstr_new(void) ds->elems = ds->last = NULL; ds->curlen = 0; ds->memarena = NULL; - + return ds; } @@ -115,11 +115,11 @@ void BLI_dynstr_append(DynStr *__restrict ds, const char *cstr) { DynStrElem *dse = dynstr_alloc(ds, sizeof(*dse)); int cstrlen = strlen(cstr); - + dse->str = dynstr_alloc(ds, cstrlen + 1); memcpy(dse->str, cstr, cstrlen + 1); dse->next = NULL; - + if (!ds->last) ds->last = ds->elems = dse; else diff --git a/source/blender/blenlib/intern/BLI_heap.c b/source/blender/blenlib/intern/BLI_heap.c index 0c71e75e40fe..5658c1fd1037 100644 --- a/source/blender/blenlib/intern/BLI_heap.c +++ b/source/blender/blenlib/intern/BLI_heap.c @@ -418,4 +418,3 @@ bool BLI_heap_is_valid(const Heap *heap) } /** \} */ - diff --git a/source/blender/blenlib/intern/BLI_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c index 027c6e084f5d..1676bf5d779c 100644 --- a/source/blender/blenlib/intern/BLI_kdopbvh.c +++ b/source/blender/blenlib/intern/BLI_kdopbvh.c @@ -458,10 +458,10 @@ static void partition_nth_element(BVHNode **a, int begin, int end, const int n, static void build_skip_links(BVHTree *tree, BVHNode *node, BVHNode *left, BVHNode *right) { int i; - + node->skip[0] = left; node->skip[1] = right; - + for (i = 0; i < node->totnode; i++) { if (i + 1 < node->totnode) build_skip_links(tree, node->children[i], left, node->children[i + 1]); @@ -482,7 +482,7 @@ static void create_kdop_hull(const BVHTree *tree, BVHNode *node, const float *co float *bv = node->bv; int k; axis_t axis_iter; - + /* don't init boudings for the moving case */ if (!moving) { node_minmax_init(tree, node); @@ -560,7 +560,7 @@ static void node_join(BVHTree *tree, BVHNode *node) axis_t axis_iter; node_minmax_init(tree, node); - + for (i = 0; i < tree->tree_type; i++) { if (node->children[i]) { for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) { @@ -631,7 +631,7 @@ static void bvhtree_info(BVHTree *tree) static void bvhtree_verify(BVHTree *tree) { int i, j, check = 0; - + /* check the pointer list */ for (i = 0; i < tree->totleaf; i++) { if (tree->nodes[i]->parent == NULL) { @@ -648,7 +648,7 @@ static void bvhtree_verify(BVHTree *tree) check = 0; } } - + /* check the leaf list */ for (i = 0; i < tree->totleaf; i++) { if (tree->nodearray[i].parent == NULL) { @@ -665,7 +665,7 @@ static void bvhtree_verify(BVHTree *tree) check = 0; } } - + printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf); } @@ -1008,7 +1008,7 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis) tree->nodebv = MEM_callocN(sizeof(float) * (size_t)(axis * numnodes), "BVHNodeBV"); tree->nodechild = MEM_callocN(sizeof(BVHNode *) * (size_t)(tree_type * numnodes), "BVHNodeBV"); tree->nodearray = MEM_callocN(sizeof(BVHNode) * (size_t)numnodes, "BVHNodeArray"); - + if (UNLIKELY((!tree->nodes) || (!tree->nodebv) || (!tree->nodechild) || @@ -1022,7 +1022,7 @@ BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis) tree->nodearray[i].bv = &tree->nodebv[i * axis]; tree->nodearray[i].children = &tree->nodechild[i * tree_type]; } - + } return tree; @@ -1108,18 +1108,18 @@ bool BLI_bvhtree_update_node(BVHTree *tree, int index, const float co[3], const { BVHNode *node = NULL; axis_t axis_iter; - + /* check if index exists */ if (index > tree->totleaf) return false; - + node = tree->nodearray + index; - + create_kdop_hull(tree, node, co, numpoints, 0); - + if (co_moving) create_kdop_hull(tree, node, co_moving, numpoints, 1); - + /* inflate the bv with some epsilon */ for (axis_iter = tree->start_axis; axis_iter < tree->stop_axis; axis_iter++) { node->bv[(2 * axis_iter)] -= tree->epsilon; /* minimum */ @@ -1180,7 +1180,7 @@ static bool tree_overlap_test(const BVHNode *node1, const BVHNode *node2, axis_t const float *bv1 = node1->bv + (start_axis << 1); const float *bv2 = node2->bv + (start_axis << 1); const float *bv1_end = node1->bv + (stop_axis << 1); - + /* test all axis if min + max overlap */ for (; bv1 != bv1_end; bv1 += 2, bv2 += 2) { if ((bv1[0] > bv2[1]) || (bv2[0] > bv1[1])) { @@ -1321,7 +1321,7 @@ BVHTreeOverlap *BLI_bvhtree_overlap( BVHOverlapData_Shared data_shared; BVHOverlapData_Thread *data = BLI_array_alloca(data, (size_t)thread_num); axis_t start_axis, stop_axis; - + /* check for compatibility of both trees (can't compare 14-DOP with 18-DOP) */ if (UNLIKELY((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && @@ -1333,7 +1333,7 @@ BVHTreeOverlap *BLI_bvhtree_overlap( start_axis = min_axis(tree1->start_axis, tree2->start_axis); stop_axis = min_axis(tree1->stop_axis, tree2->stop_axis); - + /* fast check root nodes for collision before doing big splitting + traversal */ if (!tree_overlap_test(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], start_axis, stop_axis)) { return NULL; @@ -1365,12 +1365,12 @@ BVHTreeOverlap *BLI_bvhtree_overlap( data, bvhtree_overlap_task_cb, &settings); - + for (j = 0; j < thread_num; j++) total += BLI_stack_count(data[j].overlap); - + to = overlap = MEM_mallocN(sizeof(BVHTreeOverlap) * total, "BVHTreeOverlap"); - + for (j = 0; j < thread_num; j++) { uint count = (uint)BLI_stack_count(data[j].overlap); BLI_stack_pop_n(data[j].overlap, to, count); @@ -1403,7 +1403,7 @@ static float calc_nearest_point_squared(const float proj[3], BVHNode *node, floa else if (bv[1] < proj[i]) nearest[i] = bv[1]; else - nearest[i] = proj[i]; + nearest[i] = proj[i]; } #if 0 @@ -1548,7 +1548,7 @@ static void bfs_find_nearest(BVHNearestData *data, BVHNode *node) push_heaps++; } } - + if (heap_size == 0) break; current = heap[0]; @@ -1645,7 +1645,7 @@ static float ray_nearest_hit(const BVHRayCastData *data, const float bv[6]) if (lu > low) low = lu; if (ll < upper) upper = ll; } - + if (low > upper) return FLT_MAX; } } @@ -1661,7 +1661,7 @@ static float ray_nearest_hit(const BVHRayCastData *data, const float bv[6]) static float fast_ray_nearest_hit(const BVHRayCastData *data, const BVHNode *node) { const float *bv = node->bv; - + float t1x = (bv[data->index[0]] - data->ray.origin[0]) * data->idot_axis[0]; float t2x = (bv[data->index[1]] - data->ray.origin[0]) * data->idot_axis[0]; float t1y = (bv[data->index[2]] - data->ray.origin[1]) * data->idot_axis[1]; @@ -1773,7 +1773,7 @@ static void iterative_raycast(BVHRayCastData *data, BVHNode *node) data->hit.dist = dist; madd_v3_v3v3fl(data->hit.co, data->ray.origin, data->ray.direction, dist); } - + node = node->skip[1]; } else { @@ -1867,23 +1867,23 @@ float BLI_bvhtree_bb_raycast(const float bv[6], const float light_start[3], cons float dist; data.hit.dist = BVH_RAYCAST_DIST_MAX; - + /* get light direction */ sub_v3_v3v3(data.ray.direction, light_end, light_start); - + data.ray.radius = 0.0; - + copy_v3_v3(data.ray.origin, light_start); normalize_v3(data.ray.direction); copy_v3_v3(data.ray_dot_axis, data.ray.direction); - + dist = ray_nearest_hit(&data, bv); madd_v3_v3v3fl(pos, light_start, data.ray.direction, dist); return dist; - + } /** diff --git a/source/blender/blenlib/intern/BLI_kdtree.c b/source/blender/blenlib/intern/BLI_kdtree.c index 800e245d6bd8..80a2957d9071 100644 --- a/source/blender/blenlib/intern/BLI_kdtree.c +++ b/source/blender/blenlib/intern/BLI_kdtree.c @@ -123,7 +123,7 @@ static uint kdtree_balance(KDTreeNode *nodes, uint totnode, uint axis, const uin return KD_NODE_UNSET; else if (totnode == 1) return 0 + ofs; - + /* quicksort style sorting around median */ left = 0; right = totnode - 1; @@ -238,7 +238,7 @@ int BLI_kdtree_find_nearest( if (root->right != KD_NODE_UNSET) stack[cur++] = root->right; } - + while (cur--) { const KDTreeNode *node = &nodes[stack[cur]]; @@ -448,7 +448,7 @@ int BLI_kdtree_find_nearest_n__normal( cur_dist = squared_distance(root->co, co, nor); add_nearest(r_nearest, &found, n, root->index, cur_dist, root->co); - + if (co[root->d] < root->co[root->d]) { if (root->right != KD_NODE_UNSET) stack[cur++] = root->right; @@ -774,7 +774,12 @@ int BLI_kdtree_calc_duplicates_fast( if (ELEM(duplicates[index], -1, index)) { p.search = index; copy_v3_v3(p.search_co, tree->nodes[node_index].co); + int found_prev = found; deduplicate_recursive(&p, tree->root); + if (found != found_prev) { + /* Prevent chains of doubles. */ + duplicates[index] = index; + } } } MEM_freeN(order); @@ -786,7 +791,12 @@ int BLI_kdtree_calc_duplicates_fast( if (ELEM(duplicates[index], -1, index)) { p.search = index; copy_v3_v3(p.search_co, tree->nodes[node_index].co); + int found_prev = found; deduplicate_recursive(&p, tree->root); + if (found != found_prev) { + /* Prevent chains of doubles. */ + duplicates[index] = index; + } } } } diff --git a/source/blender/blenlib/intern/BLI_linklist.c b/source/blender/blenlib/intern/BLI_linklist.c index 051792f7f7c2..80d5cbc8cd0f 100644 --- a/source/blender/blenlib/intern/BLI_linklist.c +++ b/source/blender/blenlib/intern/BLI_linklist.c @@ -58,18 +58,18 @@ int BLI_linklist_count(const LinkNode *list) int BLI_linklist_index(const LinkNode *list, void *ptr) { int index; - + for (index = 0; list; list = list->next, index++) if (list->link == ptr) return index; - + return -1; } LinkNode *BLI_linklist_find(LinkNode *list, int index) { int i; - + for (i = 0; list; list = list->next, i++) if (i == index) return list; @@ -80,16 +80,16 @@ LinkNode *BLI_linklist_find(LinkNode *list, int index) void BLI_linklist_reverse(LinkNode **listp) { LinkNode *rhead = NULL, *cur = *listp; - + while (cur) { LinkNode *next = cur->next; - + cur->next = rhead; rhead = cur; - + cur = next; } - + *listp = rhead; } @@ -199,7 +199,7 @@ void BLI_linklist_append_nlink(LinkNodePair *list_pair, void *ptr, LinkNode *nli { nlink->link = ptr; nlink->next = NULL; - + if (list_pair->list) { BLI_assert((list_pair->last_node != NULL) && (list_pair->last_node->next == NULL)); list_pair->last_node->next = nlink; @@ -275,11 +275,11 @@ void BLI_linklist_free(LinkNode *list, LinkNodeFreeFP freefunc) { while (list) { LinkNode *next = list->next; - + if (freefunc) freefunc(list->link); MEM_freeN(list); - + list = next; } } diff --git a/source/blender/blenlib/intern/DLRB_tree.c b/source/blender/blenlib/intern/DLRB_tree.c index 31b4b7cd4a5f..6ef77890e95e 100644 --- a/source/blender/blenlib/intern/DLRB_tree.c +++ b/source/blender/blenlib/intern/DLRB_tree.c @@ -48,7 +48,7 @@ void BLI_dlrbTree_init(DLRBT_Tree *tree) { if (tree == NULL) return; - + tree->first = tree->last = tree->root = NULL; } @@ -58,11 +58,11 @@ static void recursive_tree_free_nodes(DLRBT_Node *node) /* sanity check */ if (node == NULL) return; - + /* free child nodes + subtrees */ recursive_tree_free_nodes(node->left); recursive_tree_free_nodes(node->right); - + /* free self */ MEM_freeN(node); } @@ -72,8 +72,8 @@ void BLI_dlrbTree_free(DLRBT_Tree *tree) { if (tree == NULL) return; - - /* if the list-base stuff is set, just use that (and assume its set), + + /* if the list-base stuff is set, just use that (and assume its set), * otherwise, we'll need to traverse the tree... */ if (tree->first) { @@ -84,7 +84,7 @@ void BLI_dlrbTree_free(DLRBT_Tree *tree) /* traverse tree, freeing sub-nodes */ recursive_tree_free_nodes(tree->root); } - + /* clear pointers */ tree->first = tree->last = tree->root = NULL; } @@ -97,17 +97,17 @@ static void linkedlist_sync_add_node(DLRBT_Tree *tree, DLRBT_Node *node) /* sanity checks */ if ((tree == NULL) || (node == NULL)) return; - + /* add left-node (and its subtree) */ linkedlist_sync_add_node(tree, node->left); - + /* now add self * - must remove detach from other links first * (for now, only clear own pointers) */ node->prev = node->next = NULL; BLI_addtail((ListBase *)tree, (Link *)node); - + /* finally, add right node (and its subtree) */ linkedlist_sync_add_node(tree, node->right); } @@ -118,10 +118,10 @@ void BLI_dlrbTree_linkedlist_sync(DLRBT_Tree *tree) /* sanity checks */ if (tree == NULL) return; - + /* clear list-base pointers so that the new list can be added properly */ tree->first = tree->last = NULL; - + /* start adding items from the root */ linkedlist_sync_add_node(tree, tree->root); } @@ -142,7 +142,7 @@ DLRBT_Node *BLI_dlrbTree_search(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, vo /* iteratively perform this search */ while (node && found == 0) { - /* check if traverse further or not + /* check if traverse further or not * NOTE: it is assumed that the values will be unit values only */ switch (cmp_cb(node, search_data)) { @@ -152,38 +152,38 @@ DLRBT_Node *BLI_dlrbTree_search(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, vo else found = 1; break; - + case 1: /* data greater than node */ if (node->right) node = node->right; else found = 1; break; - + default: /* data equals node */ found = 1; break; } } - + /* return the nearest matching node */ return node; -} +} /* Find the node which exactly matches the required data */ DLRBT_Node *BLI_dlrbTree_search_exact(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, void *search_data) { DLRBT_Node *node = (tree) ? tree->root : NULL; short found = 0; - + /* check that there is a comparator to use */ /* TODO: if no comparator is supplied, try using the one supplied with the tree... */ if (cmp_cb == NULL) return NULL; - + /* iteratively perform this search */ while (node && found == 0) { - /* check if traverse further or not + /* check if traverse further or not * NOTE: it is assumed that the values will be unit values only */ switch (cmp_cb(node, search_data)) { @@ -193,20 +193,20 @@ DLRBT_Node *BLI_dlrbTree_search_exact(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_ else found = -1; break; - + case 1: /* data greater than node */ if (node->right) node = node->right; else found = -1; break; - + default: /* data equals node */ found = 1; break; } } - + /* return the exactly matching node */ return (found == 1) ? (node) : (NULL); } @@ -215,25 +215,25 @@ DLRBT_Node *BLI_dlrbTree_search_exact(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_ DLRBT_Node *BLI_dlrbTree_search_prev(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, void *search_data) { DLRBT_Node *node; - + /* check that there is a comparator to use */ /* TODO: if no comparator is supplied, try using the one supplied with the tree... */ if (cmp_cb == NULL) return NULL; - + /* get the node which best matches this description */ node = BLI_dlrbTree_search(tree, cmp_cb, search_data); - + if (node) { /* if the item we're searching for is greater than the node found, we've found the match */ if (cmp_cb(node, search_data) > 0) return node; - + /* return the previous node otherwise */ /* NOTE: what happens if there is no previous node? */ return node->prev; } - + /* nothing matching was found */ return NULL; } @@ -247,20 +247,20 @@ DLRBT_Node *BLI_dlrbTree_search_next(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_c /* TODO: if no comparator is supplied, try using the one supplied with the tree... */ if (cmp_cb == NULL) return NULL; - + /* get the node which best matches this description */ node = BLI_dlrbTree_search(tree, cmp_cb, search_data); - + if (node) { /* if the item we're searching for is less than the node found, we've found the match */ if (cmp_cb(node, search_data) < 0) return node; - + /* return the previous node otherwise */ /* NOTE: what happens if there is no previous node? */ return node->next; } - + /* nothing matching was found */ return NULL; } @@ -305,7 +305,7 @@ 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); - + /* uncle not found */ return NULL; } @@ -317,12 +317,12 @@ static DLRBT_Node *get_uncle(DLRBT_Node *node) static void rotate_left(DLRBT_Tree *tree, DLRBT_Node *root) { DLRBT_Node **root_slot, *pivot; - + /* pivot is simply the root's right child, to become the root's parent */ pivot = root->right; if (pivot == NULL) return; - + if (root->parent) { if (root == root->parent->left) root_slot = &root->parent->left; @@ -331,17 +331,17 @@ static void rotate_left(DLRBT_Tree *tree, DLRBT_Node *root) } else root_slot = ((DLRBT_Node **)&tree->root); /* &((DLRBT_Node *)tree->root); */ - + /* - pivot's left child becomes root's right child - * - root now becomes pivot's left child + * - root now becomes pivot's left child */ root->right = pivot->left; if (pivot->left) pivot->left->parent = root; - + pivot->left = root; pivot->parent = root->parent; root->parent = pivot; - + /* make the pivot the new root */ if (root_slot) *root_slot = pivot; @@ -351,12 +351,12 @@ static void rotate_left(DLRBT_Tree *tree, DLRBT_Node *root) static void rotate_right(DLRBT_Tree *tree, DLRBT_Node *root) { DLRBT_Node **root_slot, *pivot; - + /* pivot is simply the root's left child, to become the root's parent */ pivot = root->left; if (pivot == NULL) return; - + if (root->parent) { if (root == root->parent->left) root_slot = &root->parent->left; @@ -365,17 +365,17 @@ static void rotate_right(DLRBT_Tree *tree, DLRBT_Node *root) } else root_slot = ((DLRBT_Node **)&tree->root); /* &((DLRBT_Node *)tree->root); */ - + /* - pivot's right child becomes root's left child - * - root now becomes pivot's right child + * - root now becomes pivot's right child */ root->left = pivot->right; if (pivot->right) pivot->right->parent = root; - + pivot->right = root; pivot->parent = root->parent; root->parent = pivot; - + /* make the pivot the new root */ if (root_slot) *root_slot = pivot; @@ -409,20 +409,20 @@ static void insert_check_2(DLRBT_Tree *tree, DLRBT_Node *node) /* if the parent is not black, we need to change that... */ if (node && node->parent && node->parent->tree_col) { DLRBT_Node *unc = get_uncle(node); - - /* if uncle and parent are both red, need to change them to black and make + + /* if uncle and parent are both red, need to change them to black and make * the parent black in order to satisfy the criteria of each node having the * same number of black nodes to its leaves */ if (unc && unc->tree_col) { DLRBT_Node *gp = get_grandparent(node); - + /* make the n-1 generation nodes black */ node->parent->tree_col = unc->tree_col = DLRBT_BLACK; - - /* - make the grandparent red, so that we maintain alternating red/black property + + /* - make the grandparent red, so that we maintain alternating red/black property * (it must exist, so no need to check for NULL here), - * - as the grandparent may now cause inconsistencies with the rest of the tree, + * - as the grandparent may now cause inconsistencies with the rest of the tree, * we must flush up the tree and perform checks/re-balancing/re-painting, using the * grandparent as the node of interest */ @@ -442,7 +442,7 @@ static void insert_check_2(DLRBT_Tree *tree, DLRBT_Node *node) static void insert_check_3(DLRBT_Tree *tree, DLRBT_Node *node) { DLRBT_Node *gp = get_grandparent(node); - + /* check that grandparent and node->parent exist (jut in case... really shouldn't happen on a good tree) */ if (node && node->parent && gp) { /* a left rotation will switch the roles of node and its parent, assuming that @@ -454,22 +454,22 @@ static void insert_check_3(DLRBT_Tree *tree, DLRBT_Node *node) node = node->left; } else if ((node == node->parent->left) && (node->parent == gp->right)) { - rotate_right(tree, node); + rotate_right(tree, node); node = node->right; } - - /* fix old parent's color-tagging, and perform rotation on the old parent in the + + /* fix old parent's color-tagging, and perform rotation on the old parent in the * opposite direction if needed for the current situation - * NOTE: in the code above, node pointer is changed to point to the old parent + * NOTE: in the code above, node pointer is changed to point to the old parent */ if (node) { /* get 'new' grandparent (i.e. grandparent for old-parent (node)) */ gp = get_grandparent(node); - + /* modify the coloring of the grandparent and parent so that they still satisfy the constraints */ node->parent->tree_col = DLRBT_BLACK; gp->tree_col = DLRBT_RED; - + /* if there are several nodes that all form a left chain, do a right rotation to correct this * (or a rotation in the opposite direction if they all form a right chain) */ @@ -483,7 +483,7 @@ static void insert_check_3(DLRBT_Tree *tree, DLRBT_Node *node) /* ----- */ -/* Balance the tree after the given element has been added to it +/* Balance the tree after the given element has been added to it * (using custom code, in the Binary Tree way). */ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node) @@ -491,10 +491,10 @@ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node) /* sanity checks */ if ((tree == NULL) || (node == NULL)) return; - + /* firstly, the node we just added should be red by default */ node->tree_col = DLRBT_RED; - + /* start from case 1, an trek through the tail-recursive insertion checks */ insert_check_1(tree, node); } @@ -503,12 +503,12 @@ void BLI_dlrbTree_insert(DLRBT_Tree *tree, DLRBT_Node *node) /* Add the given data to the tree, and return the node added */ /* NOTE: for duplicates, the update_cb is called (if available), and the existing node is returned */ -DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, +DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, DLRBT_NAlloc_FP new_cb, DLRBT_NUpdate_FP update_cb, void *data) { DLRBT_Node *parNode, *node = NULL; short new_node = 0; - + /* sanity checks */ if (tree == NULL) return NULL; @@ -524,11 +524,11 @@ DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, /* try to find the nearest node to this one */ parNode = BLI_dlrbTree_search(tree, cmp_cb, data); - /* add new node to the BST in the 'standard way' as appropriate + /* add new node to the BST in the 'standard way' as appropriate * NOTE: we do not support duplicates in our tree... */ if (parNode) { - /* check how this new node compares with the existing ones + /* check how this new node compares with the existing ones * NOTE: it is assumed that the values will be unit values only */ switch (cmp_cb(parNode, data)) { @@ -536,7 +536,7 @@ DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, { node = new_cb(data); new_node = 1; - + parNode->left = node; node->parent = parNode; break; @@ -545,7 +545,7 @@ DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, { node = new_cb(data); new_node = 1; - + parNode->right = node; node->parent = parNode; break; @@ -562,21 +562,21 @@ DLRBT_Node *BLI_dlrbTree_add(DLRBT_Tree *tree, DLRBT_Comparator_FP cmp_cb, /* no nodes in the tree yet... add a new node as the root */ node = new_cb(data); new_node = 1; - + tree->root = node; } - + /* if a new node was added, it should be tagged as red, and then balanced as appropriate */ if (new_node) { /* tag this new node as being 'red' */ node->tree_col = DLRBT_RED; - + /* perform BST balancing steps: * start from case 1, an trek through the tail-recursive insertion checks */ insert_check_1(tree, node); } - + /* return the node added */ return node; } diff --git a/source/blender/blenlib/intern/boxpack_2d.c b/source/blender/blenlib/intern/boxpack_2d.c index dea396313892..0b83423921f7 100644 --- a/source/blender/blenlib/intern/boxpack_2d.c +++ b/source/blender/blenlib/intern/boxpack_2d.c @@ -317,7 +317,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r vert->used = false; vert->index = i++; box->v[BL] = vert++; - + vert->trb = vert->brb = vert->tlb = vert->isect_cache[0] = vert->isect_cache[1] = vert->isect_cache[2] = vert->isect_cache[3] = NULL; @@ -326,7 +326,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r vert->used = false; vert->index = i++; box->v[TR] = vert++; - + vert->trb = vert->blb = vert->tlb = vert->isect_cache[0] = vert->isect_cache[1] = vert->isect_cache[2] = vert->isect_cache[3] = NULL; @@ -335,7 +335,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r vert->used = false; vert->index = i++; box->v[TL] = vert++; - + vert->trb = vert->blb = vert->brb = vert->isect_cache[0] = vert->isect_cache[1] = vert->isect_cache[2] = vert->isect_cache[3] = NULL; @@ -406,7 +406,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r /* This vert has a free quadrant * Test if we can place the box here - * vert->free & quad_flags[j] - Checks + * vert->free & quad_flags[j] - Checks * */ for (j = 0; (j < 4) && isect; j++) { @@ -434,7 +434,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r * with any other boxes * Assume no intersection... */ isect = false; - + if ( /* Constrain boxes to positive X/Y values */ box_xmin_get(box) < 0.0f || box_ymin_get(box) < 0.0f || /* check for last intersected */ @@ -494,8 +494,8 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r /* Mask free flags for verts that are * on the bottom or side so we don't get * boxes outside the given rectangle ares - * - * We can do an else/if here because only the first + * + * We can do an else/if here because only the first * box can be at the very bottom left corner */ if (box_xmin_get(box) <= 0) { box->v[TL]->free &= ~(TLF | BLF); @@ -508,7 +508,7 @@ void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r /* The following block of code does a logical * check with 2 adjacent boxes, its possible to - * flag verts on one or both of the boxes + * flag verts on one or both of the boxes * as being used by checking the width or * height of both boxes */ if (vert->tlb && vert->trb && (box == vert->tlb || box == vert->trb)) { diff --git a/source/blender/blenlib/intern/dynlib.c b/source/blender/blenlib/intern/dynlib.c index 51b91fb360fa..33ba18ec409b 100644 --- a/source/blender/blenlib/intern/dynlib.c +++ b/source/blender/blenlib/intern/dynlib.c @@ -64,7 +64,7 @@ DynamicLibrary *BLI_dynlib_open(const char *name) lib = MEM_callocN(sizeof(*lib), "Dynamic Library"); lib->handle = handle; - + return lib; } @@ -92,7 +92,7 @@ char *BLI_dynlib_get_error_as_string(DynamicLibrary *lib) return buf; } } - + return NULL; } @@ -116,7 +116,7 @@ DynamicLibrary *BLI_dynlib_open(const char *name) lib = MEM_callocN(sizeof(*lib), "Dynamic Library"); lib->handle = handle; - + return lib; } @@ -130,7 +130,7 @@ char *BLI_dynlib_get_error_as_string(DynamicLibrary *lib) (void)lib; /* unused */ return dlerror(); } - + void BLI_dynlib_close(DynamicLibrary *lib) { dlclose(lib->handle); @@ -138,4 +138,3 @@ void BLI_dynlib_close(DynamicLibrary *lib) } #endif - diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c index ad53457f863d..0b57a727452b 100644 --- a/source/blender/blenlib/intern/fileops.c +++ b/source/blender/blenlib/intern/fileops.c @@ -64,7 +64,7 @@ #include "BLI_sys_types.h" // for intptr_t support #if 0 /* UNUSED */ -/* gzip the file in from and write it to "to". +/* gzip the file in from and write it to "to". * return -1 if zlib fails, -2 if the originating file does not exist * note: will remove the "from" file */ @@ -95,14 +95,14 @@ int BLI_file_gzip(const char *from, const char *to) } else if (readsize == 0) break; /* done reading */ - + if (gzwrite(gzfile, buffer, readsize) <= 0) { rval = -1; /* error happened in writing */ fprintf(stderr, "Error writing gz file %s: %s.\n", to, gzerror(gzfile, &err)); break; } } - + gzclose(gzfile); close(file); @@ -141,7 +141,7 @@ char *BLI_file_ungzip_to_mem(const char *from_file, int *r_size) break; } } - + gzclose(gzfile); if (size == 0) { @@ -389,7 +389,7 @@ int BLI_move(const char *file, const char *to) strcat(str, BLI_last_slash(file) + 1); } } - + UTF16_ENCODE(file); UTF16_ENCODE(str); err = !MoveFileW(file_16, str_16); @@ -500,7 +500,7 @@ int BLI_rename(const char *from, const char *to) /* make sure the filenames are different (case insensitive) before removing */ if (BLI_exists(to) && BLI_strcasecmp(from, to)) if (BLI_delete(to, false, false)) return 1; - + return urename(from, to); } @@ -1033,7 +1033,7 @@ bool BLI_dir_create_recursive(const char *dirname) #endif BLI_strncpy(tmp, dirname, size); - + /* Avoids one useless recursion in case of '/foo/bar/' path... */ BLI_del_slash(tmp); @@ -1064,7 +1064,7 @@ int BLI_rename(const char *from, const char *to) if (!BLI_exists(from)) { return 1; } - + if (BLI_exists(to)) if (BLI_delete(to, false, false)) return 1; diff --git a/source/blender/blenlib/intern/fnmatch.c b/source/blender/blenlib/intern/fnmatch.c index 60e898a3f193..36c1ef394a22 100644 --- a/source/blender/blenlib/intern/fnmatch.c +++ b/source/blender/blenlib/intern/fnmatch.c @@ -242,5 +242,3 @@ fnmatch (const char *pattern, const char *string, int flags) /* intentionally empty for UNIX */ #endif /* WIN32 */ - - diff --git a/source/blender/blenlib/intern/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c index e990f0b663cb..c7604b3cd6d6 100644 --- a/source/blender/blenlib/intern/freetypefont.c +++ b/source/blender/blenlib/intern/freetypefont.c @@ -445,7 +445,7 @@ static int check_freetypefont(PackedFile *pf) } } } - + return success; } @@ -470,14 +470,14 @@ VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf) } success = check_freetypefont(pf); - + if (success) { vfd = objfnt_to_ftvfontdata(pf); } /* free Freetype */ FT_Done_FreeType(library); - + return vfd; } diff --git a/source/blender/blenlib/intern/graph.c b/source/blender/blenlib/intern/graph.c index 911e8aae3407..e346b8ec0037 100644 --- a/source/blender/blenlib/intern/graph.c +++ b/source/blender/blenlib/intern/graph.c @@ -47,7 +47,7 @@ void BLI_freeNode(BGraph *graph, BNode *node) if (node->arcs) { MEM_freeN(node->arcs); } - + if (graph->free_node) { graph->free_node(node); } @@ -76,7 +76,7 @@ void BLI_removeArc(BGraph *graph, BArc *arc) void BLI_flagNodes(BGraph *graph, int flag) { BNode *node; - + for (node = graph->nodes.first; node; node = node->next) { node->flag = flag; } @@ -85,7 +85,7 @@ void BLI_flagNodes(BGraph *graph, int flag) void BLI_flagArcs(BGraph *graph, int flag) { BArc *arc; - + for (arc = graph->arcs.first; arc; arc = arc->next) { arc->flag = flag; } @@ -106,9 +106,9 @@ void BLI_buildAdjacencyList(BGraph *graph) if (node->arcs != NULL) { MEM_freeN(node->arcs); } - + node->arcs = MEM_callocN((node->degree) * sizeof(BArc *), "adjacency list"); - + /* temporary use to indicate the first index available in the lists */ node->flag = 0; } @@ -132,9 +132,9 @@ void BLI_rebuildAdjacencyListForNode(BGraph *graph, BNode *node) if (node->arcs != NULL) { MEM_freeN(node->arcs); } - + node->arcs = MEM_callocN((node->degree) * sizeof(BArc *), "adjacency list"); - + /* temporary use to indicate the first index available in the lists */ node->flag = 0; @@ -167,13 +167,13 @@ void BLI_freeAdjacencyList(BGraph *graph) bool BLI_hasAdjacencyList(BGraph *graph) { BNode *node; - + for (node = graph->nodes.first; node; node = node->next) { if (node->arcs == NULL) { return false; } } - + return true; } @@ -188,10 +188,10 @@ void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node arc->tail = node_src; node_src->degree++; } - + if (arc->head == arc->tail) { node_src->degree -= 2; - + graph->free_arc(arc); BLI_freelinkN(&graph->arcs, arc); } @@ -204,10 +204,10 @@ void BLI_replaceNodeInArc(BGraph *graph, BArc *arc, BNode *node_src, BNode *node void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced) { BArc *arc, *next_arc; - + for (arc = graph->arcs.first; arc; arc = next_arc) { next_arc = arc->next; - + if (arc->head == node_replaced) { arc->head = node_src; node_replaced->degree--; @@ -219,15 +219,15 @@ void BLI_replaceNode(BGraph *graph, BNode *node_src, BNode *node_replaced) node_replaced->degree--; node_src->degree++; } - + if (arc->head == arc->tail) { node_src->degree -= 2; - + graph->free_arc(arc); BLI_freelinkN(&graph->arcs, arc); } } - + if (node_replaced->degree == 0) { BLI_removeNode(graph, node_replaced); } @@ -237,7 +237,7 @@ void BLI_removeDoubleNodes(BGraph *graph, float limit) { const float limit_sq = limit * limit; BNode *node_src, *node_replaced; - + for (node_src = graph->nodes.first; node_src; node_src = node_src->next) { for (node_replaced = graph->nodes.first; node_replaced; node_replaced = node_replaced->next) { if (node_replaced != node_src && len_squared_v3v3(node_replaced->p, node_src->p) <= limit_sq) { @@ -245,7 +245,7 @@ void BLI_removeDoubleNodes(BGraph *graph, float limit) } } } - + } BNode *BLI_FindNodeByPosition(BGraph *graph, const float p[3], const float limit) @@ -253,7 +253,7 @@ BNode *BLI_FindNodeByPosition(BGraph *graph, const float p[3], const float limit const float limit_sq = limit * limit; BNode *closest_node = NULL, *node; float min_distance = 0.0f; - + for (node = graph->nodes.first; node; node = node->next) { float distance = len_squared_v3v3(p, node->p); if (distance <= limit_sq && (closest_node == NULL || distance < min_distance)) { @@ -261,7 +261,7 @@ BNode *BLI_FindNodeByPosition(BGraph *graph, const float p[3], const float limit min_distance = distance; } } - + return closest_node; } /************************************* SUBGRAPH DETECTION **********************************************/ @@ -271,15 +271,15 @@ static void flagSubgraph(BNode *node, int subgraph) if (node->subgraph_index == 0) { BArc *arc; int i; - + node->subgraph_index = subgraph; - + for (i = 0; i < node->degree; i++) { arc = node->arcs[i]; flagSubgraph(BLI_otherNode(arc, node), subgraph); } } -} +} int BLI_FlagSubgraphs(BGraph *graph) { @@ -289,18 +289,18 @@ int BLI_FlagSubgraphs(BGraph *graph) if (BLI_hasAdjacencyList(graph) == 0) { BLI_buildAdjacencyList(graph); } - + for (node = graph->nodes.first; node; node = node->next) { node->subgraph_index = 0; } - + for (node = graph->nodes.first; node; node = node->next) { if (node->subgraph_index == 0) { subgraph++; flagSubgraph(node, subgraph); } } - + return subgraph; } @@ -320,7 +320,7 @@ void BLI_ReflagSubgraph(BGraph *graph, int old_subgraph, int new_subgraph) static bool detectCycle(BNode *node, BArc *src_arc) { bool value = false; - + if (node->flag == 0) { int i; @@ -329,7 +329,7 @@ static bool detectCycle(BNode *node, BArc *src_arc) for (i = 0; i < node->degree && value == 0; i++) { BArc *arc = node->arcs[i]; - + /* don't go back on the source arc */ if (arc != src_arc) { value = detectCycle(BLI_otherNode(arc, node), arc); @@ -339,7 +339,7 @@ static bool detectCycle(BNode *node, BArc *src_arc) else { value = true; } - + return value; } @@ -347,9 +347,9 @@ bool BLI_isGraphCyclic(BGraph *graph) { BNode *node; bool value = false; - + /* NEED TO CHECK IF ADJACENCY LIST EXIST */ - + /* Mark all nodes as not visited */ BLI_flagNodes(graph, 0); @@ -360,20 +360,20 @@ bool BLI_isGraphCyclic(BGraph *graph) value = value || detectCycle(node, NULL); } } - + return value; } BArc *BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v) { BArc *nextArc; - + for (nextArc = graph->arcs.first; nextArc; nextArc = nextArc->next) { if (arc != nextArc && (nextArc->head == v || nextArc->tail == v)) { break; } } - + return nextArc; } @@ -382,9 +382,9 @@ BArc *BLI_findConnectedArc(BGraph *graph, BArc *arc, BNode *v) static int subtreeShape(BNode *node, BArc *rootArc, int include_root) { int depth = 0; - + node->flag = 1; - + if (include_root) { BNode *newNode = BLI_otherNode(rootArc, node); return subtreeShape(newNode, rootArc, 0); @@ -396,18 +396,18 @@ static int subtreeShape(BNode *node, BArc *rootArc, int include_root) } else { int i; - + for (i = 0; i < node->degree; i++) { BArc *arc = node->arcs[i]; BNode *newNode = BLI_otherNode(arc, node); - + /* stop immediate and cyclic backtracking */ if (arc != rootArc && newNode->flag == 0) { depth += subtreeShape(newNode, arc, 0); } } } - + return SHAPE_RADIX * depth + 1; } } @@ -428,13 +428,13 @@ float BLI_subtreeLength(BNode *node) for (i = 0; i < node->degree; i++) { BArc *arc = node->arcs[i]; BNode *other_node = BLI_otherNode(arc, node); - + if (other_node->flag != 0) { - float subgraph_length = arc->length + BLI_subtreeLength(other_node); + float subgraph_length = arc->length + BLI_subtreeLength(other_node); length = MAX2(length, subgraph_length); } } - + return length; } @@ -443,12 +443,12 @@ void BLI_calcGraphLength(BGraph *graph) float length = 0; int nb_subgraphs; int i; - + nb_subgraphs = BLI_FlagSubgraphs(graph); - + for (i = 1; i <= nb_subgraphs; i++) { BNode *node; - + for (node = graph->nodes.first; node; node = node->next) { /* start on an external node of the subgraph */ if (node->subgraph_index == i && node->degree == 1) { @@ -458,7 +458,7 @@ void BLI_calcGraphLength(BGraph *graph) } } } - + graph->length = length; } @@ -469,7 +469,7 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level void BLI_mirrorAlongAxis(float v[3], float center[3], float axis[3]) { float dv[3], pv[3]; - + sub_v3_v3v3(dv, v, center); project_v3_v3v3(pv, dv, axis); mul_v3_fl(pv, -2); @@ -481,7 +481,7 @@ static void testRadialSymmetry(BGraph *graph, BNode *root_node, RadialArc *ring, const float limit_sq = limit * limit; int symmetric = 1; int i; - + /* sort ring by angle */ for (i = 0; i < total - 1; i++) { float minAngle = FLT_MAX; @@ -520,13 +520,13 @@ static void testRadialSymmetry(BGraph *graph, BNode *root_node, RadialArc *ring, add_v3_v3v3(tangent, ring[i].n, ring[j].n); cross_v3_v3v3(normal, tangent, axis); - + node1 = BLI_otherNode(ring[i].arc, root_node); node2 = BLI_otherNode(ring[j].arc, root_node); copy_v3_v3(p, node2->p); BLI_mirrorAlongAxis(p, root_node->p, normal); - + /* check if it's within limit before continuing */ if (len_squared_v3v3(node1->p, p) > limit_sq) { symmetric = 0; @@ -539,7 +539,7 @@ static void testRadialSymmetry(BGraph *graph, BNode *root_node, RadialArc *ring, copy_v3_v3(root_node->symmetry_axis, axis); root_node->symmetry_flag |= SYM_PHYSICAL; root_node->symmetry_flag |= SYM_RADIAL; - + /* FLAG SYMMETRY GROUP */ for (i = 0; i < total; i++) { ring[i].arc->symmetry_group = group; @@ -567,7 +567,7 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo /* total the number of arcs in the symmetry ring */ for (i = 0; i < root_node->degree; i++) { BArc *connectedArc = root_node->arcs[i]; - + /* depth is store as a negative in flag. symmetry level is positive */ if (connectedArc->symmetry_level == -depth) { total++; @@ -580,7 +580,7 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo /* fill in the ring */ for (i = 0; i < root_node->degree; i++) { BArc *connectedArc = root_node->arcs[i]; - + /* depth is store as a negative in flag. symmetry level is positive */ if (connectedArc->symmetry_level == -depth) { BNode *otherNode = BLI_otherNode(connectedArc, root_node); @@ -608,14 +608,14 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo for (j = i - 1; j >= 0; j--) { BArc *arc1, *arc2; - + arc1 = ring[j].arc; arc2 = ring[j + 1].arc; - + if (arc1->length > arc2->length) { /* swap with smaller */ RadialArc tmp; - + tmp = ring[j + 1]; ring[j + 1] = ring[j]; ring[j] = tmp; @@ -629,11 +629,11 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo /* Dispatch to specific symmetry tests */ first = 0; group = 0; - + for (i = 1; i < total; i++) { int dispatch = 0; int last = i - 1; - + if (fabsf(ring[first].arc->length - ring[i].arc->length) > limit) { dispatch = 1; } @@ -645,9 +645,9 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo last = i; dispatch = 1; } - + if (dispatch) { - int sub_total = last - first + 1; + int sub_total = last - first + 1; group += 1; @@ -658,32 +658,32 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo else if (sub_total == 2) { BArc *arc1, *arc2; BNode *node1, *node2; - + arc1 = ring[first].arc; arc2 = ring[last].arc; - + node1 = BLI_otherNode(arc1, root_node); node2 = BLI_otherNode(arc2, root_node); - + testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, group); } else if (sub_total != total) /* allocate a new sub ring if needed */ { RadialArc *sub_ring = MEM_callocN(sizeof(RadialArc) * sub_total, "radial symmetry ring"); int sub_i; - + /* fill in the sub ring */ for (sub_i = 0; sub_i < sub_total; sub_i++) { sub_ring[sub_i] = ring[first + sub_i]; } - + testRadialSymmetry(graph, root_node, sub_ring, sub_total, axis, limit, group); - + MEM_freeN(sub_ring); } else if (sub_total == total) { testRadialSymmetry(graph, root_node, ring, total, axis, limit, group); } - + first = i; } } @@ -695,11 +695,11 @@ static void handleRadialSymmetry(BGraph *graph, BNode *root_node, int depth, flo static void flagAxialSymmetry(BNode *root_node, BNode *end_node, BArc *arc, int group) { float vec[3]; - + arc->symmetry_group = group; - + sub_v3_v3v3(vec, end_node->p, root_node->p); - + if (dot_v3v3(vec, root_node->symmetry_axis) < 0) { arc->symmetry_flag |= SYM_SIDE_NEGATIVE; } @@ -719,9 +719,9 @@ static void testAxialSymmetry(BGraph *graph, BNode *root_node, BNode *node1, BNo sub_v3_v3v3(p, root_node->p, node2->p); cross_v3_v3v3(vec, p, axis); add_v3_v3(vec, nor); - + cross_v3_v3v3(nor, vec, axis); - + if (fabsf(nor[0]) > fabsf(nor[1]) && fabsf(nor[0]) > fabsf(nor[2]) && nor[0] < 0) { negate_v3(nor); } @@ -731,11 +731,11 @@ static void testAxialSymmetry(BGraph *graph, BNode *root_node, BNode *node1, BNo else if (fabsf(nor[2]) > fabsf(nor[1]) && fabsf(nor[2]) > fabsf(nor[0]) && nor[2] < 0) { negate_v3(nor); } - + /* mirror node2 along axis */ copy_v3_v3(p, node2->p); BLI_mirrorAlongAxis(p, root_node->p, nor); - + /* check if it's within limit before continuing */ if (len_squared_v3v3(node1->p, p) <= limit_sq) { /* mark node as symmetric physically */ @@ -746,7 +746,7 @@ static void testAxialSymmetry(BGraph *graph, BNode *root_node, BNode *node1, BNo /* flag side on arcs */ flagAxialSymmetry(root_node, node1, arc1, group); flagAxialSymmetry(root_node, node2, arc2, group); - + if (graph->axial_symmetry) { graph->axial_symmetry(root_node, node1, node2, arc1, arc2); } @@ -761,13 +761,13 @@ static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, floa BArc *arc1 = NULL, *arc2 = NULL; BNode *node1 = NULL, *node2 = NULL; int i; - + /* mark topological symmetry */ root_node->symmetry_flag |= SYM_TOPOLOGICAL; for (i = 0; i < root_node->degree; i++) { BArc *connectedArc = root_node->arcs[i]; - + /* depth is store as a negative in flag. symmetry level is positive */ if (connectedArc->symmetry_level == -depth) { if (arc1 == NULL) { @@ -781,12 +781,12 @@ static void handleAxialSymmetry(BGraph *graph, BNode *root_node, int depth, floa } } } - + /* shouldn't happen, but just to be sure */ if (node1 == NULL || node2 == NULL) { return; } - + testAxialSymmetry(graph, root_node, node1, node2, arc1, arc2, axis, limit, 1); } @@ -795,13 +795,13 @@ static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int float axis[3] = {0, 0, 0}; int count = 0; int i; - + /* count the number of branches in this symmetry group * and determinate the axis of symmetry */ for (i = 0; i < node->degree; i++) { BArc *connectedArc = node->arcs[i]; - + /* depth is store as a negative in flag. symmetry level is positive */ if (connectedArc->symmetry_level == -depth) { count++; @@ -822,11 +822,11 @@ static void markdownSecondarySymmetry(BGraph *graph, BNode *node, int depth, int else { handleRadialSymmetry(graph, node, depth, axis, limit); } - + /* markdown secondary symetries */ for (i = 0; i < node->degree; i++) { BArc *connectedArc = node->arcs[i]; - + if (connectedArc->symmetry_level == -depth) { /* markdown symmetry for branches corresponding to the depth */ markdownSymmetryArc(graph, connectedArc, node, level + 1, limit); @@ -841,16 +841,16 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level /* if arc is null, we start straight from a node */ if (arc) { arc->symmetry_level = level; - + node = BLI_otherNode(arc, node); } - + for (i = 0; i < node->degree; i++) { BArc *connectedArc = node->arcs[i]; - + if (connectedArc != arc) { BNode *connectedNode = BLI_otherNode(connectedArc, node); - + /* symmetry level is positive value, negative values is subtree depth */ connectedArc->symmetry_level = -BLI_subtreeShape(graph, connectedNode, connectedArc, 0); } @@ -861,17 +861,17 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level for (i = 0; i < node->degree; i++) { int issymmetryAxis = 0; BArc *connectedArc = node->arcs[i]; - + /* only arcs not already marked as symetric */ if (connectedArc->symmetry_level < 0) { int j; - + /* true by default */ issymmetryAxis = 1; - + for (j = 0; j < node->degree; j++) { BArc *otherArc = node->arcs[j]; - + /* different arc, same depth */ if (otherArc != connectedArc && otherArc->symmetry_level == connectedArc->symmetry_level) { /* not on the symmetry axis */ @@ -880,7 +880,7 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level } } } - + /* arc could be on the symmetry axis */ if (issymmetryAxis == 1) { /* no arc as been marked previously, keep this one */ @@ -893,17 +893,17 @@ static void markdownSymmetryArc(BGraph *graph, BArc *arc, BNode *node, int level } } } - + /* go down the arc continuing the symmetry axis */ if (arc) { markdownSymmetryArc(graph, arc, node, level, limit); } - + /* secondary symmetry */ for (i = 0; i < node->degree; i++) { BArc *connectedArc = node->arcs[i]; - + /* only arcs not already marked as symetric and is not the next arc on the symmetry axis */ if (connectedArc->symmetry_level < 0) { /* subtree depth is store as a negative value in the symmetry */ @@ -916,34 +916,34 @@ void BLI_markdownSymmetry(BGraph *graph, BNode *root_node, float limit) { BNode *node; BArc *arc; - + if (root_node == NULL) { return; } - + if (BLI_isGraphCyclic(graph)) { return; } - + /* mark down all arcs as non-symetric */ BLI_flagArcs(graph, 0); - + /* mark down all nodes as not on the symmetry axis */ BLI_flagNodes(graph, 0); node = root_node; - + /* sanity check REMOVE ME */ if (node->degree > 0) { arc = node->arcs[0]; - + if (node->degree == 1) { markdownSymmetryArc(graph, arc, node, 1, limit); } else { markdownSymmetryArc(graph, NULL, node, 1, limit); } - + /* mark down non-symetric arcs */ @@ -973,13 +973,13 @@ void *IT_head(void *arg) void *IT_tail(void *arg) { BArcIterator *iter = (BArcIterator *)arg; - return iter->tail(iter); + return iter->tail(iter); } void *IT_peek(void *arg, int n) { BArcIterator *iter = (BArcIterator *)arg; - + if (iter->index + n < 0) { return iter->head(iter); } diff --git a/source/blender/blenlib/intern/gsqueue.c b/source/blender/blenlib/intern/gsqueue.c index 5c8c43ab92a8..29b882d0e997 100644 --- a/source/blender/blenlib/intern/gsqueue.c +++ b/source/blender/blenlib/intern/gsqueue.c @@ -66,7 +66,7 @@ GSQueue *BLI_gsqueue_new(size_t elem_size) GSQueue *gq = MEM_mallocN(sizeof(*gq), "gqueue_new"); gq->head = gq->tail = NULL; gq->elem_size = elem_size; - + return gq; } @@ -82,13 +82,13 @@ bool BLI_gsqueue_is_empty(GSQueue *gq) * Query number elements in the queue */ int BLI_gsqueue_len(GSQueue *gq) -{ +{ GSQueueElem *elem; int size = 0; for (elem = gq->head; elem; elem = elem->next) size++; - + return size; } @@ -121,7 +121,7 @@ void BLI_gsqueue_pop(GSQueue *gq, void *r_item) else { gq->head = gq->head->next; } - + if (r_item) { memcpy(r_item, elem->data, gq->elem_size); } @@ -137,7 +137,7 @@ void BLI_gsqueue_pop(GSQueue *gq, void *r_item) void BLI_gsqueue_push(GSQueue *gq, const void *item) { GSQueueElem *elem; - + /* compare: prevent events added double in row */ if (!BLI_gsqueue_is_empty(gq)) { if (0 == memcmp(item, gq->head->data, gq->elem_size)) @@ -146,7 +146,7 @@ void BLI_gsqueue_push(GSQueue *gq, const void *item) elem = MEM_mallocN(sizeof(*elem) + gq->elem_size, "gqueue_push"); memcpy(elem->data, item, gq->elem_size); elem->next = NULL; - + if (BLI_gsqueue_is_empty(gq)) { gq->tail = gq->head = elem; } diff --git a/source/blender/blenlib/intern/hash_mm2a.c b/source/blender/blenlib/intern/hash_mm2a.c index e8ca9244f25c..6fd227232edd 100644 --- a/source/blender/blenlib/intern/hash_mm2a.c +++ b/source/blender/blenlib/intern/hash_mm2a.c @@ -144,4 +144,3 @@ uint32_t BLI_hash_mm2(const unsigned char *data, size_t len, uint32_t seed) return h; } - diff --git a/source/blender/blenlib/intern/hash_mm3.c b/source/blender/blenlib/intern/hash_mm3.c new file mode 100644 index 000000000000..105c1f46832c --- /dev/null +++ b/source/blender/blenlib/intern/hash_mm3.c @@ -0,0 +1,147 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + * + * Copyright (C) 2018 Blender Foundation. + * + */ + +/** \file blender/blenlib/intern/hash_mm3.c + * \ingroup bli + * + * Functions to compute Murmur3 hash key. + * + * This Code is based on alShaders/Cryptomatte/MurmurHash3.h: + * + * MurmurHash3 was written by Austin Appleby, and is placed in the public + * domain. The author hereby disclaims copyright to this source code. + * + */ + +#include "BLI_compiler_compat.h" +#include "BLI_compiler_attrs.h" +#include "BLI_hash_mm3.h" /* own include */ + +#if defined(_MSC_VER) +# include +# define ROTL32(x,y) _rotl(x,y) +# define BIG_CONSTANT(x) (x) + +/* Other compilers */ +#else /* defined(_MSC_VER) */ +static inline uint32_t rotl32(uint32_t x, int8_t r) +{ + return (x << r) | (x >> (32 - r)); +} +# define ROTL32(x,y) rotl32(x,y) +# define BIG_CONSTANT(x) (x##LLU) +#endif /* !defined(_MSC_VER) */ + +/* Block read - if your platform needs to do endian-swapping or can only + * handle aligned reads, do the conversion here + */ + +BLI_INLINE uint32_t getblock32(const uint32_t * p, int i) +{ + return p[i]; +} + +BLI_INLINE uint64_t getblock64(const uint64_t * p, int i) +{ + return p[i]; +} + +/* Finalization mix - force all bits of a hash block to avalanche */ + +BLI_INLINE uint32_t fmix32(uint32_t h) +{ + h ^= h >> 16; + h *= 0x85ebca6b; + h ^= h >> 13; + h *= 0xc2b2ae35; + h ^= h >> 16; + + return h; +} + +BLI_INLINE uint64_t fmix64(uint64_t k) +{ + k ^= k >> 33; + k *= BIG_CONSTANT(0xff51afd7ed558ccd); + k ^= k >> 33; + k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); + k ^= k >> 33; + + return k; +} + +uint32_t BLI_hash_mm3(const unsigned char *in, size_t len, uint32_t seed) +{ + const uint8_t *data = (const uint8_t *)in; + const int nblocks = len / 4; + + uint32_t h1 = seed; + + const uint32_t c1 = 0xcc9e2d51; + const uint32_t c2 = 0x1b873593; + + /* body */ + + const uint32_t *blocks = (const uint32_t *)(data + nblocks * 4); + + for (int i = -nblocks; i; i++) { + uint32_t k1 = getblock32(blocks, i); + + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + + h1 ^= k1; + h1 = ROTL32(h1, 13); + h1 = h1 * 5 + 0xe6546b64; + } + + /* tail */ + + const uint8_t *tail = (const uint8_t *)(data + nblocks * 4); + + uint32_t k1 = 0; + + switch (len & 3) { + case 3: + k1 ^= tail[2] << 16; + ATTR_FALLTHROUGH; + case 2: + k1 ^= tail[1] << 8; + ATTR_FALLTHROUGH; + case 1: + k1 ^= tail[0]; + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + h1 ^= k1; + } + + /* finalization */ + + h1 ^= len; + + h1 = fmix32(h1); + + return h1; +} diff --git a/source/blender/blenlib/intern/jitter_2d.c b/source/blender/blenlib/intern/jitter_2d.c index 2632e8bc2346..f1ee85f47c28 100644 --- a/source/blender/blenlib/intern/jitter_2d.c +++ b/source/blender/blenlib/intern/jitter_2d.c @@ -177,7 +177,7 @@ void BLI_jitter_init(float (*jitarr)[2], int num) } MEM_freeN(jit2); - + /* finally, move jittertab to be centered around (0, 0) */ for (i = 0; i < num; i++) { jitarr[i][0] -= 0.5f; diff --git a/source/blender/blenlib/intern/listbase.c b/source/blender/blenlib/intern/listbase.c index 5918b4d3cf97..568448327bd0 100644 --- a/source/blender/blenlib/intern/listbase.c +++ b/source/blender/blenlib/intern/listbase.c @@ -308,7 +308,7 @@ void BLI_insertlinkafter(ListBase *listbase, void *vprevlink, void *vnewlink) listbase->last = newlink; return; } - + /* insert at head of list */ if (prevlink == NULL) { newlink->prev = NULL; @@ -349,7 +349,7 @@ void BLI_insertlinkbefore(ListBase *listbase, void *vnextlink, void *vnewlink) listbase->last = newlink; return; } - + /* insert at end of list */ if (nextlink == NULL) { newlink->prev = listbase->last; @@ -451,7 +451,7 @@ bool BLI_listbase_link_move(ListBase *listbase, void *vlink, int step) void BLI_freelist(ListBase *listbase) { Link *link, *next; - + link = listbase->first; while (link) { next = link->next; @@ -468,7 +468,7 @@ void BLI_freelist(ListBase *listbase) void BLI_freelistN(ListBase *listbase) { Link *link, *next; - + link = listbase->first; while (link) { next = link->next; @@ -556,16 +556,16 @@ int BLI_findindex(const ListBase *listbase, const void *vlink) int number = 0; if (vlink == NULL) return -1; - + link = listbase->first; while (link) { if (link == vlink) return number; - + number++; link = link->next; } - + return -1; } @@ -830,13 +830,13 @@ void BLI_listbase_rotate_last(ListBase *lb, void *vlink) LinkData *BLI_genericNodeN(void *data) { LinkData *ld; - + if (data == NULL) return NULL; - + /* create new link, and make it hold the given data */ ld = MEM_callocN(sizeof(LinkData), __func__); ld->data = data; - + return ld; -} +} diff --git a/source/blender/blenlib/intern/math_geom.c b/source/blender/blenlib/intern/math_geom.c index bebb5b02584d..356740b138fd 100644 --- a/source/blender/blenlib/intern/math_geom.c +++ b/source/blender/blenlib/intern/math_geom.c @@ -2475,30 +2475,38 @@ bool isect_ray_aabb_v3( return true; } -/* - * Test a bounding box (AABB) for ray intersection - * assumes the ray is already local to the boundbox space +/** + * Test a bounding box (AABB) for ray intersection. + * Assumes the ray is already local to the boundbox space. + * + * \note: \a direction should be normalized if you intend to use the \a tmin or \a tmax distance results! */ bool isect_ray_aabb_v3_simple( const float orig[3], const float dir[3], const float bb_min[3], const float bb_max[3], float *tmin, float *tmax) { - double t[7]; + double t[6]; float hit_dist[2]; - t[1] = (double)(bb_min[0] - orig[0]) / dir[0]; - t[2] = (double)(bb_max[0] - orig[0]) / dir[0]; - t[3] = (double)(bb_min[1] - orig[1]) / dir[1]; - t[4] = (double)(bb_max[1] - orig[1]) / dir[1]; - t[5] = (double)(bb_min[2] - orig[2]) / dir[2]; - t[6] = (double)(bb_max[2] - orig[2]) / dir[2]; - hit_dist[0] = (float)fmax(fmax(fmin(t[1], t[2]), fmin(t[3], t[4])), fmin(t[5], t[6])); - hit_dist[1] = (float)fmin(fmin(fmax(t[1], t[2]), fmax(t[3], t[4])), fmax(t[5], t[6])); - if ((hit_dist[1] < 0 || hit_dist[0] > hit_dist[1])) + const double invdirx = (dir[0] > 1e-35f || dir[0] < -1e-35f) ? 1.0 / (double)dir[0] : DBL_MAX; + const double invdiry = (dir[1] > 1e-35f || dir[1] < -1e-35f) ? 1.0 / (double)dir[1] : DBL_MAX; + const double invdirz = (dir[2] > 1e-35f || dir[2] < -1e-35f) ? 1.0 / (double)dir[2] : DBL_MAX; + t[0] = (double)(bb_min[0] - orig[0]) * invdirx; + t[1] = (double)(bb_max[0] - orig[0]) * invdirx; + t[2] = (double)(bb_min[1] - orig[1]) * invdiry; + t[3] = (double)(bb_max[1] - orig[1]) * invdiry; + t[4] = (double)(bb_min[2] - orig[2]) * invdirz; + t[5] = (double)(bb_max[2] - orig[2]) * invdirz; + hit_dist[0] = (float)fmax(fmax(fmin(t[0], t[1]), fmin(t[2], t[3])), fmin(t[4], t[5])); + hit_dist[1] = (float)fmin(fmin(fmax(t[0], t[1]), fmax(t[2], t[3])), fmax(t[4], t[5])); + if ((hit_dist[1] < 0.0f || hit_dist[0] > hit_dist[1])) { return false; + } else { - if (tmin) *tmin = hit_dist[0]; - if (tmax) *tmax = hit_dist[1]; + if (tmin) + *tmin = hit_dist[0]; + if (tmax) + *tmax = hit_dist[1]; return true; } } @@ -3665,11 +3673,11 @@ void resolve_quad_uv_v2_deriv(float r_uv[2], float r_deriv[2][2], if (r_deriv) { float tmp1[2], tmp2[2], s[2], t[2]; - + /* clear outputs */ zero_v2(r_deriv[0]); zero_v2(r_deriv[1]); - + sub_v2_v2v2(tmp1, st1, st0); sub_v2_v2v2(tmp2, st2, st3); interp_v2_v2v2(s, tmp1, tmp2, r_uv[1]); @@ -4958,7 +4966,7 @@ float cubic_tangent_factor_circle_v3(const float tan_l[3], const float tan_r[3]) /* -7f causes instability/glitches with Bendy Bones + Custom Refs */ const float eps = 1e-5f; - + const float tan_dot = dot_v3v3(tan_l, tan_r); if (tan_dot > 1.0f - eps) { /* no angle difference (use fallback, length wont make any difference) */ diff --git a/source/blender/blenlib/intern/math_solvers.c b/source/blender/blenlib/intern/math_solvers.c index b8a22900ba1b..e3174d8340af 100644 --- a/source/blender/blenlib/intern/math_solvers.c +++ b/source/blender/blenlib/intern/math_solvers.c @@ -179,4 +179,3 @@ bool BLI_tridiagonal_solve_cyclic(const float *a, const float *b, const float *c return success; } - diff --git a/source/blender/blenlib/intern/math_vector.c b/source/blender/blenlib/intern/math_vector.c index d6e48fa59e7d..acb4ee87f695 100644 --- a/source/blender/blenlib/intern/math_vector.c +++ b/source/blender/blenlib/intern/math_vector.c @@ -1096,6 +1096,27 @@ void negate_vn_vn(float *array_tar, const float *array_src, const int size) } } +void mul_vn_vn(float *array_tar, const float *array_src, const int size) +{ + float *tar = array_tar + (size - 1); + const float *src = array_src + (size - 1); + int i = size; + while (i--) { + *(tar--) *= *(src--); + } +} + +void mul_vn_vnvn(float *array_tar, const float *array_src_a, const float *array_src_b, const int size) +{ + float *tar = array_tar + (size - 1); + const float *src_a = array_src_a + (size - 1); + const float *src_b = array_src_b + (size - 1); + int i = size; + while (i--) { + *(tar--) = *(src_a--) * *(src_b--); + } +} + void mul_vn_fl(float *array_tar, const int size, const float f) { float *array_pt = array_tar + (size - 1); diff --git a/source/blender/blenlib/intern/math_vector_inline.c b/source/blender/blenlib/intern/math_vector_inline.c index 08687a1ab477..715e2e65c966 100644 --- a/source/blender/blenlib/intern/math_vector_inline.c +++ b/source/blender/blenlib/intern/math_vector_inline.c @@ -753,6 +753,16 @@ MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3]) r[2] = a[0] * b[1] - a[1] * b[0]; } +/* cross product suffers from severe precision loss when vectors are + * nearly parallel or opposite; doing the computation in double helps a lot */ +MINLINE void cross_v3_v3v3_hi_prec(float r[3], const float a[3], const float b[3]) +{ + BLI_assert(r != a && r != b); + r[0] = (float)((double)a[1] * (double)b[2] - (double)a[2] * (double)b[1]); + r[1] = (float)((double)a[2] * (double)b[0] - (double)a[0] * (double)b[2]); + r[2] = (float)((double)a[0] * (double)b[1] - (double)a[1] * (double)b[0]); +} + /* Newell's Method */ /* excuse this fairly specific function, * its used for polygon normals all over the place diff --git a/source/blender/blenlib/intern/noise.c b/source/blender/blenlib/intern/noise.c index 83012694ac02..075ae2f5357d 100644 --- a/source/blender/blenlib/intern/noise.c +++ b/source/blender/blenlib/intern/noise.c @@ -421,9 +421,9 @@ float BLI_turbulence(float noisesize, float x, float y, float z, int nr) float s, d = 0.5, div = 1.0; s = BLI_hnoise(noisesize, x, y, z); - + while (nr > 0) { - + s += d * BLI_hnoise(noisesize * d, x, y, z); div += d; d *= 0.5f; @@ -438,13 +438,13 @@ float BLI_turbulence1(float noisesize, float x, float y, float z, int nr) float s, d = 0.5, div = 1.0; s = fabsf((-1.0f + 2.0f * BLI_hnoise(noisesize, x, y, z))); - + while (nr > 0) { - + s += fabsf(d * (-1.0f + 2.0f * BLI_hnoise(noisesize * d, x, y, z))); div += d; d *= 0.5f; - + nr--; } return s / div; @@ -1486,7 +1486,7 @@ float BLI_gNoise(float noisesize, float x, float y, float z, int hard, int noise y *= noisesize; z *= noisesize; } - + if (hard) return fabsf(2.0f * noisefunc(x, y, z) - 1.0f); return noisefunc(x, y, z); } @@ -1497,7 +1497,7 @@ float BLI_gTurbulence(float noisesize, float x, float y, float z, int oct, int h float (*noisefunc)(float, float, float); float sum, t, amp = 1, fscale = 1; int i; - + switch (noisebasis) { case 1: noisefunc = orgPerlinNoiseU; @@ -1548,7 +1548,7 @@ float BLI_gTurbulence(float noisesize, float x, float y, float z, int oct, int h if (hard) t = fabsf(2.0f * t - 1.0f); sum += t * amp; } - + sum *= ((float)(1 << oct) / (float)((1 << (oct + 1)) - 1)); return sum; @@ -1610,7 +1610,7 @@ float mg_fBm(float x, float y, float z, float H, float lacunarity, float octaves break; } } - + for (i = 0; i < (int)octaves; i++) { value += noisefunc(x, y, z) * pwr; pwr *= pwHL; @@ -1865,7 +1865,7 @@ float mg_RidgedMultiFractal(float x, float y, float z, float H, float lacunarity int i; float pwHL = powf(lacunarity, -H); float pwr = pwHL; /* starts with i=1 instead of 0 */ - + float (*noisefunc)(float, float, float); switch (noisebasis) { case 1: diff --git a/source/blender/blenlib/intern/path_util.c b/source/blender/blenlib/intern/path_util.c index a3651de73a29..6272f2109d24 100644 --- a/source/blender/blenlib/intern/path_util.c +++ b/source/blender/blenlib/intern/path_util.c @@ -72,6 +72,8 @@ static bool BLI_path_is_abs(const char *name); #endif /* WIN32 */ +// #define DEBUG_STRSIZE + /* implementation */ /** @@ -186,7 +188,7 @@ void BLI_cleanup_path(const char *relabase, char *path) path = path + 2; /* leave the initial "//" untouched */ } } - + /* Note * memmove(start, eind, strlen(eind) + 1); * is the same as @@ -194,7 +196,7 @@ void BLI_cleanup_path(const char *relabase, char *path) * except strcpy should not be used because there is overlap, * so use memmove's slightly more obscure syntax - Campbell */ - + #ifdef WIN32 while ( (start = strstr(path, "\\..\\")) ) { eind = start + strlen("\\..\\") - 1; @@ -521,12 +523,12 @@ void BLI_path_rel(char *file, const char *relfile) const char *lslash; char temp[FILE_MAX]; char res[FILE_MAX]; - + /* if file is already relative, bail out */ if (BLI_path_is_rel(file)) { return; } - + /* also bail out if relative path is not set */ if (relfile[0] == '\0') { return; @@ -578,11 +580,11 @@ void BLI_path_rel(char *file, const char *relfile) BLI_str_replace_char(temp + BLI_path_unc_prefix_len(temp), '\\', '/'); BLI_str_replace_char(file + BLI_path_unc_prefix_len(file), '\\', '/'); - + /* remove /./ which confuse the following slash counting... */ BLI_cleanup_path(NULL, file); BLI_cleanup_path(NULL, temp); - + /* the last slash in the file indicates where the path part ends */ lslash = BLI_last_slash(temp); @@ -609,7 +611,7 @@ void BLI_path_rel(char *file, const char *relfile) } } - /* we might have passed the slash when the beginning of a dir matches + /* we might have passed the slash when the beginning of a dir matches * so we rewind. Only check on the actual filename */ if (*q != '/') { @@ -618,11 +620,11 @@ void BLI_path_rel(char *file, const char *relfile) else if (*p != '/') { while ( (p >= temp) && (*p != '/') ) { --p; --q; } } - + r += BLI_strcpy_rlen(r, "//"); /* p now points to the slash that is at the beginning of the part - * where the path is different from the relative path. + * where the path is different from the relative path. * We count the number of directories we need to go up in the * hierarchy to arrive at the common 'prefix' of the path */ @@ -636,7 +638,7 @@ void BLI_path_rel(char *file, const char *relfile) /* don't copy the slash at the beginning */ r += BLI_strcpy_rlen(r, q + 1); - + #ifdef WIN32 BLI_str_replace_char(res + 2, '/', '\\'); #endif @@ -658,6 +660,9 @@ void BLI_path_rel(char *file, const char *relfile) */ bool BLI_path_suffix(char *string, size_t maxlen, const char *suffix, const char *sep) { +#ifdef DEBUG_STRSIZE + memset(string, 0xff, sizeof(*string) * maxlen); +#endif const size_t string_len = strlen(string); const size_t suffix_len = strlen(suffix); const size_t sep_len = strlen(sep); @@ -698,7 +703,7 @@ bool BLI_parent_dir(char *path) BLI_join_dirfile(tmp, sizeof(tmp), path, parent_dir); BLI_cleanup_dir(NULL, tmp); /* does all the work of normalizing the path for us */ - if (!BLI_testextensie(tmp, parent_dir)) { + if (!BLI_path_extension_check(tmp, parent_dir)) { strcpy(path, tmp); /* We assume pardir is always shorter... */ return true; } @@ -728,7 +733,7 @@ static bool stringframe_chars(const char *path, int *char_start, int *char_end) ch_end++; } i = ch_end - 1; /* keep searching */ - + /* don't break, there may be a slash after this that invalidates the previous #'s */ } } @@ -945,7 +950,7 @@ bool BLI_path_abs(char *path, const char *basepath) } /* we are checking here if we have an absolute path that is not in the current - * blend file as a lib main - we are basically checking for the case that a + * blend file as a lib main - we are basically checking for the case that a * UNIX root '/' is passed. */ if (!wasrelative && !BLI_path_is_abs(path)) { @@ -962,20 +967,20 @@ bool BLI_path_abs(char *path, const char *basepath) } #else BLI_strncpy(tmp, path, sizeof(tmp)); - + /* Check for loading a windows path on a posix system - * in this case, there is no use in trying C:/ since it + * in this case, there is no use in trying C:/ since it * will never exist on a unix os. - * + * * Add a / prefix and lowercase the driveletter, remove the : * C:\foo.JPG -> /c/foo.JPG */ - + if (isalpha(tmp[0]) && tmp[1] == ':' && (tmp[2] == '\\' || tmp[2] == '/') ) { tmp[1] = tolower(tmp[0]); /* replace ':' with driveletter */ - tmp[0] = '/'; + tmp[0] = '/'; /* '\' the slash will be converted later */ } - + #endif /* push slashes into unix mode - strings entering this part are @@ -1004,7 +1009,7 @@ bool BLI_path_abs(char *path, const char *basepath) const int baselen = (int) (lslash - base) + 1; /* length up to and including last "/" */ /* use path for temp storage here, we copy back over it right away */ BLI_strncpy(path, tmp + 2, FILE_MAX); /* strip "//" */ - + memcpy(tmp, base, baselen); /* prefix with base up to last "/" */ BLI_strncpy(tmp + baselen, path, sizeof(tmp) - baselen); /* append path after "//" */ BLI_strncpy(path, tmp, FILE_MAX); /* return as result */ @@ -1045,9 +1050,12 @@ bool BLI_path_abs(char *path, const char *basepath) */ bool BLI_path_cwd(char *path, const size_t maxlen) { +#ifdef DEBUG_STRSIZE + memset(path, 0xff, sizeof(*path) * maxlen); +#endif bool wasrelative = true; const int filelen = strlen(path); - + #ifdef WIN32 if ((filelen >= 3 && BLI_path_is_abs(path)) || BLI_path_is_unc(path)) wasrelative = false; @@ -1055,7 +1063,7 @@ bool BLI_path_cwd(char *path, const size_t maxlen) if (filelen >= 2 && path[0] == '/') wasrelative = false; #endif - + if (wasrelative) { char cwd[FILE_MAX]; /* in case the full path to the blend isn't used */ @@ -1068,7 +1076,7 @@ bool BLI_path_cwd(char *path, const size_t maxlen) printf("Could not get the current working directory - $PWD for an unknown reason.\n"); } } - + return wasrelative; } @@ -1132,6 +1140,9 @@ bool BLI_path_program_search( char *fullname, const size_t maxlen, const char *name) { +#ifdef DEBUG_STRSIZE + memset(fullname, 0xff, sizeof(*fullname) * maxlen); +#endif const char *path; bool retval = false; @@ -1286,10 +1297,10 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir, c /* Resolve relative references */ if (relabase && dir[0] == '/' && dir[1] == '/') { char *lslash; - + /* Get the file name, chop everything past the last slash (ie. the filename) */ strcpy(string, relabase); - + lslash = (char *)BLI_last_slash(string); if (lslash) *(lslash + 1) = 0; @@ -1314,7 +1325,7 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir, c else { /* we're out of luck here, guessing the first valid drive, usually c:\ */ get_default_root(string); } - + /* ignore leading slashes */ while (*dir == '/' || *dir == '\\') dir++; } @@ -1332,17 +1343,17 @@ void BLI_make_file_string(const char *relabase, char *string, const char *dir, c } /* since we've now removed all slashes, put back one slash at the end. */ strcat(string, "/"); - + while (*file && (*file == '/' || *file == '\\')) /* Trim slashes from the front of file */ file++; - + strcat(string, file); - + /* Push all slashes to the system preferred direction */ BLI_path_native_slash(string); } -static bool testextensie_ex(const char *str, const size_t str_len, +static bool path_extension_check_ex(const char *str, const size_t str_len, const char *ext, const size_t ext_len) { BLI_assert(strlen(str) == str_len); @@ -1353,12 +1364,12 @@ static bool testextensie_ex(const char *str, const size_t str_len, } /* does str end with ext. */ -bool BLI_testextensie(const char *str, const char *ext) +bool BLI_path_extension_check(const char *str, const char *ext) { - return testextensie_ex(str, strlen(str), ext, strlen(ext)); + return path_extension_check_ex(str, strlen(str), ext, strlen(ext)); } -bool BLI_testextensie_n(const char *str, ...) +bool BLI_path_extension_check_n(const char *str, ...) { const size_t str_len = strlen(str); @@ -1369,7 +1380,7 @@ bool BLI_testextensie_n(const char *str, ...) va_start(args, str); while ((ext = (const char *) va_arg(args, void *))) { - if (testextensie_ex(str, str_len, ext, strlen(ext))) { + if (path_extension_check_ex(str, str_len, ext, strlen(ext))) { ret = true; break; } @@ -1381,13 +1392,13 @@ bool BLI_testextensie_n(const char *str, ...) } /* does str end with any of the suffixes in *ext_array. */ -bool BLI_testextensie_array(const char *str, const char **ext_array) +bool BLI_path_extension_check_array(const char *str, const char **ext_array) { const size_t str_len = strlen(str); int i = 0; while (ext_array[i]) { - if (testextensie_ex(str, str_len, ext_array[i], strlen(ext_array[i]))) { + if (path_extension_check_ex(str, str_len, ext_array[i], strlen(ext_array[i]))) { return true; } @@ -1401,7 +1412,7 @@ bool BLI_testextensie_array(const char *str, const char **ext_array) * '*.zip;*.py;*.exe' * does str match any of the semicolon-separated glob patterns in fnmatch. */ -bool BLI_testextensie_glob(const char *str, const char *ext_fnmatch) +bool BLI_path_extension_check_glob(const char *str, const char *ext_fnmatch) { const char *ext_step = ext_fnmatch; char pattern[16]; @@ -1427,13 +1438,47 @@ bool BLI_testextensie_glob(const char *str, const char *ext_fnmatch) return false; } +/** + * Does basic validation of the given glob string, to prevent common issues from string truncation. + * + * For now, only forbids last group to be a wildcard-only one, if there are more than one group + * (i.e. things like "*.txt;*.cpp;*" are changed to "*.txt;*.cpp;") + * + * \returns true if it had to modify given \a ext_fnmatch pattern. + */ +bool BLI_path_extension_glob_validate(char *ext_fnmatch) +{ + bool only_wildcards = false; + + for (size_t i = strlen(ext_fnmatch); i-- > 0; ) { + if (ext_fnmatch[i] == ';') { + /* Group separator, we truncate here if we only had wildcards so far. Otherwise, all is sound and fine. */ + if (only_wildcards) { + ext_fnmatch[i] = '\0'; + return true; + } + return false; + } + if (!ELEM(ext_fnmatch[i], '?', '*')) { + /* Non-wildcard char, we can break here and consider the pattern valid. */ + return false; + } + /* So far, only wildcards in last group of the pattern... */ + only_wildcards = true; + } + /* Only one group in the pattern, so even if its only made of wildcard(s), it is assumed vaid. */ + return false; +} /** * Removes any existing extension on the end of \a path and appends \a ext. * \return false if there was no room. */ -bool BLI_replace_extension(char *path, size_t maxlen, const char *ext) +bool BLI_path_extension_replace(char *path, size_t maxlen, const char *ext) { +#ifdef DEBUG_STRSIZE + memset(path, 0xff, sizeof(*path) * maxlen); +#endif const size_t path_len = strlen(path); const size_t ext_len = strlen(ext); ssize_t a; @@ -1458,8 +1503,11 @@ bool BLI_replace_extension(char *path, size_t maxlen, const char *ext) /** * Strip's trailing '.'s and adds the extension only when needed */ -bool BLI_ensure_extension(char *path, size_t maxlen, const char *ext) +bool BLI_path_extension_ensure(char *path, size_t maxlen, const char *ext) { +#ifdef DEBUG_STRSIZE + memset(path, 0xff, sizeof(*path) * maxlen); +#endif const size_t path_len = strlen(path); const size_t ext_len = strlen(ext); ssize_t a; @@ -1488,6 +1536,9 @@ bool BLI_ensure_extension(char *path, size_t maxlen, const char *ext) bool BLI_ensure_filename(char *filepath, size_t maxlen, const char *filename) { +#ifdef DEBUG_STRSIZE + memset(filepath, 0xff, sizeof(*filepath) * maxlen); +#endif char *c = (char *)BLI_last_slash(filepath); if (!c || ((c - filepath) < maxlen - (strlen(filename) + 1))) { strcpy(c ? &c[1] : filepath, filename); @@ -1504,6 +1555,10 @@ bool BLI_ensure_filename(char *filepath, size_t maxlen, const char *filename) * */ void BLI_split_dirfile(const char *string, char *dir, char *file, const size_t dirlen, const size_t filelen) { +#ifdef DEBUG_STRSIZE + memset(dir, 0xff, sizeof(*dir) * dirlen); + memset(file, 0xff, sizeof(*file) * filelen); +#endif const char *lslash_str = BLI_last_slash(string); const size_t lslash = lslash_str ? (size_t)(lslash_str - string) + 1 : 0; @@ -1515,7 +1570,7 @@ void BLI_split_dirfile(const char *string, char *dir, char *file, const size_t d dir[0] = '\0'; } } - + if (file) { BLI_strncpy(file, string + lslash, filelen); } @@ -1563,6 +1618,9 @@ void BLI_path_append(char *__restrict dst, const size_t maxlen, const char *__re */ void BLI_join_dirfile(char *__restrict dst, const size_t maxlen, const char *__restrict dir, const char *__restrict file) { +#ifdef DEBUG_STRSIZE + memset(dst, 0xff, sizeof(*dst) * maxlen); +#endif size_t dirlen = BLI_strnlen(dir, maxlen); /* args can't match */ @@ -1603,6 +1661,9 @@ void BLI_join_dirfile(char *__restrict dst, const size_t maxlen, const char *__r */ size_t BLI_path_join(char *__restrict dst, const size_t dst_len, const char *path, ...) { +#ifdef DEBUG_STRSIZE + memset(dst, 0xff, sizeof(*dst) * dst_len); +#endif if (UNLIKELY(dst_len == 0)) { return 0; } @@ -1755,137 +1816,6 @@ bool BLI_path_name_at_index(const char *path, const int index, int *r_offset, in } } -/* UNUSED */ -#if 0 -/** - * Produce image export path. - * - * Returns: - * 0 if image filename is empty or if destination path - * matches image path (i.e. both are the same file). - * 2 if source is identical to destination. - * 1 if rebase was successful - * ------------------------------------------------------------- - * Hint: Trailing slash in dest_dir is optional. - * - * Logic: - * - * - if an image is "below" current .blend file directory: - * rebuild the same dir structure in dest_dir - * - * Example: - * src : //textures/foo/bar.png - * dest: [dest_dir]/textures/foo/bar.png. - * - * - if an image is not "below" current .blend file directory, - * disregard it's path and copy it into the destination - * directory. - * - * Example: - * src : //../foo/bar.png becomes - * dest: [dest_dir]/bar.png. - * - * This logic ensures that all image paths are relative and - * that a user gets his images in one place. It'll also provide - * consistent behavior across exporters. - * IMPORTANT NOTE: If base_dir contains an empty string, then - * this function returns wrong results! - * XXX: test on empty base_dir and return an error ? - */ - -/** - * - * \param abs Optional string to return new full path - * \param abs_len Size of *abs string - * \param rel Optional area to return new path relative to parent directory of .blend file - * (only meaningful if item is in a subdirectory thereof) - * \param rel_len Size of *rel area - * \param base_dir Path of .blend file - * \param src_dir Original path of item (any initial "//" will be expanded to - * parent directory of .blend file) - * \param dest_dir New directory into which item will be moved - * \return bli_rebase_state - * - * \note Not actually used anywhere! - */ -int BLI_rebase_path(char *abs, size_t abs_len, - char *rel, size_t rel_len, - const char *base_dir, const char *src_dir, const char *dest_dir) -{ - char path[FILE_MAX]; /* original full path of item */ - char dir[FILE_MAX]; /* directory part of src_dir */ - char base[FILE_MAX]; /* basename part of src_dir */ - char blend_dir[FILE_MAX]; /* directory, where current .blend file resides */ - char dest_path[FILE_MAX]; - char rel_dir[FILE_MAX]; - int len; - - if (abs) - abs[0] = 0; - - if (rel) - rel[0] = 0; - - BLI_split_dir_part(base_dir, blend_dir, sizeof(blend_dir)); - - if (src_dir[0] == '\0') - return BLI_REBASE_NO_SRCDIR; - - BLI_strncpy(path, src_dir, sizeof(path)); - - /* expand "//" in filename and get absolute path */ - BLI_path_abs(path, base_dir); - - /* get the directory part */ - BLI_split_dirfile(path, dir, base, sizeof(dir), sizeof(base)); - - len = strlen(blend_dir); - - rel_dir[0] = 0; - - /* if image is "below" current .blend file directory */ - if (!BLI_path_ncmp(path, blend_dir, len)) { - - if (BLI_path_cmp(dir, blend_dir) == 0) { - /* image is directly in .blend file parent directory => put directly in dest_dir */ - BLI_join_dirfile(dest_path, sizeof(dest_path), dest_dir, base); - } - else { - /* "below" (in subdirectory of .blend file parent directory) => put in same relative directory structure in dest_dir */ - /* rel = image_path_dir - blend_dir */ - BLI_strncpy(rel_dir, dir + len, sizeof(rel_dir)); - /* subdirectories relative to blend_dir */ - BLI_join_dirfile(dest_path, sizeof(dest_path), dest_dir, rel_dir); - /* same subdirectories relative to dest_dir */ - BLI_path_append(dest_path, sizeof(dest_path), base); - /* keeping original item basename */ - } - - } - /* image is out of current directory -- just put straight in dest_dir */ - else { - BLI_join_dirfile(dest_path, sizeof(dest_path), dest_dir, base); - } - - if (abs) - BLI_strncpy(abs, dest_path, abs_len); - - if (rel) { - strncat(rel, rel_dir, rel_len); - strncat(rel, base, rel_len); /* FIXME: could overflow rel area! */ - } - - /* return 2 if (src == dest) */ - if (BLI_path_cmp(path, dest_path) == 0) { - // if (G.debug & G_DEBUG) printf("%s and %s are the same file\n", path, dest_path); - return BLI_REBASE_IDENTITY; - } - - return BLI_REBASE_OK; -} -#endif - - /** * Returns pointer to the leftmost path separator in string. Not actually used anywhere. */ @@ -1893,10 +1823,10 @@ const char *BLI_first_slash(const char *string) { const char * const ffslash = strchr(string, '/'); const char * const fbslash = strchr(string, '\\'); - + if (!ffslash) return fbslash; else if (!fbslash) return ffslash; - + return (ffslash < fbslash) ? ffslash : fbslash; } @@ -1908,9 +1838,9 @@ const char *BLI_last_slash(const char *string) const char * const lfslash = strrchr(string, '/'); const char * const lbslash = strrchr(string, '\\'); - if (!lfslash) return lbslash; + if (!lfslash) return lbslash; else if (!lbslash) return lfslash; - + return (lfslash > lbslash) ? lfslash : lbslash; } diff --git a/source/blender/blenlib/intern/rand.c b/source/blender/blenlib/intern/rand.c index 1a178db1413b..110757ac3c0f 100644 --- a/source/blender/blenlib/intern/rand.c +++ b/source/blender/blenlib/intern/rand.c @@ -312,7 +312,7 @@ void BLI_thread_srandom(int thread, unsigned int seed) { if (thread >= BLENDER_MAX_THREADS) thread = 0; - + BLI_rng_seed(&rng_tab[thread], seed + hash[seed & 255]); seed = BLI_rng_get_uint(&rng_tab[thread]); BLI_rng_seed(&rng_tab[thread], seed + hash[seed & 255]); @@ -338,11 +338,11 @@ RNG_THREAD_ARRAY *BLI_rng_threaded_new(void) { unsigned int i; RNG_THREAD_ARRAY *rngarr = MEM_mallocN(sizeof(RNG_THREAD_ARRAY), "random_array"); - + for (i = 0; i < BLENDER_MAX_THREADS; i++) { BLI_rng_srandom(&rngarr->rng_tab[i], (unsigned int)clock()); } - + return rngarr; } diff --git a/source/blender/blenlib/intern/scanfill.c b/source/blender/blenlib/intern/scanfill.c index 4406a45d4fc3..f1564d132e38 100644 --- a/source/blender/blenlib/intern/scanfill.c +++ b/source/blender/blenlib/intern/scanfill.c @@ -100,7 +100,7 @@ typedef struct ScanFillVertLink { static int vergscdata(const void *a1, const void *a2) { const ScanFillVertLink *x1 = a1, *x2 = a2; - + if (x1->vert->xy[1] < x2->vert->xy[1]) return 1; else if (x1->vert->xy[1] > x2->vert->xy[1]) return -1; else if (x1->vert->xy[0] > x2->vert->xy[0]) return 1; @@ -117,7 +117,7 @@ static int vergpoly(const void *a1, const void *a2) else if (x1->min_xy[0] < x2->min_xy[0]) return -1; else if (x1->min_xy[1] > x2->min_xy[1]) return 1; else if (x1->min_xy[1] < x2->min_xy[1]) return -1; - + return 0; } @@ -126,7 +126,7 @@ static int vergpoly(const void *a1, const void *a2) ScanFillVert *BLI_scanfill_vert_add(ScanFillContext *sf_ctx, const float vec[3]) { ScanFillVert *sf_v; - + sf_v = BLI_memarena_alloc(sf_ctx->arena, sizeof(ScanFillVert)); BLI_addtail(&sf_ctx->fillvertbase, sf_v); @@ -151,7 +151,7 @@ ScanFillEdge *BLI_scanfill_edge_add(ScanFillContext *sf_ctx, ScanFillVert *v1, S sf_ed = BLI_memarena_alloc(sf_ctx->arena, sizeof(ScanFillEdge)); BLI_addtail(&sf_ctx->filledgebase, sf_ed); - + sf_ed->v1 = v1; sf_ed->v2 = v2; @@ -171,7 +171,7 @@ static void addfillface(ScanFillContext *sf_ctx, ScanFillVert *v1, ScanFillVert sf_tri = BLI_memarena_alloc(sf_ctx->arena, sizeof(ScanFillFace)); BLI_addtail(&sf_ctx->fillfacebase, sf_tri); - + sf_tri->v1 = v1; sf_tri->v2 = v2; sf_tri->v3 = v3; @@ -402,7 +402,7 @@ static void testvertexnearedge(ScanFillContext *sf_ctx) if (dist < SF_EPSILON_SQ) { /* new edge */ ed1 = BLI_scanfill_edge_add(sf_ctx, eed->v1, eve); - + /* printf("fill: vertex near edge %x\n", eve); */ ed1->poly_nr = eed->poly_nr; eed->v1 = eve; @@ -435,7 +435,7 @@ static void splitlist(ScanFillContext *sf_ctx, ListBase *tempve, ListBase *tempe } } - + for (eed = temped->first; eed; eed = eed_next) { eed_next = eed->next; if (eed->poly_nr == nr) { @@ -592,7 +592,7 @@ static unsigned int scanfill(ScanFillContext *sf_ctx, PolyFill *pf, const int fl while (sc->edge_first) { /* for as long there are edges */ ed1 = sc->edge_first; ed2 = ed1->next; - + /* commented out... the ESC here delivers corrupted memory (and doesnt work during grab) */ /* if (callLocalInterruptCallBack()) break; */ if (totface >= maxface) { @@ -614,14 +614,14 @@ static unsigned int scanfill(ScanFillContext *sf_ctx, PolyFill *pf, const int fl float angle_best_cos = -1.0f; float miny; bool firsttime = false; - + v1 = ed1->v2; v2 = ed1->v1; v3 = ed2->v2; - + /* this happens with a serial of overlapping edges */ if (v1 == v2 || v2 == v3) break; - + /* printf("test verts %d %d %d\n", v1->tmp.u, v2->tmp.u, v3->tmp.u); */ miny = min_ff(v1->xy[1], v3->xy[1]); sc1 = sc + 1; @@ -633,10 +633,10 @@ static unsigned int scanfill(ScanFillContext *sf_ctx, PolyFill *pf, const int fl if (testedgeside(v2->xy, v3->xy, sc1->vert->xy)) { if (testedgeside(v3->xy, v1->xy, sc1->vert->xy)) { /* point is in triangle */ - + /* because multiple points can be inside triangle (concave holes) */ /* we continue searching and pick the one with sharpest corner */ - + if (best_sc == NULL) { /* even without holes we need to keep checking [#35861] */ best_sc = sc1; @@ -659,7 +659,7 @@ static unsigned int scanfill(ScanFillContext *sf_ctx, PolyFill *pf, const int fl } } } - + if (best_sc) { /* make new edge, and start over */ /* printf("add new edge %d %d and start again\n", v2->tmp.u, best_sc->vert->tmp.u); */ @@ -697,10 +697,10 @@ static unsigned int scanfill(ScanFillContext *sf_ctx, PolyFill *pf, const int fl ed3->f = SF_EDGE_INTERNAL; ed3->v1->edge_tot++; ed3->v2->edge_tot++; - + /* printf("add new edge %x %x\n", v1, v3); */ sc1 = addedgetoscanlist(scdata, ed3, verts); - + if (sc1) { /* ed3 already exists: remove if a boundary */ /* printf("Edge exists\n"); */ ed3->v1->edge_tot--; @@ -1033,7 +1033,7 @@ unsigned int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, const int flag, const * - eve->poly_nr :polynumber * - eve->edge_tot :amount of edges connected to vertex * - eve->tmp.v :store! original vertex number - * + * * - eed->f :1 = boundary edge (optionally set by caller) * - eed->poly_nr :poly number */ @@ -1069,10 +1069,10 @@ unsigned int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, const int flag, const } /* STEP 4: FIND HOLES OR BOUNDS, JOIN THEM - * ( bounds just to divide it in pieces for optimization, + * ( bounds just to divide it in pieces for optimization, * the edgefill itself has good auto-hole detection) * WATCH IT: ONLY WORKS WITH SORTED POLYS!!! */ - + if ((flag & BLI_SCANFILL_CALC_HOLES) && (poly > 1)) { unsigned short *polycache, *pc; @@ -1092,7 +1092,7 @@ unsigned int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, const int flag, const pf = pflist; for (a = 0; a < poly; a++, pf++) { for (c = (unsigned short)(a + 1); c < poly; c++) { - + /* if 'a' inside 'c': join (bbox too) * Careful: 'a' can also be inside another poly. */ @@ -1102,7 +1102,7 @@ unsigned int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, const int flag, const } /* only for optimize! */ /* else if (pf->max_xy[0] < (pflist+c)->min[cox]) break; */ - + } while (pc != polycache) { pc--; diff --git a/source/blender/blenlib/intern/string.c b/source/blender/blenlib/intern/string.c index 1b3af142b33e..c1696a912bac 100644 --- a/source/blender/blenlib/intern/string.c +++ b/source/blender/blenlib/intern/string.c @@ -63,7 +63,7 @@ char *BLI_strdupn(const char *str, const size_t len) char *n = MEM_mallocN(len + 1, "strdup"); memcpy(n, str, len); n[len] = '\0'; - + return n; } @@ -91,7 +91,7 @@ char *BLI_strdupcat(const char *__restrict str1, const char *__restrict str2) const size_t str1_len = strlen(str1); const size_t str2_len = strlen(str2) + 1; char *str, *s; - + str = MEM_mallocN(str1_len + str2_len, "strdupcat"); s = str; @@ -425,55 +425,55 @@ char *BLI_str_replaceN(const char *__restrict str, const char *__restrict substr BLI_assert(substr_old[0] != '\0'); - /* while we can still find a match for the old substring that we're searching for, + /* while we can still find a match for the old substring that we're searching for, * keep dicing and replacing */ while ((match = strstr(str, substr_old))) { /* the assembly buffer only gets created when we actually need to rebuild the string */ if (ds == NULL) ds = BLI_dynstr_new(); - - /* if the match position does not match the current position in the string, + + /* if the match position does not match the current position in the string, * copy the text up to this position and advance the current position in the string */ if (str != match) { /* add the segment of the string from str to match to the buffer, then restore the value at match */ BLI_dynstr_nappend(ds, str, (match - str)); - + /* now our current position should be set on the start of the match */ str = match; } - + /* add the replacement text to the accumulation buffer */ BLI_dynstr_append(ds, substr_new); - + /* advance the current position of the string up to the end of the replaced segment */ str += len_old; } - + /* finish off and return a new string that has had all occurrences of */ if (ds) { char *str_new; - - /* add what's left of the string to the assembly buffer + + /* add what's left of the string to the assembly buffer * - we've been adjusting str to point at the end of the replaced segments */ BLI_dynstr_append(ds, str); - + /* convert to new c-string (MEM_malloc'd), and free the buffer */ str_new = BLI_dynstr_get_cstring(ds); BLI_dynstr_free(ds); - + return str_new; } else { - /* just create a new copy of the entire string - we avoid going through the assembly buffer + /* just create a new copy of the entire string - we avoid going through the assembly buffer * for what should be a bit more efficiency... */ return BLI_strdup(str); } -} +} /** * In-place replace every \a src to \a dst in \a str. @@ -497,7 +497,7 @@ void BLI_str_replace_char(char *str, char src, char dst) * * \retval True if the strings are equal, false otherwise. */ -int BLI_strcaseeq(const char *a, const char *b) +int BLI_strcaseeq(const char *a, const char *b) { return (BLI_strcasecmp(a, b) == 0); } @@ -509,7 +509,7 @@ char *BLI_strcasestr(const char *s, const char *find) { register char c, sc; register size_t len; - + if ((c = *find++) != 0) { c = tolower(c); len = strlen(find); @@ -654,16 +654,16 @@ int BLI_natstrcmp(const char *s1, const char *s2) int tiebreaker = 0; /* if both chars are numeric, to a left_number_strcmp(). - * then increase string deltas as long they are + * then increase string deltas as long they are * numeric, else do a tolower and char compare */ while (1) { c1 = tolower(s1[d1]); c2 = tolower(s2[d2]); - + if (isdigit(c1) && isdigit(c2)) { int numcompare = left_number_strcmp(s1 + d1, s2 + d2, &tiebreaker); - + if (numcompare != 0) return numcompare; @@ -673,11 +673,11 @@ int BLI_natstrcmp(const char *s1, const char *s2) d2++; while (isdigit(s2[d2])) d2++; - + c1 = tolower(s1[d1]); c2 = tolower(s2[d2]); } - + /* first check for '.' so "foo.bar" comes before "foo 1.bar" */ if (c1 == '.' && c2 != '.') return -1; @@ -698,7 +698,7 @@ int BLI_natstrcmp(const char *s1, const char *s2) if (tiebreaker) return tiebreaker; - + /* we might still have a different string because of lower/upper case, in * that case fall back to regular string comparison */ return strcmp(s1, s2); @@ -851,7 +851,7 @@ int BLI_str_index_in_array(const char *__restrict str, const char **__restrict s bool BLI_strn_endswith(const char *__restrict str, const char *__restrict end, size_t slength) { size_t elength = strlen(end); - + if (elength < slength) { const char *iter = &str[slength - elength]; while (*iter) { diff --git a/source/blender/blenlib/intern/string_utils.c b/source/blender/blenlib/intern/string_utils.c index 197169ab3812..de24fc4d1f56 100644 --- a/source/blender/blenlib/intern/string_utils.c +++ b/source/blender/blenlib/intern/string_utils.c @@ -404,7 +404,7 @@ char *BLI_string_join_arrayN( for (uint i = 0; i < strings_len; i++) { total_len += strlen(strings[i]); } - char *result = MEM_mallocN(sizeof(char) * total_len, __func__); + char *result = MEM_mallocN(sizeof(char) * total_len, __func__); char *c = result; for (uint i = 0; i < strings_len; i++) { c += BLI_strcpy_rlen(c, strings[i]); @@ -426,7 +426,7 @@ char *BLI_string_join_array_by_sep_charN( total_len = 1; } - char *result = MEM_mallocN(sizeof(char) * total_len, __func__); + char *result = MEM_mallocN(sizeof(char) * total_len, __func__); char *c = result; if (strings_len != 0) { for (uint i = 0; i < strings_len; i++) { @@ -455,7 +455,7 @@ char *BLI_string_join_array_by_sep_char_with_tableN( total_len = 1; } - char *result = MEM_mallocN(sizeof(char) * total_len, __func__); + char *result = MEM_mallocN(sizeof(char) * total_len, __func__); char *c = result; if (strings_len != 0) { for (uint i = 0; i < strings_len; i++) { diff --git a/source/blender/blenlib/intern/threads.c b/source/blender/blenlib/intern/threads.c index dd79f3f5e5ef..862ce3911093 100644 --- a/source/blender/blenlib/intern/threads.c +++ b/source/blender/blenlib/intern/threads.c @@ -69,7 +69,7 @@ static void *thread_tls_data; /* We're using one global task scheduler for all kind of tasks. */ static TaskScheduler *task_scheduler = NULL; -/* ********** basic thread control API ************ +/* ********** basic thread control API ************ * * Many thread cases have an X amount of jobs, and only an Y amount of * threads are useful (typically amount of cpus) @@ -189,10 +189,10 @@ void BLI_threadpool_init(ListBase *threadbase, void *(*do_thread)(void *), int t if (threadbase != NULL && tot > 0) { BLI_listbase_clear(threadbase); - + if (tot > RE_MAX_THREAD) tot = RE_MAX_THREAD; else if (tot < 1) tot = 1; - + for (a = 0; a < tot; a++) { ThreadSlot *tslot = MEM_callocN(sizeof(ThreadSlot), "threadslot"); BLI_addtail(threadbase, tslot); @@ -219,7 +219,7 @@ int BLI_available_threads(ListBase *threadbase) { ThreadSlot *tslot; int counter = 0; - + for (tslot = threadbase->first; tslot; tslot = tslot->next) { if (tslot->avail) counter++; @@ -232,7 +232,7 @@ int BLI_threadpool_available_thread_index(ListBase *threadbase) { ThreadSlot *tslot; int counter = 0; - + for (tslot = threadbase->first; tslot; tslot = tslot->next, counter++) { if (tslot->avail) return counter; @@ -261,7 +261,7 @@ int BLI_thread_is_main(void) void BLI_threadpool_insert(ListBase *threadbase, void *callerdata) { ThreadSlot *tslot; - + for (tslot = threadbase->first; tslot; tslot = tslot->next) { if (tslot->avail) { tslot->avail = 0; @@ -276,7 +276,7 @@ void BLI_threadpool_insert(ListBase *threadbase, void *callerdata) void BLI_threadpool_remove(ListBase *threadbase, void *callerdata) { ThreadSlot *tslot; - + for (tslot = threadbase->first; tslot; tslot = tslot->next) { if (tslot->callerdata == callerdata) { pthread_join(tslot->pthread, NULL); @@ -290,7 +290,7 @@ void BLI_threadpool_remove_index(ListBase *threadbase, int index) { ThreadSlot *tslot; int counter = 0; - + for (tslot = threadbase->first; tslot; tslot = tslot->next, counter++) { if (counter == index && tslot->avail == 0) { pthread_join(tslot->pthread, NULL); @@ -304,7 +304,7 @@ void BLI_threadpool_remove_index(ListBase *threadbase, int index) void BLI_threadpool_clear(ListBase *threadbase) { ThreadSlot *tslot; - + for (tslot = threadbase->first; tslot; tslot = tslot->next) { if (tslot->avail == 0) { pthread_join(tslot->pthread, NULL); @@ -317,9 +317,9 @@ void BLI_threadpool_clear(ListBase *threadbase) void BLI_threadpool_end(ListBase *threadbase) { ThreadSlot *tslot; - + /* only needed if there's actually some stuff to end - * this way we don't end up decrementing thread_levels on an empty threadbase + * this way we don't end up decrementing thread_levels on an empty threadbase * */ if (threadbase && (BLI_listbase_is_empty(threadbase) == false)) { for (tslot = threadbase->first; tslot; tslot = tslot->next) { @@ -355,7 +355,7 @@ int BLI_system_thread_count(void) SYSTEM_INFO info; GetSystemInfo(&info); t = (int) info.dwNumberOfProcessors; -#else +#else # ifdef __APPLE__ int mib[2]; size_t len; @@ -694,11 +694,11 @@ void *BLI_thread_queue_pop(ThreadQueue *queue) pthread_mutex_lock(&queue->mutex); while (BLI_gsqueue_is_empty(queue->queue) && !queue->nowait) pthread_cond_wait(&queue->push_cond, &queue->mutex); - + /* if we have something, pop it */ if (!BLI_gsqueue_is_empty(queue->queue)) { BLI_gsqueue_pop(queue->queue, &work); - + if (BLI_gsqueue_is_empty(queue->queue)) pthread_cond_broadcast(&queue->finish_cond); } @@ -764,11 +764,11 @@ void *BLI_thread_queue_pop_timeout(ThreadQueue *queue, int ms) /* if we have something, pop it */ if (!BLI_gsqueue_is_empty(queue->queue)) { BLI_gsqueue_pop(queue->queue, &work); - + if (BLI_gsqueue_is_empty(queue->queue)) pthread_cond_broadcast(&queue->finish_cond); } - + pthread_mutex_unlock(&queue->mutex); return work; @@ -840,4 +840,3 @@ void BLI_threaded_malloc_end(void) MEM_set_lock_callback(NULL, NULL); } } - diff --git a/source/blender/blenlib/intern/time.c b/source/blender/blenlib/intern/time.c index 3cf3221bd08c..a2665f96b292 100644 --- a/source/blender/blenlib/intern/time.c +++ b/source/blender/blenlib/intern/time.c @@ -39,7 +39,7 @@ #define WIN32_LEAN_AND_MEAN #include -double PIL_check_seconds_timer(void) +double PIL_check_seconds_timer(void) { static int hasperfcounter = -1; /* (-1 == unknown) */ static double perffreq; @@ -89,7 +89,7 @@ void PIL_sleep_ms(int ms) #include #include -double PIL_check_seconds_timer(void) +double PIL_check_seconds_timer(void) { struct timeval tv; struct timezone tz; @@ -115,7 +115,7 @@ void PIL_sleep_ms(int ms) sleep(ms / 1000); ms = (ms % 1000); } - + usleep(ms * 1000); } diff --git a/source/blender/blenlib/intern/voxel.c b/source/blender/blenlib/intern/voxel.c index 093333769d63..37b7ca37ba59 100644 --- a/source/blender/blenlib/intern/voxel.c +++ b/source/blender/blenlib/intern/voxel.c @@ -48,11 +48,11 @@ BLI_INLINE float D(float *data, const int res[3], int x, int y, int z) float BLI_voxel_sample_nearest(float *data, const int res[3], const float co[3]) { int xi, yi, zi; - + xi = (int)(co[0] * (float)res[0]); yi = (int)(co[1] * (float)res[1]); zi = (int)(co[2] * (float)res[2]); - + return D(data, res, xi, yi, zi); } @@ -76,13 +76,13 @@ BLI_INLINE int64_t _clamp(int a, int b, int c) float BLI_voxel_sample_trilinear(float *data, const int res[3], const float co[3]) { if (data) { - + const float xf = co[0] * (float)res[0] - 0.5f; const float yf = co[1] * (float)res[1] - 0.5f; const float zf = co[2] * (float)res[2] - 0.5f; - + const int x = FLOORI(xf), y = FLOORI(yf), z = FLOORI(zf); - + const int64_t xc[2] = { _clamp(x, 0, res[0] - 1), _clamp(x + 1, 0, res[0] - 1), @@ -95,20 +95,20 @@ float BLI_voxel_sample_trilinear(float *data, const int res[3], const float co[3 _clamp(z, 0, res[2] - 1) * res[0] * res[1], _clamp(z + 1, 0, res[2] - 1) * res[0] * res[1], }; - + const float dx = xf - (float)x; const float dy = yf - (float)y; const float dz = zf - (float)z; - + const float u[2] = {1.f - dx, dx}; const float v[2] = {1.f - dy, dy}; const float w[2] = {1.f - dz, dz}; - + return w[0] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[0]] + u[1] * data[xc[1] + yc[0] + zc[0]] ) + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[0]] + u[1] * data[xc[1] + yc[1] + zc[0]] ) ) + w[1] * ( v[0] * ( u[0] * data[xc[0] + yc[0] + zc[1]] + u[1] * data[xc[1] + yc[0] + zc[1]] ) + v[1] * ( u[0] * data[xc[0] + yc[1] + zc[1]] + u[1] * data[xc[1] + yc[1] + zc[1]] ) ); - + } return 0.f; } diff --git a/source/blender/blenlib/intern/winstuff.c b/source/blender/blenlib/intern/winstuff.c index d68344283766..bf0b28b5cc27 100644 --- a/source/blender/blenlib/intern/winstuff.c +++ b/source/blender/blenlib/intern/winstuff.c @@ -61,9 +61,9 @@ int BLI_getInstallationDir(char *str) BLI_split_dir_part(str, dir, sizeof(dir)); /* shouldn't be relative */ a = strlen(dir); if (dir[a - 1] == '\\') dir[a - 1] = 0; - + strcpy(str, dir); - + return 1; } @@ -155,7 +155,7 @@ void RegisterBlendExtension(void) } if (lresult != ERROR_SUCCESS) RegisterBlendExtension_Fail(root); - + BLI_getInstallationDir(InstallDir); GetSystemDirectory(SysDir, FILE_MAXDIR); #ifdef _WIN64 @@ -182,8 +182,8 @@ void RegisterBlendExtension(void) void get_default_root(char *root) { char str[MAX_PATH + 1]; - - /* the default drive to resolve a directory without a specified drive + + /* the default drive to resolve a directory without a specified drive * should be the Windows installation drive, since this was what the OS * assumes. */ if (GetWindowsDirectory(str, MAX_PATH + 1)) { @@ -193,7 +193,7 @@ void get_default_root(char *root) root[3] = '\0'; } else { - /* if GetWindowsDirectory fails, something has probably gone wrong, + /* if GetWindowsDirectory fails, something has probably gone wrong, * we are trying the blender install dir though */ if (GetModuleFileName(NULL, str, MAX_PATH + 1)) { printf("Error! Could not get the Windows Directory - " diff --git a/source/blender/blenlib/intern/winstuff_dir.c b/source/blender/blenlib/intern/winstuff_dir.c index bde0734a7403..4e2a6976ce4c 100644 --- a/source/blender/blenlib/intern/winstuff_dir.c +++ b/source/blender/blenlib/intern/winstuff_dir.c @@ -119,16 +119,16 @@ struct dirent *readdir(DIR *dp) MEM_freeN(dp->direntry.d_name); dp->direntry.d_name = NULL; } - + if (dp->handle == INVALID_HANDLE_VALUE) { wchar_t *path_16 = alloc_utf16_from_8(dp->path, 0); dp->handle = FindFirstFileW(path_16, &(dp->data)); free(path_16); if (dp->handle == INVALID_HANDLE_VALUE) return NULL; - + dp->direntry.d_name = BLI_alloc_utf_8_from_16(dp->data.cFileName, 0); - + return &dp->direntry; } else if (FindNextFileW(dp->handle, &(dp->data))) { @@ -147,7 +147,7 @@ int closedir(DIR *dp) if (dp->handle != INVALID_HANDLE_VALUE) FindClose(dp->handle); MEM_freeN(dp); - + return 0; } diff --git a/source/blender/blenloader/BLO_readfile.h b/source/blender/blenloader/BLO_readfile.h index 0b4ff13c7bd7..11f34732cfc7 100644 --- a/source/blender/blenloader/BLO_readfile.h +++ b/source/blender/blenloader/BLO_readfile.h @@ -64,10 +64,10 @@ typedef struct BlendFileData { int fileflags; int globalf; char filename[1024]; /* 1024 = FILE_MAX */ - + struct bScreen *curscreen; struct Scene *curscene; - + eBlenFileType type; } BlendFileData; @@ -150,7 +150,7 @@ struct BlendThumbnail *BLO_thumbnail_from_file(const char *filepath); struct Main *BLO_main_from_memfile(struct MemFile *memfile, struct Main *bmain, struct Scene **r_scene); #ifdef __cplusplus -} +} #endif #endif /* __BLO_READFILE_H__ */ diff --git a/source/blender/blenloader/BLO_runtime.h b/source/blender/blenloader/BLO_runtime.h index 2c3947c9ddac..09f25bdca534 100644 --- a/source/blender/blenloader/BLO_runtime.h +++ b/source/blender/blenloader/BLO_runtime.h @@ -51,4 +51,3 @@ bool BLO_main_validate_libraries(struct Main *bmain, struct ReportList *reports) #endif #endif /* __BLO_RUNTIME_H__ */ - diff --git a/source/blender/blenloader/BLO_undofile.h b/source/blender/blenloader/BLO_undofile.h index c407ea31b9b2..59df361c7c18 100644 --- a/source/blender/blenloader/BLO_undofile.h +++ b/source/blender/blenloader/BLO_undofile.h @@ -69,4 +69,3 @@ extern struct Main *BLO_memfile_main_get(struct MemFile *memfile, struct Main *b extern bool BLO_memfile_write_file(struct MemFile *memfile, const char *filename); #endif /* __BLO_UNDOFILE_H__ */ - diff --git a/source/blender/blenloader/BLO_writefile.h b/source/blender/blenloader/BLO_writefile.h index af3bc2dbdcd8..f6d0be6f5f02 100644 --- a/source/blender/blenloader/BLO_writefile.h +++ b/source/blender/blenloader/BLO_writefile.h @@ -45,4 +45,3 @@ extern bool BLO_write_file_mem( struct Main *mainvar, struct MemFile *compare, struct MemFile *current, int write_flags); #endif - diff --git a/source/blender/blenloader/CMakeLists.txt b/source/blender/blenloader/CMakeLists.txt index bada1175cca1..bb7db27578ff 100644 --- a/source/blender/blenloader/CMakeLists.txt +++ b/source/blender/blenloader/CMakeLists.txt @@ -23,7 +23,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . ../blenfont ../blenkernel diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c index d0d05254bc94..1bbc14e4a42d 100644 --- a/source/blender/blenloader/intern/readblenentry.c +++ b/source/blender/blenloader/intern/readblenentry.c @@ -72,10 +72,10 @@ #endif /* local prototypes --------------------- */ -void BLO_blendhandle_print_sizes(BlendHandle *, void *); +void BLO_blendhandle_print_sizes(BlendHandle *, void *); /* Access routines used by filesel. */ - + /** * Open a blendhandle from a file path. * @@ -108,7 +108,7 @@ BlendHandle *BLO_blendhandle_from_memory(const void *mem, int memsize) return bh; } -void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp) +void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp) { FileData *fd = (FileData *) bh; BHead *bhead; @@ -121,7 +121,7 @@ void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp) const short *sp = fd->filesdna->structs[bhead->SDNAnr]; const char *name = fd->filesdna->types[sp[0]]; char buf[4]; - + buf[0] = (bhead->code >> 24) & 0xFF; buf[1] = (bhead->code >> 16) & 0xFF; buf[2] = (bhead->code >> 8) & 0xFF; @@ -131,7 +131,7 @@ void BLO_blendhandle_print_sizes(BlendHandle *bh, void *fp) buf[1] = buf[1] ? buf[1] : ' '; buf[2] = buf[2] ? buf[2] : ' '; buf[3] = buf[3] ? buf[3] : ' '; - + fprintf(fp, "['%.4s', '%s', %d, %ld ],\n", buf, name, bhead->nr, (long int)(bhead->len + sizeof(BHead))); } } @@ -229,7 +229,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to new_prv->rect[0] = NULL; new_prv->w[0] = new_prv->h[0] = 0; } - + if (prv->rect[1] && prv->w[1] && prv->h[1]) { unsigned int *rect = NULL; size_t len = new_prv->w[1] * new_prv->h[1] * sizeof(unsigned int); @@ -259,7 +259,7 @@ LinkNode *BLO_blendhandle_get_previews(BlendHandle *bh, int ofblocktype, int *to new_prv = NULL; prv = NULL; } - + } *tot_prev = tot; @@ -278,7 +278,7 @@ LinkNode *BLO_blendhandle_get_linkable_groups(BlendHandle *bh) GSet *gathered = BLI_gset_ptr_new("linkable_groups gh"); LinkNode *names = NULL; BHead *bhead; - + for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) { if (bhead->code == ENDB) { break; @@ -286,18 +286,18 @@ LinkNode *BLO_blendhandle_get_linkable_groups(BlendHandle *bh) else if (BKE_idcode_is_valid(bhead->code)) { if (BKE_idcode_is_linkable(bhead->code)) { const char *str = BKE_idcode_to_name(bhead->code); - + if (BLI_gset_add(gathered, (void *)str)) { BLI_linklist_prepend(&names, strdup(str)); } } } } - + BLI_gset_free(gathered, NULL); - + return names; -} +} /** * Close and free a blendhandle. The handle becomes invalid after this call. @@ -307,7 +307,7 @@ LinkNode *BLO_blendhandle_get_linkable_groups(BlendHandle *bh) void BLO_blendhandle_close(BlendHandle *bh) { FileData *fd = (FileData *) bh; - + blo_freefiledata(fd); } @@ -327,7 +327,7 @@ BlendFileData *BLO_read_from_file( { BlendFileData *bfd = NULL; FileData *fd; - + fd = blo_openblenderfile(filepath, reports); if (fd) { fd->reports = reports; @@ -354,7 +354,7 @@ BlendFileData *BLO_read_from_memory( { BlendFileData *bfd = NULL; FileData *fd; - + fd = blo_openblendermemory(mem, memsize, reports); if (fd) { #ifdef WITH_GAMEENGINE_BPPLAYER @@ -386,13 +386,13 @@ BlendFileData *BLO_read_from_memfile( BlendFileData *bfd = NULL; FileData *fd; ListBase old_mainlist; - + fd = blo_openblendermemfile(memfile, reports); if (fd) { fd->reports = reports; fd->skip_flags = skip_flags; BLI_strncpy(fd->relabase, filename, sizeof(fd->relabase)); - + /* clear ob->proxy_from pointers in old main */ blo_clear_proxy_pointers_from_lib(oldmain); @@ -400,26 +400,26 @@ BlendFileData *BLO_read_from_memfile( blo_split_main(&old_mainlist, oldmain); /* add the library pointers in oldmap lookup */ blo_add_library_pointer_map(&old_mainlist, fd); - + /* makes lookup of existing images in old main */ blo_make_image_pointer_map(fd, oldmain); - + /* makes lookup of existing video clips in old main */ blo_make_movieclip_pointer_map(fd, oldmain); /* make lookups of existing sound data in old main */ blo_make_sound_pointer_map(fd, oldmain); - + /* removed packed data from this trick - it's internal data that needs saves */ - + bfd = blo_read_file_internal(fd, filename); - + /* ensures relinked images are not freed */ blo_end_image_pointer_map(fd, oldmain); - + /* ensures relinked movie clips are not freed */ blo_end_movieclip_pointer_map(fd, oldmain); - + /* ensures relinked sounds are not freed */ blo_end_sound_pointer_map(fd, oldmain); @@ -478,11 +478,10 @@ void BLO_blendfiledata_free(BlendFileData *bfd) if (bfd->main) { BKE_main_free(bfd->main); } - + if (bfd->user) { MEM_freeN(bfd->user); } MEM_freeN(bfd); } - diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c index 7070e71a6d27..7af196251d1f 100644 --- a/source/blender/blenloader/intern/readfile.c +++ b/source/blender/blenloader/intern/readfile.c @@ -139,6 +139,7 @@ #include "BKE_multires.h" #include "BKE_node.h" // for tree type defines #include "BKE_object.h" +#include "BKE_ocean.h" #include "BKE_paint.h" #include "BKE_particle.h" #include "BKE_pointcache.h" @@ -267,17 +268,17 @@ static BHead *find_bhead_from_idname(FileData *fd, const char *idname); void blo_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...) { char fixed_buf[1024]; /* should be long enough */ - + va_list args; - + va_start(args, format); vsnprintf(fixed_buf, sizeof(fixed_buf), format, args); va_end(args); - + fixed_buf[sizeof(fixed_buf) - 1] = '\0'; - + BKE_report(reports, type, fixed_buf); - + if (G.background == 0) { printf("%s: %s\n", BKE_report_type_str(type), fixed_buf); } @@ -289,27 +290,27 @@ static const char *library_parent_filepath(Library *lib) return lib->parent ? lib->parent->filepath : ""; } -static OldNewMap *oldnewmap_new(void) +static OldNewMap *oldnewmap_new(void) { OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap"); - + onm->entriessize = 1024; onm->entries = MEM_malloc_arrayN(onm->entriessize, sizeof(*onm->entries), "OldNewMap.entries"); - + return onm; } static int verg_oldnewmap(const void *v1, const void *v2) { const struct OldNew *x1=v1, *x2=v2; - + if (x1->old > x2->old) return 1; else if (x1->old < x2->old) return -1; return 0; } -static void oldnewmap_sort(FileData *fd) +static void oldnewmap_sort(FileData *fd) { BLI_assert(fd->libmap->sorted == false); qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap); @@ -320,9 +321,9 @@ static void oldnewmap_sort(FileData *fd) static void oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr) { OldNew *entry; - + if (oldaddr==NULL || newaddr==NULL) return; - + if (UNLIKELY(onm->nentries == onm->entriessize)) { onm->entriessize *= 2; onm->entries = MEM_reallocN(onm->entries, sizeof(*onm->entries) * onm->entriessize); @@ -392,19 +393,19 @@ static int oldnewmap_lookup_entry_full(const OldNewMap *onm, const void *addr, i static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool increase_users) { int i; - + if (addr == NULL) return NULL; - + if (onm->lasthit < onm->nentries-1) { OldNew *entry = &onm->entries[++onm->lasthit]; - + if (entry->old == addr) { if (increase_users) entry->nr++; return entry->newp; } } - + i = oldnewmap_lookup_entry_full(onm, addr, onm->lasthit); if (i != -1) { OldNew *entry = &onm->entries[i]; @@ -414,7 +415,7 @@ static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool inc entry->nr++; return entry->newp; } - + return NULL; } @@ -453,7 +454,7 @@ static void *oldnewmap_liblookup(OldNewMap *onm, const void *addr, const void *l return NULL; } -static void oldnewmap_free_unused(OldNewMap *onm) +static void oldnewmap_free_unused(OldNewMap *onm) { int i; @@ -466,13 +467,13 @@ static void oldnewmap_free_unused(OldNewMap *onm) } } -static void oldnewmap_clear(OldNewMap *onm) +static void oldnewmap_clear(OldNewMap *onm) { onm->nentries = 0; onm->lasthit = 0; } -static void oldnewmap_free(OldNewMap *onm) +static void oldnewmap_free(OldNewMap *onm) { MEM_freeN(onm->entries); MEM_freeN(onm); @@ -488,7 +489,7 @@ static void add_main_to_main(Main *mainvar, Main *from) { ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY]; int a; - + set_listbasepointers(mainvar, lbarray); a = set_listbasepointers(from, fromarray); while (a--) { @@ -499,7 +500,7 @@ static void add_main_to_main(Main *mainvar, Main *from) void blo_join_main(ListBase *mainlist) { Main *tojoin, *mainl; - + mainl = mainlist->first; while ((tojoin = mainl->next)) { add_main_to_main(mainl, tojoin); @@ -535,10 +536,10 @@ void blo_split_main(ListBase *mainlist, Main *main) { mainlist->first = mainlist->last = main; main->next = NULL; - + if (BLI_listbase_is_empty(&main->library)) return; - + /* (Library.temp_index -> Main), lookup table */ const unsigned int lib_main_array_len = BLI_listbase_count(&main->library); Main **lib_main_array = MEM_malloc_arrayN(lib_main_array_len, sizeof(*lib_main_array), __func__); @@ -553,7 +554,7 @@ void blo_split_main(ListBase *mainlist, Main *main) lib->temp_index = i; lib_main_array[i] = libmain; } - + ListBase *lbarray[MAX_LIBARRAY]; i = set_listbasepointers(main, lbarray); while (i--) { @@ -570,7 +571,7 @@ void blo_split_main(ListBase *mainlist, Main *main) static void read_file_version(FileData *fd, Main *main) { BHead *bhead; - + for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) { if (bhead->code == GLOB) { FileGlobal *fg= read_struct(fd, bhead, "Global"); @@ -635,37 +636,37 @@ static Main *blo_find_main(FileData *fd, const char *filepath, const char *relab Main *m; Library *lib; char name1[FILE_MAX]; - + BLI_strncpy(name1, filepath, sizeof(name1)); BLI_cleanup_path(relabase, name1); - + // printf("blo_find_main: relabase %s\n", relabase); // printf("blo_find_main: original in %s\n", filepath); // printf("blo_find_main: converted to %s\n", name1); - + for (m = mainlist->first; m; m = m->next) { const char *libname = (m->curlib) ? m->curlib->filepath : m->name; - + if (BLI_path_cmp(name1, libname) == 0) { if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname); return m; } } - + m = BKE_main_new(); BLI_addtail(mainlist, m); - + /* Add library datablock itself to 'main' Main, since libraries are **never** linked data. * Fixes bug where you could end with all ID_LI datablocks having the same name... */ lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib", 0); lib->id.us = ID_FAKE_USERS(lib); /* Important, consistency with main ID reading code from read_libblock(). */ BLI_strncpy(lib->name, filepath, sizeof(lib->name)); BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath)); - + m->curlib = lib; - + read_file_version(fd, m); - + if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath); return m; } @@ -677,7 +678,7 @@ static void switch_endian_bh4(BHead4 *bhead) { /* the ID_.. codes */ if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16; - + if (bhead->code != ENDB) { BLI_endian_switch_int32(&bhead->len); BLI_endian_switch_int32(&bhead->SDNAnr); @@ -689,7 +690,7 @@ static void switch_endian_bh8(BHead8 *bhead) { /* the ID_.. codes */ if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16; - + if (bhead->code != ENDB) { BLI_endian_switch_int32(&bhead->len); BLI_endian_switch_int32(&bhead->SDNAnr); @@ -712,12 +713,12 @@ static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap) if (do_endian_swap) { BLI_endian_switch_int64(&bhead8->old); } - + /* this patch is to avoid a long long being read from not-eight aligned positions * is necessary on any modern 64bit architecture) */ memcpy(&old, &bhead8->old, 8); bhead4->old = (int) (old >> 3); - + bhead4->SDNAnr = bhead8->SDNAnr; bhead4->nr = bhead8->nr; } @@ -726,10 +727,10 @@ static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap) static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4) { BHead8 *bhead8 = (BHead8 *) bhead; - + bhead8->code = bhead4->code; bhead8->len = bhead4->len; - + if (bhead8->code != ENDB) { bhead8->old = bhead4->old; bhead8->SDNAnr = bhead4->SDNAnr; @@ -741,7 +742,7 @@ static BHeadN *get_bhead(FileData *fd) { BHeadN *new_bhead = NULL; int readsize; - + if (fd) { if (!fd->eof) { /* initializing to zero isn't strictly needed but shuts valgrind up @@ -749,7 +750,7 @@ static BHeadN *get_bhead(FileData *fd) BHead8 bhead8 = {0}; BHead4 bhead4 = {0}; BHead bhead = {0}; - + /* First read the bhead structure. * Depending on the platform the file was written on this can * be a big or little endian BHead4 or BHead8 structure. @@ -760,12 +761,12 @@ static BHeadN *get_bhead(FileData *fd) if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) { bhead4.code = DATA; readsize = fd->read(fd, &bhead4, sizeof(bhead4)); - + if (readsize == sizeof(bhead4) || bhead4.code == ENDB) { if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { switch_endian_bh4(&bhead4); } - + if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) { bh8_from_bh4(&bhead, &bhead4); } @@ -783,12 +784,12 @@ static BHeadN *get_bhead(FileData *fd) else { bhead8.code = DATA; readsize = fd->read(fd, &bhead8, sizeof(bhead8)); - + if (readsize == sizeof(bhead8) || bhead8.code == ENDB) { if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { switch_endian_bh8(&bhead8); } - + if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) { bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN)); } @@ -803,10 +804,10 @@ static BHeadN *get_bhead(FileData *fd) bhead.len= 0; } } - + /* make sure people are not trying to pass bad blend files */ if (bhead.len < 0) fd->eof = 1; - + /* bhead now contains the (converted) bhead structure. Now read * the associated data and put everything in a BHeadN (creative naming !) */ @@ -815,9 +816,9 @@ static BHeadN *get_bhead(FileData *fd) if (new_bhead) { new_bhead->next = new_bhead->prev = NULL; new_bhead->bhead = bhead; - + readsize = fd->read(fd, new_bhead + 1, bhead.len); - + if (readsize != bhead.len) { fd->eof = 1; MEM_freeN(new_bhead); @@ -837,7 +838,7 @@ static BHeadN *get_bhead(FileData *fd) if (new_bhead) { BLI_addtail(&fd->listbase, new_bhead); } - + return(new_bhead); } @@ -845,7 +846,7 @@ BHead *blo_firstbhead(FileData *fd) { BHeadN *new_bhead; BHead *bhead = NULL; - + /* Rewind the file * Read in a new block if necessary */ @@ -853,11 +854,11 @@ BHead *blo_firstbhead(FileData *fd) if (new_bhead == NULL) { new_bhead = get_bhead(fd); } - + if (new_bhead) { bhead = &new_bhead->bhead; } - + return(bhead); } @@ -865,7 +866,7 @@ BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock) { BHeadN *bheadn = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead)); BHeadN *prev = bheadn->prev; - + return (prev) ? &prev->bhead : NULL; } @@ -873,25 +874,25 @@ BHead *blo_nextbhead(FileData *fd, BHead *thisblock) { BHeadN *new_bhead = NULL; BHead *bhead = NULL; - + if (thisblock) { /* bhead is actually a sub part of BHeadN * We calculate the BHeadN pointer from the BHead pointer below */ new_bhead = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead)); - + /* get the next BHeadN. If it doesn't exist we read in the next one */ new_bhead = new_bhead->next; if (new_bhead == NULL) { new_bhead = get_bhead(fd); } } - + if (new_bhead) { /* here we do the reverse: * go from the BHeadN pointer to the BHead pointer */ bhead = &new_bhead->bhead; } - + return(bhead); } @@ -950,11 +951,11 @@ static void decode_blender_header(FileData *fd) static bool read_file_dna(FileData *fd, const char **r_error_message) { BHead *bhead; - + for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) { if (bhead->code == DNA1) { const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0; - + fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap, true, r_error_message); if (fd->filesdna) { fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna); @@ -966,12 +967,12 @@ static bool read_file_dna(FileData *fd, const char **r_error_message) else { return false; } - + } else if (bhead->code == ENDB) break; } - + *r_error_message = "Missing DNA block"; return false; } @@ -1020,28 +1021,28 @@ static int *read_file_thumbnail(FileData *fd) static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size) { int readsize = read(filedata->filedes, buffer, size); - + if (readsize < 0) { readsize = EOF; } else { filedata->seek += readsize; } - + return readsize; } static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size) { int readsize = gzread(filedata->gzfiledes, buffer, size); - + if (readsize < 0) { readsize = EOF; } else { filedata->seek += readsize; } - + return (readsize); } @@ -1049,10 +1050,10 @@ static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int si { /* don't read more bytes then there are available in the buffer */ int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek)); - + memcpy(buffer, filedata->buffer + filedata->seek, readsize); filedata->seek += readsize; - + return (readsize); } @@ -1062,13 +1063,13 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int s static unsigned int offset = 0; /* size of previous chunks */ static MemFileChunk *chunk = NULL; unsigned int chunkoffset, readsize, totread; - + if (size == 0) return 0; - + if (seek != (unsigned int)filedata->seek) { chunk = filedata->memfile->chunks.first; seek = 0; - + while (chunk) { if (seek + chunk->size > (unsigned) filedata->seek) break; seek += chunk->size; @@ -1077,48 +1078,48 @@ static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int s offset = seek; seek = filedata->seek; } - + if (chunk) { totread = 0; - + do { /* first check if it's on the end if current chunk */ if (seek-offset == chunk->size) { offset += chunk->size; chunk = chunk->next; } - + /* debug, should never happen */ if (chunk == NULL) { printf("illegal read, chunk zero\n"); return 0; } - + chunkoffset = seek-offset; readsize = size-totread; - + /* data can be spread over multiple chunks, so clamp size * to within this chunk, and then it will read further in * the next chunk */ if (chunkoffset+readsize > chunk->size) readsize= chunk->size-chunkoffset; - + memcpy(POINTER_OFFSET(buffer, totread), chunk->buf + chunkoffset, readsize); totread += readsize; filedata->seek += readsize; seek += readsize; } while (totread < size); - + return totread; } - + return 0; } static FileData *filedata_new(void) { FileData *fd = MEM_callocN(sizeof(FileData), "FileData"); - + fd->filedes = -1; fd->gzfiledes = NULL; @@ -1127,14 +1128,14 @@ static FileData *filedata_new(void) fd->datamap = oldnewmap_new(); fd->globmap = oldnewmap_new(); fd->libmap = oldnewmap_new(); - + return fd; } static FileData *blo_decode_and_check(FileData *fd, ReportList *reports) { decode_blender_header(fd); - + if (fd->flags & FD_FLAGS_FILE_OK) { const char *error_message = NULL; if (read_file_dna(fd, &error_message) == false) { @@ -1150,7 +1151,7 @@ static FileData *blo_decode_and_check(FileData *fd, ReportList *reports) blo_freefiledata(fd); fd = NULL; } - + return fd; } @@ -1250,12 +1251,12 @@ static int fd_read_gzip_from_memory_init(FileData *fd) fd->strm.total_out = 0; fd->strm.zalloc = Z_NULL; fd->strm.zfree = Z_NULL; - + if (inflateInit2(&fd->strm, (16+MAX_WBITS)) != Z_OK) return 0; fd->read = fd_read_gzip_from_memory; - + return 1; } @@ -1268,10 +1269,10 @@ FileData *blo_openblendermemory(const void *mem, int memsize, ReportList *report else { FileData *fd = filedata_new(); const char *cp = mem; - + fd->buffer = mem; fd->buffersize = memsize; - + /* test if gzip */ if (cp[0] == 0x1f && cp[1] == 0x8b) { if (0 == fd_read_gzip_from_memory_init(fd)) { @@ -1281,7 +1282,7 @@ FileData *blo_openblendermemory(const void *mem, int memsize, ReportList *report } else fd->read = fd_read_from_memory; - + fd->flags |= FD_FLAGS_NOT_MY_BUFFER; #ifdef WITH_GAMEENGINE_BPPLAYER @@ -1302,10 +1303,10 @@ FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports) else { FileData *fd = filedata_new(); fd->memfile = memfile; - + fd->read = fd_read_from_memfile; fd->flags |= FD_FLAGS_NOT_MY_BUFFER; - + return blo_decode_and_check(fd, reports); } } @@ -1317,22 +1318,22 @@ void blo_freefiledata(FileData *fd) if (fd->filedes != -1) { close(fd->filedes); } - + if (fd->gzfiledes != NULL) { gzclose(fd->gzfiledes); } - + if (fd->strm.next_in) { if (inflateEnd(&fd->strm) != Z_OK) { printf("close gzip stream error\n"); } } - + if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) { MEM_freeN((void *)fd->buffer); fd->buffer = NULL; } - + // Free all BHeadN data blocks BLI_freelistN(&fd->listbase); @@ -1340,7 +1341,7 @@ void blo_freefiledata(FileData *fd) DNA_sdna_free(fd->filesdna); if (fd->compflags) MEM_freeN((void *)fd->compflags); - + if (fd->datamap) oldnewmap_free(fd->datamap); if (fd->globmap) @@ -1357,7 +1358,7 @@ void blo_freefiledata(FileData *fd) oldnewmap_free(fd->libmap); if (fd->bheadmap) MEM_freeN(fd->bheadmap); - + #ifdef USE_GHASH_BHEAD if (fd->bhead_idname_hash) { BLI_ghash_free(fd->bhead_idname_hash, NULL, NULL); @@ -1379,7 +1380,7 @@ void blo_freefiledata(FileData *fd) bool BLO_has_bfile_extension(const char *str) { const char *ext_test[4] = {".blend", ".ble", ".blend.gz", NULL}; - return BLI_testextensie_array(str, ext_test); + return BLI_path_extension_check_array(str, ext_test); } /** @@ -1554,7 +1555,7 @@ static void *newpackedadr(FileData *fd, const void *adr) /* used to restore { if (fd->packedmap && adr) return oldnewmap_lookup_and_inc(fd->packedmap, adr, true); - + return oldnewmap_lookup_and_inc(fd->datamap, adr, true); } @@ -1572,9 +1573,9 @@ void *blo_do_versions_newlibadr(FileData *fd, const void *lib, const void *adr) static void *newlibadr_us(FileData *fd, const void *lib, const void *adr) /* increases user number */ { ID *id = newlibadr(fd, lib, adr); - + id_us_plus_no_lib(id); - + return id; } @@ -1595,13 +1596,13 @@ static void *newlibadr_real_us(FileData *fd, const void *lib, const void *adr) / static void change_idid_adr_fd(FileData *fd, const void *old, void *new) { int i; - + /* use a binary search if we have a sorted libmap, for now it's not needed. */ BLI_assert(fd->libmap->sorted == false); for (i = 0; i < fd->libmap->nentries; i++) { OldNew *entry = &fd->libmap->entries[i]; - + if (old==entry->newp && entry->nr==ID_ID) { entry->newp = new; if (new) entry->nr = GS( ((ID *)new)->name ); @@ -1612,15 +1613,15 @@ static void change_idid_adr_fd(FileData *fd, const void *old, void *new) static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new) { Main *mainptr; - + for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) { FileData *fd; - + if (mainptr->curlib) fd = mainptr->curlib->filedata; else fd = basefd; - + if (fd) { change_idid_adr_fd(fd, old, new); } @@ -1634,7 +1635,7 @@ static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, voi void blo_clear_proxy_pointers_from_lib(Main *oldmain) { Object *ob = oldmain->object.first; - + for (; ob; ob= ob->id.next) { if (ob->id.lib) ob->proxy_from = NULL; @@ -1646,9 +1647,9 @@ void blo_make_image_pointer_map(FileData *fd, Main *oldmain) Image *ima = oldmain->image.first; Scene *sce = oldmain->scene.first; int a; - + fd->imamap = oldnewmap_new(); - + for (; ima; ima = ima->id.next) { if (ima->cache) oldnewmap_insert(fd->imamap, ima->cache, ima->cache, 0); @@ -1680,13 +1681,13 @@ void blo_end_image_pointer_map(FileData *fd, Main *oldmain) Image *ima = oldmain->image.first; Scene *sce = oldmain->scene.first; int i; - + /* used entries were restored, so we put them to zero */ for (i = 0; i < fd->imamap->nentries; i++, entry++) { if (entry->nr > 0) entry->newp = NULL; } - + for (; ima; ima = ima->id.next) { ima->cache = newimaadr(fd, ima->cache); if (ima->cache == NULL) { @@ -1699,7 +1700,7 @@ void blo_end_image_pointer_map(FileData *fd, Main *oldmain) } for (i = 0; i < IMA_MAX_RENDER_SLOT; i++) ima->renders[i] = newimaadr(fd, ima->renders[i]); - + for (i = 0; i < TEXTARGET_COUNT; i++) ima->gputexture[i] = newimaadr(fd, ima->gputexture[i]); ima->rr = newimaadr(fd, ima->rr); @@ -1708,7 +1709,7 @@ void blo_end_image_pointer_map(FileData *fd, Main *oldmain) if (sce->nodetree && sce->nodetree->previews) { bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews"); bNodeInstanceHashIterator iter; - + /* reconstruct the preview hash, only using remaining pointers */ NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) { bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); @@ -1730,17 +1731,17 @@ void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain) { MovieClip *clip = oldmain->movieclip.first; Scene *sce = oldmain->scene.first; - + fd->movieclipmap = oldnewmap_new(); - + for (; clip; clip = clip->id.next) { if (clip->cache) oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0); - + if (clip->tracking.camera.intrinsics) oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0); } - + for (; sce; sce = sce->id.next) { if (sce->nodetree) { bNode *node; @@ -1759,18 +1760,18 @@ void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain) MovieClip *clip = oldmain->movieclip.first; Scene *sce = oldmain->scene.first; int i; - + /* used entries were restored, so we put them to zero */ for (i=0; i < fd->movieclipmap->nentries; i++, entry++) { if (entry->nr > 0) entry->newp = NULL; } - + for (; clip; clip = clip->id.next) { clip->cache = newmclipadr(fd, clip->cache); clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics); } - + for (; sce; sce = sce->id.next) { if (sce->nodetree) { bNode *node; @@ -1784,12 +1785,12 @@ void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain) void blo_make_sound_pointer_map(FileData *fd, Main *oldmain) { bSound *sound = oldmain->sound.first; - + fd->soundmap = oldnewmap_new(); - + for (; sound; sound = sound->id.next) { if (sound->waveform) - oldnewmap_insert(fd->soundmap, sound->waveform, sound->waveform, 0); + oldnewmap_insert(fd->soundmap, sound->waveform, sound->waveform, 0); } } @@ -1800,13 +1801,13 @@ void blo_end_sound_pointer_map(FileData *fd, Main *oldmain) OldNew *entry = fd->soundmap->entries; bSound *sound = oldmain->sound.first; int i; - + /* used entries were restored, so we put them to zero */ for (i = 0; i < fd->soundmap->nentries; i++, entry++) { if (entry->nr > 0) entry->newp = NULL; } - + for (; sound; sound = sound->id.next) { sound->waveform = newsoundadr(fd, sound->waveform); } @@ -1826,9 +1827,9 @@ void blo_make_packed_pointer_map(FileData *fd, Main *oldmain) VFont *vfont; bSound *sound; Library *lib; - + fd->packedmap = oldnewmap_new(); - + for (ima = oldmain->image.first; ima; ima = ima->id.next) { ImagePackedFile *imapf; @@ -1839,15 +1840,15 @@ void blo_make_packed_pointer_map(FileData *fd, Main *oldmain) if (imapf->packedfile) insert_packedmap(fd, imapf->packedfile); } - + for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next) if (vfont->packedfile) insert_packedmap(fd, vfont->packedfile); - + for (sound = oldmain->sound.first; sound; sound = sound->id.next) if (sound->packedfile) insert_packedmap(fd, sound->packedfile); - + for (lib = oldmain->library.first; lib; lib = lib->id.next) if (lib->packedfile) insert_packedmap(fd, lib->packedfile); @@ -1864,13 +1865,13 @@ void blo_end_packed_pointer_map(FileData *fd, Main *oldmain) Library *lib; OldNew *entry = fd->packedmap->entries; int i; - + /* used entries were restored, so we put them to zero */ for (i=0; i < fd->packedmap->nentries; i++, entry++) { if (entry->nr > 0) entry->newp = NULL; } - + for (ima = oldmain->image.first; ima; ima = ima->id.next) { ImagePackedFile *imapf; @@ -1879,13 +1880,13 @@ void blo_end_packed_pointer_map(FileData *fd, Main *oldmain) for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) imapf->packedfile = newpackedadr(fd, imapf->packedfile); } - + for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next) vfont->packedfile = newpackedadr(fd, vfont->packedfile); for (sound = oldmain->sound.first; sound; sound = sound->id.next) sound->packedfile = newpackedadr(fd, sound->packedfile); - + for (lib = oldmain->library.first; lib; lib = lib->id.next) lib->packedfile = newpackedadr(fd, lib->packedfile); } @@ -1896,7 +1897,7 @@ void blo_add_library_pointer_map(ListBase *old_mainlist, FileData *fd) { Main *ptr = old_mainlist->first; ListBase *lbarray[MAX_LIBARRAY]; - + for (ptr = ptr->next; ptr; ptr = ptr->next) { int i = set_listbasepointers(ptr, lbarray); while (i--) { @@ -1917,14 +1918,14 @@ static void switch_endian_structs(const struct SDNA *filesdna, BHead *bhead) { int blocksize, nblocks; char *data; - + data = (char *)(bhead+1); blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ]; - + nblocks = bhead->nr; while (nblocks--) { DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data); - + data += blocksize; } } @@ -1932,12 +1933,12 @@ static void switch_endian_structs(const struct SDNA *filesdna, BHead *bhead) static void *read_struct(FileData *fd, BHead *bh, const char *blockname) { void *temp = NULL; - + if (bh->len) { /* switch is based on file dna */ if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN)) switch_endian_structs(fd->filesdna, bh); - + if (fd->compflags[bh->SDNAnr] != SDNA_CMP_REMOVED) { if (fd->compflags[bh->SDNAnr] == SDNA_CMP_NOT_EQUAL) { temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1)); @@ -1958,9 +1959,9 @@ typedef void (*link_list_cb)(FileData *fd, void *data); static void link_list_ex(FileData *fd, ListBase *lb, link_list_cb callback) /* only direct data */ { Link *ln, *prev; - + if (BLI_listbase_is_empty(lb)) return; - + lb->first = newdataadr(fd, lb->first); if (callback != NULL) { callback(fd, lb->first); @@ -1995,7 +1996,7 @@ static void link_glob_list(FileData *fd, ListBase *lb) /* for glob data */ oldnewmap_insert(fd->globmap, lb->first, poin, 0); } lb->first = poin; - + ln = lb->first; prev = NULL; while (ln) { @@ -2023,11 +2024,11 @@ static void test_pointer_array(FileData *fd, void **mat) */ if (*mat) { len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen; - + if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) { ipoin=imat= MEM_malloc_arrayN(len, 4, "newmatar"); lpoin= *mat; - + while (len-- > 0) { if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN)) BLI_endian_switch_int64(lpoin); @@ -2038,11 +2039,11 @@ static void test_pointer_array(FileData *fd, void **mat) MEM_freeN(*mat); *mat = imat; } - + if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) { lpoin = lmat = MEM_malloc_arrayN(len, 8, "newmatar"); ipoin = *mat; - + while (len-- > 0) { *lpoin = *ipoin; ipoin++; @@ -2063,21 +2064,21 @@ static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData { IDProperty *array; int i; - + /* since we didn't save the extra buffer, set totallen to len */ prop->totallen = prop->len; prop->data.pointer = newdataadr(fd, prop->data.pointer); array = (IDProperty *)prop->data.pointer; - + /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared * theres not really anything we can do to correct this, at least don't crash */ if (array == NULL) { prop->len = 0; prop->totallen = 0; } - - + + for (i = 0; i < prop->len; i++) IDP_DirectLinkProperty(&array[i], switch_endian, fd); } @@ -2086,15 +2087,15 @@ static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *f { IDProperty **array; int i; - + /* since we didn't save the extra buffer, set totallen to len */ prop->totallen = prop->len; prop->data.pointer = newdataadr(fd, prop->data.pointer); - + if (prop->subtype == IDP_GROUP) { test_pointer_array(fd, prop->data.pointer); array = prop->data.pointer; - + for (i = 0; i < prop->len; i++) IDP_DirectLinkProperty(array[i], switch_endian, fd); } @@ -2122,9 +2123,9 @@ static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *f { ListBase *lb = &prop->data.group; IDProperty *loop; - + link_list(fd, lb); - + /*Link child id properties now*/ for (loop=prop->data.group.first; loop; loop=loop->next) { IDP_DirectLinkProperty(loop, switch_endian, fd); @@ -2156,7 +2157,7 @@ static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData * if switch_endian is true, so we have to first unswap * them then reswap them as a single 64-bit entity. */ - + if (switch_endian) { BLI_endian_switch_int32(&prop->data.val); BLI_endian_switch_int32(&prop->data.val2); @@ -2239,7 +2240,7 @@ static void IDP_LibLinkProperty(IDProperty *prop, FileData *fd) static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv) { PreviewImage *prv = newdataadr(fd, old_prv); - + if (prv) { int i; for (i = 0; i < NUM_ICON_SIZES; ++i) { @@ -2251,7 +2252,7 @@ static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_p prv->icon_id = 0; prv->tag = 0; } - + return prv; } @@ -2278,10 +2279,10 @@ static void direct_link_id(FileData *fd, ID *id) static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap) { int a; - + /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */ cumap->flag &= ~CUMA_PREMULLED; - + for (a = 0; a < CM_TOT; a++) { cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve); cumap->cm[a].table = NULL; @@ -2372,7 +2373,7 @@ static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf) if (pf) { pf->data = newpackedadr(fd, pf->data); } - + return pf; } @@ -2384,7 +2385,7 @@ static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf) static void lib_link_ipo(FileData *fd, Main *main) { Ipo *ipo; - + for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) { if (ipo->id.tag & LIB_TAG_NEED_LINK) { IpoCurve *icu; @@ -2403,7 +2404,7 @@ static void direct_link_ipo(FileData *fd, Ipo *ipo) IpoCurve *icu; link_list(fd, &(ipo->curve)); - + for (icu = ipo->curve.first; icu; icu = icu->next) { icu->bezt = newdataadr(fd, icu->bezt); icu->bp = newdataadr(fd, icu->bp); @@ -2416,7 +2417,7 @@ static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist) { bActionStrip *strip; bActionModifier *amod; - + for (strip=striplist->first; strip; strip=strip->next) { strip->object = newlibadr(fd, id->lib, strip->object); strip->act = newlibadr_us(fd, id->lib, strip->act); @@ -2430,9 +2431,9 @@ static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist) static void direct_link_nlastrips(FileData *fd, ListBase *strips) { bActionStrip *strip; - + link_list(fd, strips); - + for (strip = strips->first; strip; strip = strip->next) link_list(fd, &strip->modifiers); } @@ -2452,7 +2453,7 @@ static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbas static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list) { FModifier *fcm; - + for (fcm = list->first; fcm; fcm = fcm->next) { /* data for specific modifiers */ switch (fcm->type) { @@ -2467,33 +2468,33 @@ static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list) } } -static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) +static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) { FCurve *fcu; - + if (list == NULL) return; - + /* relink ID-block references... */ for (fcu = list->first; fcu; fcu = fcu->next) { /* driver data */ if (fcu->driver) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar= driver->variables.first; dvar; dvar= dvar->next) { DRIVER_TARGETS_LOOPER(dvar) { /* only relink if still used */ if (tarIndex < dvar->num_targets) - dtar->id = newlibadr(fd, id->lib, dtar->id); + dtar->id = newlibadr(fd, id->lib, dtar->id); else dtar->id = NULL; } DRIVER_TARGETS_LOOPER_END } } - + /* modifiers */ lib_link_fmodifiers(fd, id, &fcu->modifiers); } @@ -2504,20 +2505,20 @@ static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) static void direct_link_fmodifiers(FileData *fd, ListBase *list, FCurve *curve) { FModifier *fcm; - + for (fcm = list->first; fcm; fcm = fcm->next) { /* relink general data */ fcm->data = newdataadr(fd, fcm->data); fcm->curve = curve; - + /* do relinking of data for specific types */ switch (fcm->type) { case FMODIFIER_TYPE_GENERATOR: { FMod_Generator *data = (FMod_Generator *)fcm->data; - + data->coefficients = newdataadr(fd, data->coefficients); - + if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { BLI_endian_switch_float_array(data->coefficients, data->arraysize); } @@ -2527,7 +2528,7 @@ static void direct_link_fmodifiers(FileData *fd, ListBase *list, FCurve *curve) case FMODIFIER_TYPE_ENVELOPE: { FMod_Envelope *data= (FMod_Envelope *)fcm->data; - + data->data= newdataadr(fd, data->data); break; @@ -2535,7 +2536,7 @@ static void direct_link_fmodifiers(FileData *fd, ListBase *list, FCurve *curve) case FMODIFIER_TYPE_PYTHON: { FMod_Python *data = (FMod_Python *)fcm->data; - + data->prop = newdataadr(fd, data->prop); IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); @@ -2549,38 +2550,38 @@ static void direct_link_fmodifiers(FileData *fd, ListBase *list, FCurve *curve) static void direct_link_fcurves(FileData *fd, ListBase *list) { FCurve *fcu; - + /* link F-Curve data to F-Curve again (non ID-libs) */ for (fcu = list->first; fcu; fcu = fcu->next) { /* curve data */ fcu->bezt = newdataadr(fd, fcu->bezt); fcu->fpt = newdataadr(fd, fcu->fpt); - + /* rna path */ fcu->rna_path = newdataadr(fd, fcu->rna_path); - + /* group */ fcu->grp = newdataadr_ex(fd, fcu->grp, false); - + /* clear disabled flag - allows disabled drivers to be tried again ([#32155]), * but also means that another method for "reviving disabled F-Curves" exists */ fcu->flag &= ~FCURVE_DISABLED; - + /* driver */ fcu->driver= newdataadr(fd, fcu->driver); if (fcu->driver) { ChannelDriver *driver= fcu->driver; DriverVar *dvar; - + /* compiled expression data will need to be regenerated (old pointer may still be set here) */ driver->expr_comp = NULL; - - /* give the driver a fresh chance - the operating environment may be different now + + /* give the driver a fresh chance - the operating environment may be different now * (addons, etc. may be different) so the driver namespace may be sane now [#32155] */ driver->flag &= ~DRIVER_FLAG_INVALID; - + /* relink variables, targets and their paths */ link_list(fd, &driver->variables); for (dvar= driver->variables.first; dvar; dvar= dvar->next) { @@ -2595,7 +2596,7 @@ static void direct_link_fcurves(FileData *fd, ListBase *list) DRIVER_TARGETS_LOOPER_END } } - + /* modifiers */ link_list(fd, &fcu->modifiers); direct_link_fmodifiers(fd, &fcu->modifiers, fcu); @@ -2608,14 +2609,14 @@ static void lib_link_action(FileData *fd, Main *main) for (bAction *act = main->action.first; act; act = act->id.next) { if (act->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(act->id.properties, fd); - + // XXX deprecated - old animation system <<< for (bActionChannel *chan = act->chanbase.first; chan; chan = chan->next) { chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo); lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels); } // >>> XXX deprecated - old animation system - + lib_link_fcurves(fd, &act->id, &act->curves); for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) { @@ -2642,13 +2643,13 @@ static void direct_link_action(FileData *fd, bAction *act) // XXX deprecated - old animation system <<< for (achan = act->chanbase.first; achan; achan=achan->next) { achan->grp = newdataadr(fd, achan->grp); - + link_list(fd, &achan->constraintChannels); } // >>> XXX deprecated - old animation system direct_link_fcurves(fd, &act->curves); - + for (agrp = act->groups.first; agrp; agrp= agrp->next) { agrp->channels.first= newdataadr(fd, agrp->channels.first); agrp->channels.last= newdataadr(fd, agrp->channels.last); @@ -2658,17 +2659,17 @@ static void direct_link_action(FileData *fd, bAction *act) static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list) { NlaStrip *strip; - + for (strip = list->first; strip; strip = strip->next) { /* check strip's children */ lib_link_nladata_strips(fd, id, &strip->strips); - + /* check strip's F-Curves */ lib_link_fcurves(fd, id, &strip->fcurves); - + /* reassign the counted-reference to action */ strip->act = newlibadr_us(fd, id->lib, strip->act); - + /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */ if ((strip->act) && (strip->act->idroot == 0)) strip->act->idroot = GS(id->name); @@ -2678,29 +2679,29 @@ static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list) static void lib_link_nladata(FileData *fd, ID *id, ListBase *list) { NlaTrack *nlt; - + /* we only care about the NLA strips inside the tracks */ for (nlt = list->first; nlt; nlt = nlt->next) { lib_link_nladata_strips(fd, id, &nlt->strips); } } -/* This handles Animato NLA-Strips linking +/* This handles Animato NLA-Strips linking * NOTE: this assumes that link_list has already been called on the list */ static void direct_link_nladata_strips(FileData *fd, ListBase *list) { NlaStrip *strip; - + for (strip = list->first; strip; strip = strip->next) { /* strip's child strips */ link_list(fd, &strip->strips); direct_link_nladata_strips(fd, &strip->strips); - + /* strip's F-Curves */ link_list(fd, &strip->fcurves); direct_link_fcurves(fd, &strip->fcurves); - + /* strip's F-Modifiers */ link_list(fd, &strip->modifiers); direct_link_fmodifiers(fd, &strip->modifiers, NULL); @@ -2711,11 +2712,11 @@ static void direct_link_nladata_strips(FileData *fd, ListBase *list) static void direct_link_nladata(FileData *fd, ListBase *list) { NlaTrack *nlt; - + for (nlt = list->first; nlt; nlt = nlt->next) { /* relink list of strips */ link_list(fd, &nlt->strips); - + /* relink strip data */ direct_link_nladata_strips(fd, &nlt->strips); } @@ -2727,11 +2728,11 @@ static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list) { KeyingSet *ks; KS_Path *ksp; - + /* here, we're only interested in the ID pointer stored in some of the paths */ for (ks = list->first; ks; ks = ks->next) { for (ksp = ks->paths.first; ksp; ksp = ksp->next) { - ksp->id= newlibadr(fd, id->lib, ksp->id); + ksp->id= newlibadr(fd, id->lib, ksp->id); } } } @@ -2741,12 +2742,12 @@ static void direct_link_keyingsets(FileData *fd, ListBase *list) { KeyingSet *ks; KS_Path *ksp; - + /* link KeyingSet data to KeyingSet again (non ID-libs) */ for (ks = list->first; ks; ks = ks->next) { /* paths */ link_list(fd, &ks->paths); - + for (ksp = ks->paths.first; ksp; ksp = ksp->next) { /* rna path */ ksp->rna_path= newdataadr(fd, ksp->rna_path); @@ -2760,22 +2761,22 @@ static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt) { if (adt == NULL) return; - + /* link action data */ adt->action= newlibadr_us(fd, id->lib, adt->action); adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact); - + /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */ if ((adt->action) && (adt->action->idroot == 0)) adt->action->idroot = GS(id->name); if ((adt->tmpact) && (adt->tmpact->idroot == 0)) adt->tmpact->idroot = GS(id->name); - + /* link drivers */ lib_link_fcurves(fd, id, &adt->drivers); - + /* overrides don't have lib-link for now, so no need to do anything */ - + /* link NLA-data */ lib_link_nladata(fd, id, &adt->nla_tracks); } @@ -2785,18 +2786,18 @@ static void direct_link_animdata(FileData *fd, AnimData *adt) /* NOTE: must have called newdataadr already before doing this... */ if (adt == NULL) return; - + /* link drivers */ link_list(fd, &adt->drivers); direct_link_fcurves(fd, &adt->drivers); - + /* link overrides */ // TODO... - + /* link NLA-data */ link_list(fd, &adt->nla_tracks); direct_link_nladata(fd, &adt->nla_tracks); - + /* relink active track/strip - even though strictly speaking this should only be used * if we're in 'tweaking mode', we need to be able to have this loaded back for * undo, but also since users may not exit tweakmode before saving (#24535) @@ -2805,7 +2806,7 @@ static void direct_link_animdata(FileData *fd, AnimData *adt) // state, but it's going to be too hard to enforce this single case... adt->act_track = newdataadr(fd, adt->act_track); adt->actstrip = newdataadr(fd, adt->actstrip); -} +} /* ************ READ CACHEFILES *************** */ @@ -2841,7 +2842,7 @@ static void direct_link_motionpath(FileData *fd, bMotionPath *mpath) /* sanity check */ if (mpath == NULL) return; - + /* relink points cache */ mpath->points = newdataadr(fd, mpath->points); } @@ -2853,17 +2854,17 @@ static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree) { bNode *node; bNodeSocket *sock; - + IDP_LibLinkProperty(ntree->id.properties, fd); lib_link_animdata(fd, &ntree->id, ntree->adt); - + ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd); - + for (node = ntree->nodes.first; node; node = node->next) { /* Link ID Properties -- and copy this comment EXACTLY for easy finding * of library blocks that implement this.*/ IDP_LibLinkProperty(node->prop, fd); - + node->id = newlibadr_us(fd, id->lib, node->id); for (sock = node->inputs.first; sock; sock = sock->next) { @@ -2873,7 +2874,7 @@ static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree) IDP_LibLinkProperty(sock->prop, fd); } } - + for (sock = ntree->inputs.first; sock; sock = sock->next) { IDP_LibLinkProperty(sock->prop, fd); } @@ -2903,10 +2904,10 @@ static void lib_node_do_versions_group_indices(bNode *gnode) bNodeTree *ngroup = (bNodeTree*)gnode->id; bNodeSocket *sock; bNodeLink *link; - + for (sock=gnode->outputs.first; sock; sock = sock->next) { int old_index = sock->to_index; - + for (link = ngroup->links.first; link; link = link->next) { if (link->tonode == NULL && link->fromsock->own_index == old_index) { strcpy(sock->identifier, link->fromsock->identifier); @@ -2919,7 +2920,7 @@ static void lib_node_do_versions_group_indices(bNode *gnode) } for (sock=gnode->inputs.first; sock; sock = sock->next) { int old_index = sock->to_index; - + for (link = ngroup->links.first; link; link = link->next) { if (link->fromnode == NULL && link->tosock->own_index == old_index) { strcpy(sock->identifier, link->tosock->identifier); @@ -2943,19 +2944,19 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) reinit_nodesystem(); } #endif - + /* set node->typeinfo pointers */ FOREACH_NODETREE(main, ntree, id) { ntreeSetTypes(NULL, ntree); } FOREACH_NODETREE_END - + /* verify static socket templates */ FOREACH_NODETREE(main, ntree, id) { bNode *node; for (node=ntree->nodes.first; node; node=node->next) node_verify_socket_templates(ntree, node); } FOREACH_NODETREE_END - + { bool has_old_groups = false; /* XXX this should actually be part of do_versions, but since we need @@ -2968,7 +2969,7 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) has_old_groups = 1; } } - + if (has_old_groups) { FOREACH_NODETREE(main, ntree, id) { /* updates external links for all group nodes in a tree */ @@ -2982,12 +2983,12 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) } } FOREACH_NODETREE_END } - + for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) { ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2; } } - + { /* Convert the previously used ntree->inputs/ntree->outputs lists to interface nodes. * Pre 2.56.2 node trees automatically have all unlinked sockets exposed already @@ -3000,7 +3001,7 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) * but due to a temporary bug such links could have been added in all trees, * so have to clean up all of them ... */ - + FOREACH_NODETREE(main, ntree, id) { if (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP) { bNode *input_node = NULL, *output_node = NULL; @@ -3011,21 +3012,21 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) * in that case just remove the invalid links. */ const bool create_io_nodes = (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE) != 0; - + float input_locx = 1000000.0f, input_locy = 0.0f; float output_locx = -1000000.0f, output_locy = 0.0f; /* rough guess, not nice but we don't have access to UI constants here ... */ static const float offsetx = 42 + 3*20 + 20; /*static const float offsety = 0.0f;*/ - + if (create_io_nodes) { if (ntree->inputs.first) input_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_INPUT); - + if (ntree->outputs.first) output_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_OUTPUT); } - + /* Redirect links from/to the node tree interface to input/output node. * If the fromnode/tonode pointers are NULL, this means a link from/to * the ntree interface sockets, which need to be redirected to new interface nodes. @@ -3033,13 +3034,13 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) for (link = ntree->links.first; link; link = next_link) { bool free_link = false; next_link = link->next; - + if (link->fromnode == NULL) { if (input_node) { link->fromnode = input_node; link->fromsock = node_group_input_find_socket(input_node, link->fromsock->identifier); ++num_inputs; - + if (link->tonode) { if (input_locx > link->tonode->locx - offsetx) input_locx = link->tonode->locx - offsetx; @@ -3050,13 +3051,13 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) free_link = true; } } - + if (link->tonode == NULL) { if (output_node) { link->tonode = output_node; link->tosock = node_group_output_find_socket(output_node, link->tosock->identifier); ++num_outputs; - + if (link->fromnode) { if (output_locx < link->fromnode->locx + offsetx) output_locx = link->fromnode->locx + offsetx; @@ -3067,11 +3068,11 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) free_link = true; } } - + if (free_link) nodeRemLink(ntree, link); } - + if (num_inputs > 0) { input_locy /= num_inputs; input_node->locx = input_locx; @@ -3082,19 +3083,19 @@ static void lib_verify_nodetree(Main *main, int UNUSED(open)) output_node->locx = output_locx; output_node->locy = output_locy; } - + /* clear do_versions flags */ ntree->flag &= ~(NTREE_DO_VERSIONS_CUSTOMNODES_GROUP | NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE); } } FOREACH_NODETREE_END } - + /* verify all group user nodes */ for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) { ntreeVerifyNodes(main, &ntree->id); } - + /* make update calls where necessary */ { FOREACH_NODETREE(main, ntree, id) { @@ -3108,7 +3109,7 @@ static void direct_link_node_socket(FileData *fd, bNodeSocket *sock) { sock->prop = newdataadr(fd, sock->prop); IDP_DirectLinkGroup_OrFree(&sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); - + sock->link = newdataadr(fd, sock->link); sock->typeinfo = NULL; sock->storage = newdataadr(fd, sock->storage); @@ -3123,31 +3124,31 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) bNode *node; bNodeSocket *sock; bNodeLink *link; - + ntree->init = 0; /* to set callbacks and force setting types */ ntree->is_updating = false; ntree->typeinfo= NULL; ntree->interface_type = NULL; - + ntree->progress = NULL; ntree->execdata = NULL; ntree->duplilock = NULL; ntree->adt = newdataadr(fd, ntree->adt); direct_link_animdata(fd, ntree->adt); - + ntree->id.recalc &= ~ID_RECALC_ALL; link_list(fd, &ntree->nodes); for (node = ntree->nodes.first; node; node = node->next) { node->typeinfo = NULL; - + link_list(fd, &node->inputs); link_list(fd, &node->outputs); - + node->prop = newdataadr(fd, node->prop); IDP_DirectLinkGroup_OrFree(&node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); - + link_list(fd, &node->internal_links); for (link = node->internal_links.first; link; link = link->next) { link->fromnode = newdataadr(fd, link->fromnode); @@ -3155,14 +3156,14 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) link->tonode = newdataadr(fd, link->tonode); link->tosock = newdataadr(fd, link->tosock); } - + if (node->type == CMP_NODE_MOVIEDISTORTION) { node->storage = newmclipadr(fd, node->storage); } else { node->storage = newdataadr(fd, node->storage); } - + if (node->storage) { /* could be handlerized at some point */ if (ntree->type==NTREE_SHADER) { @@ -3183,6 +3184,10 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) direct_link_curvemapping(fd, node->storage); else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) ((ImageUser *)node->storage)->ok = 1; + else if (node->type==CMP_NODE_CRYPTOMATTE) { + NodeCryptomatte *nc = (NodeCryptomatte *) node->storage; + nc->matte_id = newdataadr(fd, nc->matte_id); + } } else if ( ntree->type==NTREE_TEXTURE) { if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) @@ -3193,18 +3198,18 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) } } link_list(fd, &ntree->links); - + /* and we connect the rest */ for (node = ntree->nodes.first; node; node = node->next) { node->parent = newdataadr(fd, node->parent); node->lasty = 0; - + for (sock = node->inputs.first; sock; sock = sock->next) direct_link_node_socket(fd, sock); for (sock = node->outputs.first; sock; sock = sock->next) direct_link_node_socket(fd, sock); } - + /* interface socket lists */ link_list(fd, &ntree->inputs); link_list(fd, &ntree->outputs); @@ -3212,19 +3217,19 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) direct_link_node_socket(fd, sock); for (sock = ntree->outputs.first; sock; sock = sock->next) direct_link_node_socket(fd, sock); - + for (link = ntree->links.first; link; link= link->next) { link->fromnode = newdataadr(fd, link->fromnode); link->tonode = newdataadr(fd, link->tonode); link->fromsock = newdataadr(fd, link->fromsock); link->tosock = newdataadr(fd, link->tosock); } - + #if 0 if (ntree->previews) { bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews"); bNodeInstanceHashIterator iter; - + NODE_INSTANCE_HASH_ITER(iter, ntree->previews) { bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); if (preview) { @@ -3242,7 +3247,7 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree) /* XXX TODO */ ntree->previews = NULL; #endif - + /* type verification is in lib-link */ } @@ -3257,7 +3262,7 @@ typedef struct tConstraintLinkData { static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, bool is_reference, void *userdata) { tConstraintLinkData *cld= (tConstraintLinkData *)userdata; - + /* for reference types, we need to increment the usercounts on load... */ if (is_reference) { /* reference type - with usercount */ @@ -3273,7 +3278,7 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist) { tConstraintLinkData cld; bConstraint *con; - + /* legacy fixes */ for (con = conlist->first; con; con=con->next) { /* patch for error introduced by changing constraints (dunno how) */ @@ -3284,29 +3289,29 @@ static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist) /* own ipo, all constraints have it */ con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system } - + /* relink all ID-blocks used by the constraints */ cld.fd = fd; cld.id = id; - + BKE_constraints_id_loop(conlist, lib_link_constraint_cb, &cld); } static void direct_link_constraints(FileData *fd, ListBase *lb) { bConstraint *con; - + link_list(fd, lb); for (con=lb->first; con; con=con->next) { con->data = newdataadr(fd, con->data); - + switch (con->type) { case CONSTRAINT_TYPE_PYTHON: { bPythonConstraint *data= con->data; - + link_list(fd, &data->targets); - + data->prop = newdataadr(fd, data->prop); IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); break; @@ -3348,10 +3353,10 @@ static void direct_link_constraints(FileData *fd, ListBase *lb) static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose) { bArmature *arm = ob->data; - + if (!pose || !arm) return; - + /* always rebuild to match proxy or lib changes, but on Undo */ bool rebuild = false; @@ -3368,7 +3373,7 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose) /* sync proxy layer */ if (pose->proxy_layer) arm->layer = pose->proxy_layer; - + /* sync proxy active bone */ if (pose->proxy_act_bone[0]) { Bone *bone = BLI_ghash_lookup(bone_hash, pose->proxy_act_bone); @@ -3382,7 +3387,7 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose) lib_link_constraints(fd, (ID *)ob, &pchan->constraints); pchan->bone = BLI_ghash_lookup(bone_hash, pchan->name); - + IDP_LibLinkProperty(pchan->prop, fd); pchan->custom = newlibadr_us(fd, arm->id.lib, pchan->custom); @@ -3397,7 +3402,7 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose) } BLI_ghash_free(bone_hash, NULL, NULL); - + if (rebuild) { DAG_id_tag_update_ex(bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); @@ -3433,15 +3438,15 @@ static void lib_link_armature(FileData *fd, Main *main) static void direct_link_bones(FileData *fd, Bone *bone) { Bone *child; - + bone->parent = newdataadr(fd, bone->parent); bone->prop = newdataadr(fd, bone->prop); IDP_DirectLinkGroup_OrFree(&bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); - + bone->flag &= ~BONE_DRAW_ACTIVE; - + link_list(fd, &bone->childbase); - + for (child=bone->childbase.first; child; child=child->next) direct_link_bones(fd, child); } @@ -3449,18 +3454,18 @@ static void direct_link_bones(FileData *fd, Bone *bone) static void direct_link_armature(FileData *fd, bArmature *arm) { Bone *bone; - + link_list(fd, &arm->bonebase); arm->edbo = NULL; arm->sketch = NULL; - + arm->adt = newdataadr(fd, arm->adt); direct_link_animdata(fd, arm->adt); - + for (bone = arm->bonebase.first; bone; bone = bone->next) { direct_link_bones(fd, bone); } - + arm->act_bone = newdataadr(fd, arm->act_bone); arm->act_edbone = NULL; } @@ -3473,11 +3478,11 @@ static void lib_link_camera(FileData *fd, Main *main) if (ca->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(ca->id.properties, fd); lib_link_animdata(fd, &ca->id, ca->adt); - + ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX deprecated - old animation system ca->dof_ob = newlibadr(fd, ca->id.lib, ca->dof_ob); - + ca->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3498,7 +3503,7 @@ static void lib_link_lamp(FileData *fd, Main *main) if (la->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(la->id.properties, fd); lib_link_animdata(fd, &la->id, la->adt); - + for (int a = 0; a < MAX_MTEX; a++) { MTex *mtex = la->mtex[a]; if (mtex) { @@ -3506,14 +3511,14 @@ static void lib_link_lamp(FileData *fd, Main *main) mtex->object = newlibadr(fd, la->id.lib, mtex->object); } } - + la->ipo = newlibadr_us(fd, la->id.lib, la->ipo); // XXX deprecated - old animation system - + if (la->nodetree) { lib_link_ntree(fd, &la->id, la->nodetree); la->nodetree->id.lib = la->id.lib; } - + la->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3522,14 +3527,14 @@ static void lib_link_lamp(FileData *fd, Main *main) static void direct_link_lamp(FileData *fd, Lamp *la) { int a; - + la->adt = newdataadr(fd, la->adt); direct_link_animdata(fd, la->adt); - + for (a=0; amtex[a] = newdataadr(fd, la->mtex[a]); } - + la->curfalloff = newdataadr(fd, la->curfalloff); if (la->curfalloff) direct_link_curvemapping(fd, la->curfalloff); @@ -3539,7 +3544,7 @@ static void direct_link_lamp(FileData *fd, Lamp *la) direct_link_id(fd, &la->nodetree->id); direct_link_nodetree(fd, la->nodetree); } - + la->preview = direct_link_preview_image(fd, la->preview); } @@ -3563,10 +3568,10 @@ static void lib_link_key(FileData *fd, Main *main) if (key->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(key->id.properties, fd); lib_link_animdata(fd, &key->id, key->adt); - + key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX deprecated - old animation system key->from = newlibadr(fd, key->id.lib, key->from); - + key->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3576,14 +3581,14 @@ static void switch_endian_keyblock(Key *key, KeyBlock *kb) { int elemsize, a, b; char *data; - + elemsize = key->elemsize; data = kb->data; - + for (a = 0; a < kb->totelem; a++) { const char *cp = key->elemstr; char *poin = data; - + while (cp[0]) { /* cp[0] == amount */ switch (cp[1]) { /* cp[1] = type */ case IPO_FLOAT: @@ -3594,7 +3599,7 @@ static void switch_endian_keyblock(Key *key, KeyBlock *kb) poin += sizeof(float) * b; break; } - + cp += 2; } data += elemsize; @@ -3604,17 +3609,17 @@ static void switch_endian_keyblock(Key *key, KeyBlock *kb) static void direct_link_key(FileData *fd, Key *key) { KeyBlock *kb; - + link_list(fd, &(key->block)); - + key->adt = newdataadr(fd, key->adt); direct_link_animdata(fd, key->adt); - + key->refkey= newdataadr(fd, key->refkey); - + for (kb = key->block.first; kb; kb = kb->next) { kb->data = newdataadr(fd, kb->data); - + if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) switch_endian_keyblock(key, kb); } @@ -3628,13 +3633,13 @@ static void lib_link_mball(FileData *fd, Main *main) if (mb->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(mb->id.properties, fd); lib_link_animdata(fd, &mb->id, mb->adt); - + for (int a = 0; a < mb->totcol; a++) { mb->mat[a] = newlibadr_us(fd, mb->id.lib, mb->mat[a]); } - + mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX deprecated - old animation system - + mb->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3644,12 +3649,12 @@ static void direct_link_mball(FileData *fd, MetaBall *mb) { mb->adt = newdataadr(fd, mb->adt); direct_link_animdata(fd, mb->adt); - + mb->mat = newdataadr(fd, mb->mat); test_pointer_array(fd, (void **)&mb->mat); - + link_list(fd, &(mb->elems)); - + BLI_listbase_clear(&mb->disp); mb->editelems = NULL; /* mb->edit_elems.first= mb->edit_elems.last= NULL;*/ @@ -3664,9 +3669,9 @@ static void lib_link_world(FileData *fd, Main *main) if (wrld->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(wrld->id.properties, fd); lib_link_animdata(fd, &wrld->id, wrld->adt); - + wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX deprecated - old animation system - + for (int a = 0; a < MAX_MTEX; a++) { MTex *mtex = wrld->mtex[a]; if (mtex) { @@ -3674,12 +3679,12 @@ static void lib_link_world(FileData *fd, Main *main) mtex->object = newlibadr(fd, wrld->id.lib, mtex->object); } } - + if (wrld->nodetree) { lib_link_ntree(fd, &wrld->id, wrld->nodetree); wrld->nodetree->id.lib = wrld->id.lib; } - + wrld->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3688,20 +3693,20 @@ static void lib_link_world(FileData *fd, Main *main) static void direct_link_world(FileData *fd, World *wrld) { int a; - + wrld->adt = newdataadr(fd, wrld->adt); direct_link_animdata(fd, wrld->adt); - + for (a = 0; a < MAX_MTEX; a++) { wrld->mtex[a] = newdataadr(fd, wrld->mtex[a]); } - + wrld->nodetree = newdataadr(fd, wrld->nodetree); if (wrld->nodetree) { direct_link_id(fd, &wrld->nodetree->id); direct_link_nodetree(fd, wrld->nodetree); } - + wrld->preview = direct_link_preview_image(fd, wrld->preview); BLI_listbase_clear(&wrld->gpumaterial); } @@ -3754,24 +3759,24 @@ static void direct_link_text(FileData *fd, Text *text) } /* else { */ #endif - + link_list(fd, &text->lines); - + text->curl = newdataadr(fd, text->curl); text->sell = newdataadr(fd, text->sell); - + for (ln = text->lines.first; ln; ln = ln->next) { ln->line = newdataadr(fd, ln->line); ln->format = NULL; - + if (ln->len != (int) strlen(ln->line)) { printf("Error loading text, line lengths differ\n"); ln->len = strlen(ln->line); } } - + text->flags = (text->flags) & ~TXT_ISEXT; - + id_us_ensure_real(&text->id); } @@ -3782,7 +3787,7 @@ static void lib_link_image(FileData *fd, Main *main) for (Image *ima = main->image.first; ima; ima = ima->id.next) { if (ima->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(ima->id.properties, fd); - + ima->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3816,7 +3821,7 @@ static void direct_link_image(FileData *fd, Image *ima) /* undo system, try to restore render buffers */ if (fd->imamap) { int a; - + for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) ima->renders[a] = newimaadr(fd, ima->renders[a]); } @@ -3853,11 +3858,11 @@ static void lib_link_curve(FileData *fd, Main *main) if (cu->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(cu->id.properties, fd); lib_link_animdata(fd, &cu->id, cu->adt); - + for (int a = 0; a < cu->totcol; a++) { cu->mat[a] = newlibadr_us(fd, cu->id.lib, cu->mat[a]); } - + cu->bevobj = newlibadr(fd, cu->id.lib, cu->bevobj); cu->taperobj = newlibadr(fd, cu->id.lib, cu->taperobj); cu->textoncurve = newlibadr(fd, cu->id.lib, cu->textoncurve); @@ -3865,10 +3870,10 @@ static void lib_link_curve(FileData *fd, Main *main) cu->vfontb = newlibadr_us(fd, cu->id.lib, cu->vfontb); cu->vfonti = newlibadr_us(fd, cu->id.lib, cu->vfonti); cu->vfontbi = newlibadr_us(fd, cu->id.lib, cu->vfontbi); - + cu->ipo = newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX deprecated - old animation system cu->key = newlibadr_us(fd, cu->id.lib, cu->key); - + cu->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3889,10 +3894,10 @@ static void direct_link_curve(FileData *fd, Curve *cu) { Nurb *nu; TextBox *tb; - + cu->adt= newdataadr(fd, cu->adt); direct_link_animdata(fd, cu->adt); - + /* Protect against integer overflow vulnerability. */ CLAMP(cu->len_wchar, 0, INT_MAX - 4); @@ -3907,7 +3912,7 @@ static void direct_link_curve(FileData *fd, Curve *cu) } else { cu->nurb.first=cu->nurb.last= NULL; - + tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBoxread"); if (cu->tb) { memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox)); @@ -3925,14 +3930,14 @@ static void direct_link_curve(FileData *fd, Curve *cu) cu->editnurb = NULL; cu->editfont = NULL; - + for (nu = cu->nurb.first; nu; nu = nu->next) { nu->bezt = newdataadr(fd, nu->bezt); nu->bp = newdataadr(fd, nu->bp); nu->knotsu = newdataadr(fd, nu->knotsu); nu->knotsv = newdataadr(fd, nu->knotsv); if (cu->vfont == NULL) nu->charidx = 0; - + if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { switch_endian_knots(nu); } @@ -3948,7 +3953,7 @@ static void lib_link_texture(FileData *fd, Main *main) if (tex->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(tex->id.properties, fd); lib_link_animdata(fd, &tex->id, tex->adt); - + tex->ima = newlibadr_us(fd, tex->id.lib, tex->ima); tex->ipo = newlibadr_us(fd, tex->id.lib, tex->ipo); // XXX deprecated - old animation system if (tex->env) @@ -3959,12 +3964,12 @@ static void lib_link_texture(FileData *fd, Main *main) tex->vd->object = newlibadr(fd, tex->id.lib, tex->vd->object); if (tex->ot) tex->ot->object = newlibadr(fd, tex->id.lib, tex->ot->object); - + if (tex->nodetree) { lib_link_ntree(fd, &tex->id, tex->nodetree); tex->nodetree->id.lib = tex->id.lib; } - + tex->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -3992,7 +3997,7 @@ static void direct_link_texture(FileData *fd, Tex *tex) } tex->pd->point_data = NULL; /* runtime data */ } - + tex->vd = newdataadr(fd, tex->vd); if (tex->vd) { tex->vd->dataset = NULL; @@ -4002,17 +4007,17 @@ static void direct_link_texture(FileData *fd, Tex *tex) if (tex->type == TEX_VOXELDATA) tex->vd = MEM_callocN(sizeof(VoxelData), "direct_link_texture VoxelData"); } - + tex->ot = newdataadr(fd, tex->ot); - + tex->nodetree = newdataadr(fd, tex->nodetree); if (tex->nodetree) { direct_link_id(fd, &tex->nodetree->id); direct_link_nodetree(fd, tex->nodetree); } - + tex->preview = direct_link_preview_image(fd, tex->preview); - + tex->iuser.ok = 1; } @@ -4026,10 +4031,10 @@ static void lib_link_material(FileData *fd, Main *main) if (ma->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(ma->id.properties, fd); lib_link_animdata(fd, &ma->id, ma->adt); - + ma->ipo = newlibadr_us(fd, ma->id.lib, ma->ipo); // XXX deprecated - old animation system ma->group = newlibadr_us(fd, ma->id.lib, ma->group); - + for (int a = 0; a < MAX_MTEX; a++) { MTex *mtex = ma->mtex[a]; if (mtex) { @@ -4037,12 +4042,12 @@ static void lib_link_material(FileData *fd, Main *main) mtex->object = newlibadr(fd, ma->id.lib, mtex->object); } } - + if (ma->nodetree) { lib_link_ntree(fd, &ma->id, ma->nodetree); ma->nodetree->id.lib = ma->id.lib; } - + ma->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -4051,10 +4056,10 @@ static void lib_link_material(FileData *fd, Main *main) static void direct_link_material(FileData *fd, Material *ma) { int a; - + ma->adt = newdataadr(fd, ma->adt); direct_link_animdata(fd, ma->adt); - + for (a = 0; a < MAX_MTEX; a++) { ma->mtex[a] = newdataadr(fd, ma->mtex[a]); } @@ -4062,13 +4067,13 @@ static void direct_link_material(FileData *fd, Material *ma) ma->ramp_col = newdataadr(fd, ma->ramp_col); ma->ramp_spec = newdataadr(fd, ma->ramp_spec); - + ma->nodetree = newdataadr(fd, ma->nodetree); if (ma->nodetree) { direct_link_id(fd, &ma->nodetree->id); direct_link_nodetree(fd, ma->nodetree); } - + ma->preview = direct_link_preview_image(fd, ma->preview); BLI_listbase_clear(&ma->gpumaterial); BLI_listbase_clear(&ma->gpumaterialinstancing); @@ -4117,7 +4122,7 @@ static void direct_link_pointcache(FileData *fd, PointCache *cache) } else BLI_listbase_clear(&cache->mem_cache); - + cache->flag &= ~PTCACHE_SIMULATION_VALID; cache->simframe = 0; cache->edit = NULL; @@ -4137,7 +4142,7 @@ static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointC cache->step = 1; } } - + *ocache = newdataadr(fd, *ocache); } else if (*ocache) { @@ -4148,7 +4153,7 @@ static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointC (*ocache)->flag |= PTCACHE_DISK_CACHE; (*ocache)->step = 1; } - + ptcaches->first = ptcaches->last = *ocache; } } @@ -4169,16 +4174,16 @@ static void lib_link_particlesettings(FileData *fd, Main *main) lib_link_animdata(fd, &part->id, part->adt); part->ipo = newlibadr_us(fd, part->id.lib, part->ipo); // XXX deprecated - old animation system - + part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob); part->dup_group = newlibadr(fd, part->id.lib, part->dup_group); part->eff_group = newlibadr(fd, part->id.lib, part->eff_group); part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob); part->collision_group = newlibadr(fd, part->id.lib, part->collision_group); - + lib_link_partdeflect(fd, &part->id, part->pd); lib_link_partdeflect(fd, &part->id, part->pd2); - + if (part->effector_weights) { part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group); } @@ -4226,7 +4231,7 @@ static void lib_link_particlesettings(FileData *fd, Main *main) else { BLI_listbase_clear(&part->dupliweights); } - + if (part->boids) { BoidState *state = part->boids->states.first; BoidRule *rule; @@ -4259,7 +4264,7 @@ static void lib_link_particlesettings(FileData *fd, Main *main) mtex->object = newlibadr(fd, part->id.lib, mtex->object); } } - + part->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -4273,7 +4278,7 @@ static void direct_link_partdeflect(PartDeflect *pd) static void direct_link_particlesettings(FileData *fd, ParticleSettings *part) { int a; - + part->adt = newdataadr(fd, part->adt); part->pd = newdataadr(fd, part->pd); part->pd2 = newdataadr(fd, part->pd2); @@ -4304,7 +4309,7 @@ static void direct_link_particlesettings(FileData *fd, ParticleSettings *part) if (part->boids) { BoidState *state; link_list(fd, &part->boids->states); - + for (state=part->boids->states.first; state; state=state->next) { link_list(fd, &state->rules); link_list(fd, &state->conditions); @@ -4325,17 +4330,17 @@ static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase for (psys=particles->first; psys; psys=psysnext) { psysnext = psys->next; - + psys->part = newlibadr_us(fd, id->lib, psys->part); if (psys->part) { ParticleTarget *pt = psys->targets.first; - + for (; pt; pt=pt->next) pt->ob=newlibadr(fd, id->lib, pt->ob); - + psys->parent = newlibadr(fd, id->lib, psys->parent); psys->target_ob = newlibadr(fd, id->lib, psys->target_ob); - + if (psys->clmd) { /* XXX - from reading existing code this seems correct but intended usage of * pointcache /w cloth should be added in 'ParticleSystem' - campbell */ @@ -4350,7 +4355,7 @@ static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); BLI_remlink(&ob->modifiers, psmd); modifier_free((ModifierData *)psmd); - + BLI_remlink(particles, psys); MEM_freeN(psys); } @@ -4361,21 +4366,21 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) ParticleSystem *psys; ParticleData *pa; int a; - + for (psys=particles->first; psys; psys=psys->next) { psys->particles=newdataadr(fd, psys->particles); - + if (psys->particles && psys->particles->hair) { for (a=0, pa=psys->particles; atotpart; a++, pa++) pa->hair=newdataadr(fd, pa->hair); } - + if (psys->particles && psys->particles->keys) { for (a=0, pa=psys->particles; atotpart; a++, pa++) { pa->keys= NULL; pa->totkey= 0; } - + psys->flag &= ~PSYS_KEYED; } @@ -4392,14 +4397,14 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) for (a=0, pa=psys->particles; atotpart; a++, pa++) pa->boid = NULL; } - + psys->fluid_springs = newdataadr(fd, psys->fluid_springs); - + psys->child = newdataadr(fd, psys->child); psys->effectors = NULL; - + link_list(fd, &psys->targets); - + psys->edit = NULL; psys->free_edit = NULL; psys->pathcache = NULL; @@ -4408,21 +4413,21 @@ static void direct_link_particlesystems(FileData *fd, ListBase *particles) BLI_listbase_clear(&psys->childcachebufs); psys->pdd = NULL; psys->renderdata = NULL; - + if (psys->clmd) { psys->clmd = newdataadr(fd, psys->clmd); psys->clmd->clothObject = NULL; psys->clmd->hairdata = NULL; - + psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms); psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms); - + if (psys->clmd->sim_parms) { psys->clmd->sim_parms->effector_weights = NULL; if (psys->clmd->sim_parms->presets > 10) psys->clmd->sim_parms->presets = 0; } - + psys->hair_in_dm = psys->hair_out_dm = NULL; psys->clmd->solver_result = NULL; } @@ -4444,7 +4449,7 @@ static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface) { MTFace *tf= mtface; int i; - + /* Add pseudo-references (not fake users!) to images used by texface. A * little bogus; it would be better if each mesh consistently added one ref * to each image it used. - z0r */ @@ -4458,7 +4463,7 @@ static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata int i; for (i = 0; i < fdata->totlayer; i++) { CustomDataLayer *layer = &fdata->layers[i]; - + if (layer->type == CD_MTFACE) lib_link_mtface(fd, me, layer->data, totface); } @@ -4471,11 +4476,11 @@ static void lib_link_customdata_mtpoly(FileData *fd, Mesh *me, CustomData *pdata for (i=0; i < pdata->totlayer; i++) { CustomDataLayer *layer = &pdata->layers[i]; - + if (layer->type == CD_MTEXPOLY) { MTexPoly *tf= layer->data; int j; - + for (j = 0; j < totface; j++, tf++) { tf->tpage = newlibadr_real_us(fd, me->id.lib, tf->tpage); } @@ -4486,16 +4491,16 @@ static void lib_link_customdata_mtpoly(FileData *fd, Mesh *me, CustomData *pdata static void lib_link_mesh(FileData *fd, Main *main) { Mesh *me; - + for (me = main->mesh.first; me; me = me->id.next) { if (me->id.tag & LIB_TAG_NEED_LINK) { int i; - + /* Link ID Properties -- and copy this comment EXACTLY for easy finding * of library blocks that implement this.*/ IDP_LibLinkProperty(me->id.properties, fd); lib_link_animdata(fd, &me->id, me->adt); - + /* this check added for python created meshes */ if (me->mat) { for (i = 0; i < me->totcol; i++) { @@ -4509,7 +4514,7 @@ static void lib_link_mesh(FileData *fd, Main *main) me->ipo = newlibadr_us(fd, me->id.lib, me->ipo); // XXX: deprecated: old anim sys me->key = newlibadr_us(fd, me->id.lib, me->key); me->texcomesh = newlibadr_us(fd, me->id.lib, me->texcomesh); - + lib_link_customdata_mtface(fd, me, &me->fdata, me->totface); lib_link_customdata_mtpoly(fd, me, &me->pdata, me->totpoly); if (me->mr && me->mr->levels.first) { @@ -4530,9 +4535,9 @@ static void lib_link_mesh(FileData *fd, Main *main) * external CustomData works */ Main *gmain = G_MAIN; G_MAIN = main; - + BKE_mesh_do_versions_convert_mfaces_to_mpolys(me); - + G_MAIN = gmain; } @@ -4560,11 +4565,11 @@ static void lib_link_mesh(FileData *fd, Main *main) static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts) { int i; - + if (mdverts == NULL) { return; } - + for (i = count; i > 0; i--, mdverts++) { /*convert to vgroup allocation system*/ MDeformWeight *dw; @@ -4586,11 +4591,11 @@ static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps, int exte { if (mdisps) { int i; - + for (i = 0; i < count; ++i) { mdisps[i].disps = newdataadr(fd, mdisps[i].disps); mdisps[i].hidden = newdataadr(fd, mdisps[i].hidden); - + if (mdisps[i].totdisp && !mdisps[i].level) { /* this calculation is only correct for loop mdisps; * if loading pre-BMesh face mdisps this will be @@ -4599,7 +4604,7 @@ static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps, int exte float gridsize = sqrtf(mdisps[i].totdisp); mdisps[i].level = (int)(logf(gridsize - 1.0f) / (float)M_LN2) + 1; } - + if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && (mdisps[i].disps)) { /* DNA_struct_switch_endian doesn't do endian swap for (*disps)[] */ /* this does swap for data written at write_mdisps() - readfile.c */ @@ -4615,7 +4620,7 @@ static void direct_link_grid_paint_mask(FileData *fd, int count, GridPaintMask * { if (grid_paint_mask) { int i; - + for (i = 0; i < count; ++i) { GridPaintMask *gpm = &grid_paint_mask[i]; if (gpm->data) @@ -4628,26 +4633,26 @@ static void direct_link_grid_paint_mask(FileData *fd, int count, GridPaintMask * static void direct_link_customdata(FileData *fd, CustomData *data, int count) { int i = 0; - + data->layers = newdataadr(fd, data->layers); - + /* annoying workaround for bug [#31079] loading legacy files with * no polygons _but_ have stale customdata */ if (UNLIKELY(count == 0 && data->layers == NULL && data->totlayer != 0)) { CustomData_reset(data); return; } - + data->external = newdataadr(fd, data->external); - + while (i < data->totlayer) { CustomDataLayer *layer = &data->layers[i]; - + if (layer->flag & CD_FLAG_EXTERNAL) layer->flag &= ~CD_FLAG_IN_MEMORY; layer->flag &= ~CD_FLAG_NOFREE; - + if (CustomData_verify_versions(data, i)) { layer->data = newdataadr(fd, layer->data); if (layer->type == CD_MDISPS) @@ -4657,7 +4662,7 @@ static void direct_link_customdata(FileData *fd, CustomData *data, int count) i++; } } - + CustomData_update_typemap(data); } @@ -4665,7 +4670,7 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) { mesh->mat= newdataadr(fd, mesh->mat); test_pointer_array(fd, (void **)&mesh->mat); - + mesh->mvert = newdataadr(fd, mesh->mvert); mesh->medge = newdataadr(fd, mesh->medge); mesh->mface = newdataadr(fd, mesh->mface); @@ -4679,15 +4684,15 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) mesh->mloopuv = newdataadr(fd, mesh->mloopuv); mesh->mtpoly = newdataadr(fd, mesh->mtpoly); mesh->mselect = newdataadr(fd, mesh->mselect); - + /* animdata */ mesh->adt = newdataadr(fd, mesh->adt); direct_link_animdata(fd, mesh->adt); - + /* normally direct_link_dverts should be called in direct_link_customdata, * but for backwards compat in do_versions to work we do it here */ direct_link_dverts(fd, mesh->totvert, mesh->dvert); - + direct_link_customdata(fd, &mesh->vdata, mesh->totvert); direct_link_customdata(fd, &mesh->edata, mesh->totedge); direct_link_customdata(fd, &mesh->fdata, mesh->totface); @@ -4696,7 +4701,7 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) mesh->bb = NULL; mesh->edit_btmesh = NULL; - + /* happens with old files */ if (mesh->mselect == NULL) { mesh->totselect = 0; @@ -4712,19 +4717,19 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) mesh->mr= newdataadr(fd, mesh->mr); if (mesh->mr) { MultiresLevel *lvl; - + link_list(fd, &mesh->mr->levels); lvl = mesh->mr->levels.first; - + direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert); direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT)); direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface); - + mesh->mr->edge_flags = newdataadr(fd, mesh->mr->edge_flags); mesh->mr->edge_creases = newdataadr(fd, mesh->mr->edge_creases); - + mesh->mr->verts = newdataadr(fd, mesh->mr->verts); - + /* If mesh has the same number of vertices as the * highest multires level, load the current mesh verts * into multires and discard the old data. Needed @@ -4736,7 +4741,7 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) MEM_freeN(mesh->mr->verts); mesh->mr->verts = MEM_dupallocN(mesh->mvert); } - + for (; lvl; lvl = lvl->next) { lvl->verts = newdataadr(fd, lvl->verts); lvl->faces = newdataadr(fd, lvl->faces); @@ -4751,11 +4756,11 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh) multires_free(mesh->mr); mesh->mr = NULL; } - + if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) { TFace *tf = mesh->tface; int i; - + for (i = 0; i < mesh->totface; i++, tf++) { BLI_endian_switch_uint32_array(tf->col, 4); } @@ -4770,10 +4775,10 @@ static void lib_link_latt(FileData *fd, Main *main) if (lt->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(lt->id.properties, fd); lib_link_animdata(fd, <->id, lt->adt); - + lt->ipo = newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX deprecated - old animation system lt->key = newlibadr_us(fd, lt->id.lib, lt->key); - + lt->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -4782,12 +4787,12 @@ static void lib_link_latt(FileData *fd, Main *main) static void direct_link_latt(FileData *fd, Lattice *lt) { lt->def = newdataadr(fd, lt->def); - + lt->dvert = newdataadr(fd, lt->dvert); direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert); - + lt->editlatt = NULL; - + lt->adt = newdataadr(fd, lt->adt); direct_link_animdata(fd, lt->adt); } @@ -4820,7 +4825,7 @@ static void lib_link_object(FileData *fd, Main *main) IDP_LibLinkProperty(ob->id.properties, fd); lib_link_animdata(fd, &ob->id, ob->adt); - + // XXX deprecated - old animation system <<< ob->ipo = newlibadr_us(fd, ob->id.lib, ob->ipo); ob->action = newlibadr_us(fd, ob->id.lib, ob->action); @@ -4830,14 +4835,14 @@ static void lib_link_object(FileData *fd, Main *main) ob->track = newlibadr(fd, ob->id.lib, ob->track); ob->poselib = newlibadr_us(fd, ob->id.lib, ob->poselib); ob->dup_group = newlibadr_us(fd, ob->id.lib, ob->dup_group); - + ob->proxy = newlibadr_us(fd, ob->id.lib, ob->proxy); if (ob->proxy) { /* paranoia check, actually a proxy_from pointer should never be written... */ if (ob->proxy->id.lib == NULL) { ob->proxy->proxy_from = NULL; ob->proxy = NULL; - + if (ob->id.lib) printf("Proxy lost from object %s lib %s\n", ob->id.name + 2, ob->id.lib->name); else @@ -4849,19 +4854,19 @@ static void lib_link_object(FileData *fd, Main *main) } } ob->proxy_group = newlibadr(fd, ob->id.lib, ob->proxy_group); - + void *poin = ob->data; ob->data = newlibadr_us(fd, ob->id.lib, ob->data); - + if (ob->data == NULL && poin != NULL) { if (ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name + 2, ob->id.lib->name); else printf("Object %s lost data.\n", ob->id.name + 2); - + ob->type = OB_EMPTY; warn = true; - + if (ob->pose) { /* we can't call #BKE_pose_free() here because of library linking * freeing will recurse down into every pose constraints ID pointers @@ -4877,9 +4882,9 @@ static void lib_link_object(FileData *fd, Main *main) ob->mode &= ~OB_MODE_POSE; } } - for (a=0; a < ob->totcol; a++) + for (a=0; a < ob->totcol; a++) ob->mat[a] = newlibadr_us(fd, ob->id.lib, ob->mat[a]); - + /* When the object is local and the data is library its possible * the material list size gets out of sync. [#22663] */ if (ob->data && ob->id.lib != ((ID *)ob->data)->lib) { @@ -4890,28 +4895,28 @@ static void lib_link_object(FileData *fd, Main *main) BKE_material_resize_object(main, ob, *totcol_data, false); } } - + ob->gpd = newlibadr_us(fd, ob->id.lib, ob->gpd); ob->duplilist = NULL; - + ob->id.tag &= ~LIB_TAG_NEED_LINK; /* if id.us==0 a new base will be created later on */ - + /* WARNING! Also check expand_object(), should reflect the stuff below. */ lib_link_pose(fd, main, ob, ob->pose); lib_link_constraints(fd, &ob->id, &ob->constraints); - + // XXX deprecated - old animation system <<< lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels); lib_link_nlastrips(fd, &ob->id, &ob->nlastrips); // >>> XXX deprecated - old animation system - + for (PartEff *paf = ob->effect.first; paf; paf = paf->next) { if (paf->type == EFF_PARTICLE) { paf->group = newlibadr_us(fd, ob->id.lib, paf->group); } } - + for (bSensor *sens = ob->sensors.first; sens; sens = sens->next) { for (a = 0; a < sens->totlinks; a++) sens->links[a] = newglobadr(fd, sens->links[a]); @@ -4922,11 +4927,11 @@ static void lib_link_object(FileData *fd, Main *main) newlibadr(fd, ob->id.lib, ms->fromObject); } } - + for (bController *cont = ob->controllers.first; cont; cont = cont->next) { for (a=0; a < cont->totlinks; a++) cont->links[a] = newglobadr(fd, cont->links[a]); - + if (cont->type == CONT_PYTHON) { bPythonCont *pc = cont->data; pc->text = newlibadr(fd, ob->id.lib, pc->text); @@ -4934,7 +4939,7 @@ static void lib_link_object(FileData *fd, Main *main) cont->slinks = NULL; cont->totslinks = 0; } - + for (bActuator *act = ob->actuators.first; act; act = act->next) { switch (act->type) { case ACT_SOUND: @@ -5053,29 +5058,29 @@ static void lib_link_object(FileData *fd, Main *main) { FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - + if (fluidmd && fluidmd->fss) fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, fluidmd->fss->ipo); // XXX deprecated - old animation system } - + { SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke); - + if (smd && (smd->type == MOD_SMOKE_TYPE_DOMAIN) && smd->domain) { smd->domain->flags |= MOD_SMOKE_FILE_LOAD; /* flag for refreshing the simulation after loading */ } } - + /* texture field */ if (ob->pd) lib_link_partdeflect(fd, &ob->id, ob->pd); - + if (ob->soft) { ob->soft->collision_group = newlibadr(fd, ob->id.lib, ob->soft->collision_group); ob->soft->effector_weights->group = newlibadr(fd, ob->id.lib, ob->soft->effector_weights->group); } - + lib_link_particlesystems(fd, ob, &ob->id, &ob->particlesystem); lib_link_modifiers(fd, ob); @@ -5095,7 +5100,7 @@ static void lib_link_object(FileData *fd, Main *main) } } } - + if (warn) { BKE_report(fd->reports, RPT_WARNING, "Warning in console"); } @@ -5120,22 +5125,22 @@ static void direct_link_pose(FileData *fd, bPose *pose) pchan->parent = newdataadr(fd, pchan->parent); pchan->child = newdataadr(fd, pchan->child); pchan->custom_tx = newdataadr(fd, pchan->custom_tx); - + pchan->bbone_prev = newdataadr(fd, pchan->bbone_prev); pchan->bbone_next = newdataadr(fd, pchan->bbone_next); - + direct_link_constraints(fd, &pchan->constraints); - + pchan->prop = newdataadr(fd, pchan->prop); IDP_DirectLinkGroup_OrFree(&pchan->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); - + pchan->mpath = newdataadr(fd, pchan->mpath); if (pchan->mpath) direct_link_motionpath(fd, pchan->mpath); - + BLI_listbase_clear(&pchan->iktree); BLI_listbase_clear(&pchan->siktree); - + /* in case this value changes in future, clamp else we get undefined behavior */ CLAMP(pchan->rotmode, ROT_MODE_MIN, ROT_MODE_MAX); } @@ -5148,56 +5153,56 @@ static void direct_link_pose(FileData *fd, bPose *pose) static void direct_link_modifiers(FileData *fd, ListBase *lb) { ModifierData *md; - + link_list(fd, lb); - + for (md=lb->first; md; md=md->next) { md->error = NULL; md->scene = NULL; - + /* if modifiers disappear, or for upward compatibility */ if (NULL == modifierType_getInfo(md->type)) md->type = eModifierType_None; - + if (md->type == eModifierType_Subsurf) { SubsurfModifierData *smd = (SubsurfModifierData *)md; - + smd->emCache = smd->mCache = NULL; } else if (md->type == eModifierType_Armature) { ArmatureModifierData *amd = (ArmatureModifierData *)md; - + amd->prevCos = NULL; } else if (md->type == eModifierType_Cloth) { ClothModifierData *clmd = (ClothModifierData *)md; - + clmd->clothObject = NULL; clmd->hairdata = NULL; - + clmd->sim_parms= newdataadr(fd, clmd->sim_parms); clmd->coll_parms= newdataadr(fd, clmd->coll_parms); - + direct_link_pointcache_list(fd, &clmd->ptcaches, &clmd->point_cache, 0); - + if (clmd->sim_parms) { if (clmd->sim_parms->presets > 10) clmd->sim_parms->presets = 0; - + clmd->sim_parms->reset = 0; - + clmd->sim_parms->effector_weights = newdataadr(fd, clmd->sim_parms->effector_weights); - + if (!clmd->sim_parms->effector_weights) { clmd->sim_parms->effector_weights = BKE_add_effector_weights(NULL); } } - + clmd->solver_result = NULL; } else if (md->type == eModifierType_Fluidsim) { FluidsimModifierData *fluidmd = (FluidsimModifierData *)md; - + fluidmd->fss = newdataadr(fd, fluidmd->fss); if (fluidmd->fss) { fluidmd->fss->fmd = fluidmd; @@ -5206,13 +5211,13 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_Smoke) { SmokeModifierData *smd = (SmokeModifierData *)md; - + if (smd->type == MOD_SMOKE_TYPE_DOMAIN) { smd->flow = NULL; smd->coll = NULL; smd->domain = newdataadr(fd, smd->domain); smd->domain->smd = smd; - + smd->domain->fluid = NULL; smd->domain->fluid_mutex = BLI_rw_mutex_alloc(); smd->domain->wt = NULL; @@ -5221,13 +5226,13 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) smd->domain->tex_shadow = NULL; smd->domain->tex_wt = NULL; smd->domain->coba = newdataadr(fd, smd->domain->coba); - + smd->domain->effector_weights = newdataadr(fd, smd->domain->effector_weights); if (!smd->domain->effector_weights) smd->domain->effector_weights = BKE_add_effector_weights(NULL); - + direct_link_pointcache_list(fd, &(smd->domain->ptcaches[0]), &(smd->domain->point_cache[0]), 1); - + /* Smoke uses only one cache from now on, so store pointer convert */ if (smd->domain->ptcaches[1].first || smd->domain->point_cache[1]) { if (smd->domain->point_cache[1]) { @@ -5274,22 +5279,22 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_DynamicPaint) { DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md; - + if (pmd->canvas) { pmd->canvas = newdataadr(fd, pmd->canvas); pmd->canvas->pmd = pmd; pmd->canvas->dm = NULL; pmd->canvas->flags &= ~MOD_DPAINT_BAKING; /* just in case */ - + if (pmd->canvas->surfaces.first) { DynamicPaintSurface *surface; link_list(fd, &pmd->canvas->surfaces); - + for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next) { surface->canvas = pmd->canvas; surface->data = NULL; direct_link_pointcache_list(fd, &(surface->ptcaches), &(surface->pointcache), 1); - + if (!(surface->effector_weights = newdataadr(fd, surface->effector_weights))) surface->effector_weights = BKE_add_effector_weights(NULL); } @@ -5307,17 +5312,17 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) else if (md->type == eModifierType_Collision) { CollisionModifierData *collmd = (CollisionModifierData *)md; #if 0 - // TODO: CollisionModifier should use pointcache + // TODO: CollisionModifier should use pointcache // + have proper reset events before enabling this collmd->x = newdataadr(fd, collmd->x); collmd->xnew = newdataadr(fd, collmd->xnew); collmd->mfaces = newdataadr(fd, collmd->mfaces); - + collmd->current_x = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_x"); collmd->current_xnew = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_xnew"); collmd->current_v = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_v"); #endif - + collmd->x = NULL; collmd->xnew = NULL; collmd->current_x = NULL; @@ -5329,11 +5334,11 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) collmd->is_static = false; collmd->bvhtree = NULL; collmd->tri = NULL; - + } else if (md->type == eModifierType_Surface) { SurfaceModifierData *surmd = (SurfaceModifierData *)md; - + surmd->dm = NULL; surmd->bvhtree = NULL; surmd->x = NULL; @@ -5342,7 +5347,7 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_Hook) { HookModifierData *hmd = (HookModifierData *)md; - + hmd->indexar = newdataadr(fd, hmd->indexar); if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { BLI_endian_switch_int32_array(hmd->indexar, hmd->totindex); @@ -5355,7 +5360,7 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_ParticleSystem) { ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md; - + psmd->dm_final = NULL; psmd->dm_deformed = NULL; psmd->psys= newdataadr(fd, psmd->psys); @@ -5364,22 +5369,22 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) } else if (md->type == eModifierType_Explode) { ExplodeModifierData *psmd = (ExplodeModifierData *)md; - + psmd->facepa = NULL; } else if (md->type == eModifierType_MeshDeform) { MeshDeformModifierData *mmd = (MeshDeformModifierData *)md; - + mmd->bindinfluences = newdataadr(fd, mmd->bindinfluences); mmd->bindoffsets = newdataadr(fd, mmd->bindoffsets); mmd->bindcagecos = newdataadr(fd, mmd->bindcagecos); mmd->dyngrid = newdataadr(fd, mmd->dyngrid); mmd->dyninfluences = newdataadr(fd, mmd->dyninfluences); mmd->dynverts = newdataadr(fd, mmd->dynverts); - + mmd->bindweights = newdataadr(fd, mmd->bindweights); mmd->bindcos = newdataadr(fd, mmd->bindcos); - + if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { if (mmd->bindoffsets) BLI_endian_switch_int32_array(mmd->bindoffsets, mmd->totvert + 1); if (mmd->bindcagecos) BLI_endian_switch_float_array(mmd->bindcagecos, mmd->totcagevert * 3); @@ -5391,19 +5396,19 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) else if (md->type == eModifierType_Ocean) { OceanModifierData *omd = (OceanModifierData *)md; omd->oceancache = NULL; - omd->ocean = NULL; - omd->refresh = (MOD_OCEAN_REFRESH_ADD|MOD_OCEAN_REFRESH_RESET|MOD_OCEAN_REFRESH_SIM); + omd->ocean = BKE_ocean_add(); + omd->refresh = MOD_OCEAN_REFRESH_RESET; } else if (md->type == eModifierType_Warp) { WarpModifierData *tmd = (WarpModifierData *)md; - + tmd->curfalloff= newdataadr(fd, tmd->curfalloff); if (tmd->curfalloff) direct_link_curvemapping(fd, tmd->curfalloff); } else if (md->type == eModifierType_WeightVGEdit) { WeightVGEditModifierData *wmd = (WeightVGEditModifierData *)md; - + wmd->cmap_curve = newdataadr(fd, wmd->cmap_curve); if (wmd->cmap_curve) direct_link_curvemapping(fd, wmd->cmap_curve); @@ -5478,7 +5483,7 @@ static void direct_link_object(FileData *fd, Object *ob) bActuator *act; PythonComponent *pc; PythonComponentProperty *cprop; - + /* weak weak... this was only meant as draw flag, now is used in give_base_to_objects too */ ob->flag &= ~OB_FROMGROUP; @@ -5502,30 +5507,30 @@ static void direct_link_object(FileData *fd, Object *ob) ob->mode &= ~OB_MODE_POSE; } } - + ob->adt = newdataadr(fd, ob->adt); direct_link_animdata(fd, ob->adt); - + ob->pose = newdataadr(fd, ob->pose); direct_link_pose(fd, ob->pose); - + ob->mpath = newdataadr(fd, ob->mpath); if (ob->mpath) direct_link_motionpath(fd, ob->mpath); - + link_list(fd, &ob->defbase); // XXX deprecated - old animation system <<< direct_link_nlastrips(fd, &ob->nlastrips); link_list(fd, &ob->constraintChannels); // >>> XXX deprecated - old animation system - + ob->mat= newdataadr(fd, ob->mat); test_pointer_array(fd, (void **)&ob->mat); ob->matbits= newdataadr(fd, ob->matbits); - + /* do it here, below old data gets converted */ direct_link_modifiers(fd, &ob->modifiers); - + link_list(fd, &ob->effect); paf= ob->effect.first; while (paf) { @@ -5536,7 +5541,7 @@ static void direct_link_object(FileData *fd, Object *ob) WaveEff *wav = (WaveEff*) paf; PartEff *next = paf->next; WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave); - + wmd->damp = wav->damp; wmd->flag = wav->flag; wmd->height = wav->height; @@ -5547,12 +5552,12 @@ static void direct_link_object(FileData *fd, Object *ob) wmd->starty = wav->startx; wmd->timeoffs = wav->timeoffs; wmd->width = wav->width; - + BLI_addtail(&ob->modifiers, wmd); - + BLI_remlink(&ob->effect, paf); MEM_freeN(paf); - + paf = next; continue; } @@ -5560,29 +5565,29 @@ static void direct_link_object(FileData *fd, Object *ob) BuildEff *baf = (BuildEff*) paf; PartEff *next = paf->next; BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build); - + bmd->start = baf->sfra; bmd->length = baf->len; bmd->randomize = 0; bmd->seed = 1; - + BLI_addtail(&ob->modifiers, bmd); - + BLI_remlink(&ob->effect, paf); MEM_freeN(paf); - + paf = next; continue; } paf = paf->next; } - + ob->pd= newdataadr(fd, ob->pd); direct_link_partdeflect(ob->pd); ob->soft= newdataadr(fd, ob->soft); if (ob->soft) { SoftBody *sb = ob->soft; - + sb->bpoint = NULL; // init pointers so it gets rebuilt nicely sb->bspring = NULL; sb->scratch = NULL; @@ -5596,22 +5601,22 @@ static void direct_link_object(FileData *fd, Object *ob) sb->keys[a] = newdataadr(fd, sb->keys[a]); } } - + sb->effector_weights = newdataadr(fd, sb->effector_weights); if (!sb->effector_weights) sb->effector_weights = BKE_add_effector_weights(NULL); - + direct_link_pointcache_list(fd, &sb->ptcaches, &sb->pointcache, 0); } ob->bsoft = newdataadr(fd, ob->bsoft); ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */ - + ob->rigidbody_object = newdataadr(fd, ob->rigidbody_object); if (ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - - /* must nullify the references to physics sim objects, since they no-longer exist - * (and will need to be recalculated) + + /* must nullify the references to physics sim objects, since they no-longer exist + * (and will need to be recalculated) */ rbo->physics_object = NULL; rbo->physics_shape = NULL; @@ -5622,11 +5627,11 @@ static void direct_link_object(FileData *fd, Object *ob) link_list(fd, &ob->particlesystem); direct_link_particlesystems(fd, &ob->particlesystem); - + link_list(fd, &ob->prop); for (prop = ob->prop.first; prop; prop = prop->next) { prop->poin = newdataadr(fd, prop->poin); - if (prop->poin == NULL) + if (prop->poin == NULL) prop->poin = &prop->data; } @@ -5682,12 +5687,12 @@ static void direct_link_object(FileData *fd, Object *ob) while (ob->hooks.first) { ObHook *hook = ob->hooks.first; HookModifierData *hmd = (HookModifierData *)modifier_new(eModifierType_Hook); - + hook->indexar= newdataadr(fd, hook->indexar); if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) { BLI_endian_switch_int32_array(hook->indexar, hook->totindex); } - + /* Do conversion here because if we have loaded * a hook we need to make sure it gets converted * and freed, regardless of version. @@ -5699,15 +5704,15 @@ static void direct_link_object(FileData *fd, Object *ob) hmd->object = hook->parent; memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv)); hmd->totindex = hook->totindex; - + BLI_addhead(&ob->modifiers, hmd); BLI_remlink(&ob->hooks, hook); - + modifier_unique_name(&ob->modifiers, (ModifierData*)hmd); - + MEM_freeN(hook); } - + ob->iuser = newdataadr(fd, ob->iuser); if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE && !ob->iuser) { BKE_object_empty_draw_type_set(ob, ob->empty_drawtype); @@ -5742,7 +5747,7 @@ static void direct_link_object(FileData *fd, Object *ob) static void composite_patch(bNodeTree *ntree, Scene *scene) { bNode *node; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->id==NULL && node->type == CMP_NODE_R_LAYERS) node->id = &scene->id; @@ -5804,21 +5809,21 @@ static void lib_link_scene(FileData *fd, Main *main) bool need_check_set = false; int totscene = 0; #endif - + for (Scene *sce = main->scene.first; sce; sce = sce->id.next) { if (sce->id.tag & LIB_TAG_NEED_LINK) { /* Link ID Properties -- and copy this comment EXACTLY for easy finding * of library blocks that implement this.*/ IDP_LibLinkProperty(sce->id.properties, fd); lib_link_animdata(fd, &sce->id, sce->adt); - + lib_link_keyingsets(fd, &sce->id, &sce->keyingsets); - + sce->camera = newlibadr(fd, sce->id.lib, sce->camera); sce->world = newlibadr_us(fd, sce->id.lib, sce->world); sce->set = newlibadr(fd, sce->id.lib, sce->set); sce->gpd = newlibadr_us(fd, sce->id.lib, sce->gpd); - + link_paint(fd, sce, &sce->toolsettings->sculpt->paint); link_paint(fd, sce, &sce->toolsettings->vpaint->paint); link_paint(fd, sce, &sce->toolsettings->wpaint->paint); @@ -5840,16 +5845,16 @@ static void lib_link_scene(FileData *fd, Main *main) if (sce->toolsettings->imapaint.canvas) sce->toolsettings->imapaint.canvas = newlibadr_us(fd, sce->id.lib, sce->toolsettings->imapaint.canvas); - + sce->toolsettings->skgen_template = newlibadr(fd, sce->id.lib, sce->toolsettings->skgen_template); - + sce->toolsettings->particle.shape_object = newlibadr(fd, sce->id.lib, sce->toolsettings->particle.shape_object); - + for (Base *next, *base = sce->base.first; base; base = next) { next = base->next; - + base->object = newlibadr_us(fd, sce->id.lib, base->object); - + if (base->object == NULL) { blo_reportf_wrap(fd->reports, RPT_WARNING, TIP_("LIB: object lost from scene: '%s'"), sce->id.name + 2); @@ -5858,7 +5863,7 @@ static void lib_link_scene(FileData *fd, Main *main) MEM_freeN(base); } } - + Sequence *seq; SEQ_BEGIN (sce->ed, seq) { @@ -5905,11 +5910,11 @@ static void lib_link_scene(FileData *fd, Main *main) marker->camera = newlibadr(fd, sce->id.lib, marker->camera); } } - + BKE_sequencer_update_muting(sce->ed); BKE_sequencer_update_sound_bounds_all(sce); - - + + /* rigidbody world relies on it's linked groups */ if (sce->rigidbody_world) { RigidBodyWorld *rbw = sce->rigidbody_world; @@ -5920,13 +5925,13 @@ static void lib_link_scene(FileData *fd, Main *main) if (rbw->effector_weights) rbw->effector_weights->group = newlibadr(fd, sce->id.lib, rbw->effector_weights->group); } - + if (sce->nodetree) { lib_link_ntree(fd, &sce->id, sce->nodetree); sce->nodetree->id.lib = sce->id.lib; composite_patch(sce->nodetree, sce); } - + for (SceneRenderLayer *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); @@ -5983,9 +5988,9 @@ static void lib_link_scene(FileData *fd, Main *main) static void link_recurs_seq(FileData *fd, ListBase *lb) { Sequence *seq; - + link_list(fd, lb); - + for (seq = lb->first; seq; seq = seq->next) { if (seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase); @@ -6052,7 +6057,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) MetaStack *ms; RigidBodyWorld *rbw; SceneRenderLayer *srl; - + sce->theDag = NULL; sce->depsgraph = NULL; sce->obedit = NULL; @@ -6060,29 +6065,29 @@ static void direct_link_scene(FileData *fd, Scene *sce) sce->fps_info = NULL; sce->customdata_mask_modal = 0; sce->lay_updated = 0; - + BKE_sound_create_scene(sce); - + /* set users to one by default, not in lib-link, this will increase it for compo nodes */ id_us_ensure_real(&sce->id); - + link_list(fd, &(sce->base)); - + sce->adt = newdataadr(fd, sce->adt); direct_link_animdata(fd, sce->adt); - + link_list(fd, &sce->keyingsets); direct_link_keyingsets(fd, &sce->keyingsets); - + sce->basact = newdataadr(fd, sce->basact); - + sce->toolsettings= newdataadr(fd, sce->toolsettings); if (sce->toolsettings) { direct_link_paint_helper(fd, (Paint**)&sce->toolsettings->sculpt); direct_link_paint_helper(fd, (Paint**)&sce->toolsettings->vpaint); direct_link_paint_helper(fd, (Paint**)&sce->toolsettings->wpaint); direct_link_paint_helper(fd, (Paint**)&sce->toolsettings->uvsculpt); - + direct_link_paint(fd, &sce->toolsettings->imapaint.paint); sce->toolsettings->imapaint.paintcursor = NULL; @@ -6090,7 +6095,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) sce->toolsettings->particle.scene = NULL; sce->toolsettings->particle.object = NULL; sce->toolsettings->gp_sculpt.paintcursor = NULL; - + /* relink grease pencil drawing brushes */ link_list(fd, &sce->toolsettings->gp_brushes); for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) { @@ -6107,7 +6112,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) direct_link_curvemapping(fd, brush->cur_jitter); } } - + /* relink grease pencil interpolation curves */ sce->toolsettings->gp_interpolate.custom_ipo = newdataadr(fd, sce->toolsettings->gp_interpolate.custom_ipo); if (sce->toolsettings->gp_interpolate.custom_ipo) { @@ -6117,29 +6122,29 @@ static void direct_link_scene(FileData *fd, Scene *sce) if (sce->ed) { ListBase *old_seqbasep = &sce->ed->seqbase; - + ed = sce->ed = newdataadr(fd, sce->ed); - + ed->act_seq = newdataadr(fd, ed->act_seq); - + /* recursive link sequences, lb will be correctly initialized */ link_recurs_seq(fd, &ed->seqbase); - + SEQ_BEGIN (ed, seq) { seq->seq1= newdataadr(fd, seq->seq1); seq->seq2= newdataadr(fd, seq->seq2); seq->seq3= newdataadr(fd, seq->seq3); - + /* a patch: after introduction of effects with 3 input strips */ if (seq->seq3 == NULL) seq->seq3 = seq->seq2; - + seq->effectdata = newdataadr(fd, seq->effectdata); seq->stereo3d_format = newdataadr(fd, seq->stereo3d_format); - + if (seq->type & SEQ_TYPE_EFFECT) seq->flag |= SEQ_EFFECT_NOT_LOADED; - + if (seq->type == SEQ_TYPE_SPEED) { SpeedControlVars *s = seq->effectdata; s->frameMap = NULL; @@ -6151,7 +6156,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) seq->strip = newdataadr(fd, seq->strip); if (seq->strip && seq->strip->done==0) { seq->strip->done = true; - + if (ELEM(seq->type, SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) { seq->strip->stripdata = newdataadr(fd, seq->strip->stripdata); } @@ -6192,22 +6197,22 @@ static void direct_link_scene(FileData *fd, Scene *sce) direct_link_sequence_modifiers(fd, &seq->modifiers); } SEQ_END - + /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */ { Sequence temp; void *poin; intptr_t offset; - + offset = ((intptr_t)&(temp.seqbase)) - ((intptr_t)&temp); - + /* root pointer */ if (ed->seqbasep == old_seqbasep) { ed->seqbasep = &ed->seqbase; } else { poin = POINTER_OFFSET(ed->seqbasep, -offset); - + poin = newdataadr(fd, poin); if (poin) ed->seqbasep = (ListBase *)POINTER_OFFSET(poin, offset); @@ -6216,18 +6221,18 @@ static void direct_link_scene(FileData *fd, Scene *sce) } /* stack */ link_list(fd, &(ed->metastack)); - + for (ms = ed->metastack.first; ms; ms= ms->next) { ms->parseq = newdataadr(fd, ms->parseq); - + if (ms->oldbasep == old_seqbasep) ms->oldbasep= &ed->seqbase; else { poin = POINTER_OFFSET(ms->oldbasep, -offset); poin = newdataadr(fd, poin); - if (poin) + if (poin) ms->oldbasep = (ListBase *)POINTER_OFFSET(poin, offset); - else + else ms->oldbasep = &ed->seqbase; } } @@ -6248,7 +6253,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) sce->r.ffcodecdata.properties = newdataadr(fd, sce->r.ffcodecdata.properties); IDP_DirectLinkGroup_OrFree(&sce->r.ffcodecdata.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd); } - + link_list(fd, &(sce->markers)); link_list(fd, &(sce->transform_spaces)); link_list(fd, &(sce->r.layers)); @@ -6265,7 +6270,7 @@ static void direct_link_scene(FileData *fd, Scene *sce) 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_id(fd, &sce->nodetree->id); @@ -6273,12 +6278,12 @@ static void direct_link_scene(FileData *fd, Scene *sce) } direct_link_view_settings(fd, &sce->view_settings); - + sce->rigidbody_world = newdataadr(fd, sce->rigidbody_world); rbw = sce->rigidbody_world; if (rbw) { - /* must nullify the reference to physics sim object, since it no-longer exist - * (and will need to be recalculated) + /* must nullify the reference to physics sim object, since it no-longer exist + * (and will need to be recalculated) */ rbw->physics_world = NULL; rbw->objects = NULL; @@ -6307,10 +6312,10 @@ static void direct_link_scene(FileData *fd, Scene *sce) static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm) { wmWindow *win; - + id_us_ensure_real(&wm->id); link_list(fd, &wm->windows); - + for (win = wm->windows.first; win; win = win->next) { win->ghostwin = NULL; win->eventstate = NULL; @@ -6319,14 +6324,14 @@ static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm) #ifdef WIN32 win->ime_data = NULL; #endif - + BLI_listbase_clear(&win->queue); BLI_listbase_clear(&win->handlers); BLI_listbase_clear(&win->modalhandlers); BLI_listbase_clear(&win->subwindows); BLI_listbase_clear(&win->gesture); BLI_listbase_clear(&win->drawdata); - + win->drawmethod = -1; win->drawfail = 0; win->active = 0; @@ -6345,13 +6350,13 @@ static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm) win->stereo3d_format->display_mode = S3D_DISPLAY_ANAGLYPH; } } - + BLI_listbase_clear(&wm->timers); BLI_listbase_clear(&wm->operators); BLI_listbase_clear(&wm->paintcursors); BLI_listbase_clear(&wm->queue); BKE_reports_init(&wm->reports, RPT_STORE); - + BLI_listbase_clear(&wm->keyconfigs); wm->defaultconf = NULL; wm->addonconf = NULL; @@ -6360,7 +6365,7 @@ static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm) BLI_listbase_clear(&wm->jobs); BLI_listbase_clear(&wm->drags); - + wm->windrawable = NULL; wm->winactive = NULL; wm->initialized = 0; @@ -6372,14 +6377,14 @@ static void lib_link_windowmanager(FileData *fd, Main *main) { wmWindowManager *wm; wmWindow *win; - + for (wm = main->wm.first; wm; wm = wm->id.next) { if (wm->id.tag & LIB_TAG_NEED_LINK) { /* Note: WM IDProperties are never written to file, hence no need to read/link them here. */ for (win = wm->windows.first; win; win = win->next) { win->screen = newlibadr(fd, NULL, win->screen); } - + wm->id.tag &= ~LIB_TAG_NEED_LINK; } } @@ -6411,7 +6416,7 @@ static void direct_link_gpencil(FileData *fd, bGPdata *gpd) /* we must firstly have some grease-pencil data to link! */ if (gpd == NULL) return; - + /* relink animdata */ gpd->adt = newdataadr(fd, gpd->adt); direct_link_animdata(fd, gpd->adt); @@ -6424,21 +6429,21 @@ static void direct_link_gpencil(FileData *fd, bGPdata *gpd) /* relink layers */ link_list(fd, &gpd->layers); - + for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { /* parent */ gpl->parent = newlibadr(fd, gpd->id.lib, gpl->parent); /* relink frames */ link_list(fd, &gpl->frames); gpl->actframe = newdataadr(fd, gpl->actframe); - + for (gpf = gpl->frames.first; gpf; gpf = gpf->next) { /* relink strokes (and their points) */ link_list(fd, &gpf->strokes); - + for (gps = gpf->strokes.first; gps; gps = gps->next) { gps->points = newdataadr(fd, gps->points); - + /* the triangulation is not saved, so need to be recalculated */ gps->triangles = NULL; gps->tot_triangles = 0; @@ -6453,7 +6458,7 @@ static void direct_link_gpencil(FileData *fd, bGPdata *gpd) /* ****************** READ SCREEN ***************** */ -/* note: file read without screens option G_FILE_NO_UI; +/* note: file read without screens option G_FILE_NO_UI; * check lib pointers in call below */ static void lib_link_screen(FileData *fd, Main *main) { @@ -6472,10 +6477,10 @@ static void lib_link_screen(FileData *fd, Main *main) sc->animtimer = NULL; /* saved in rare cases */ sc->tool_tip = NULL; sc->scrubbing = false; - + for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) { sa->full = newlibadr(fd, sc->id.lib, sa->full); - + for (SpaceLink *sl = sa->spacedata.first; sl; sl= sl->next) { switch (sl->spacetype) { case SPACE_VIEW3D: @@ -6793,34 +6798,34 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc for (wm = newmain->wm.first; wm; wm = wm->id.next) { for (win= wm->windows.first; win; win= win->next) { win->screen = restore_pointer_by_name(id_map, (ID *)win->screen, USER_REAL); - + if (win->screen == NULL) win->screen = curscreen; - + win->screen->winid = win->winid; } } - - + + for (sc = newmain->screen.first; sc; sc = sc->id.next) { Scene *oldscene = sc->scene; - + sc->scene= restore_pointer_by_name(id_map, (ID *)sc->scene, USER_REAL); if (sc->scene == NULL) sc->scene = curscene; - + /* keep cursor location through undo */ copy_v3_v3(sc->scene->cursor, oldscene->cursor); - + for (sa = sc->areabase.first; sa; sa = sa->next) { SpaceLink *sl; - + for (sl = sa->spacedata.first; sl; sl = sl->next) { if (sl->spacetype == SPACE_VIEW3D) { View3D *v3d = (View3D *)sl; BGpic *bgpic; ARegion *ar; - + if (v3d->scenelock) v3d->camera = NULL; /* always get from scene */ else @@ -6828,7 +6833,7 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc if (v3d->camera == NULL) v3d->camera = sc->scene->camera; v3d->ob_centre = restore_pointer_by_name(id_map, (ID *)v3d->ob_centre, USER_REAL); - + for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) { if ((bgpic->ima = restore_pointer_by_name(id_map, (ID *)bgpic->ima, USER_IGNORE))) { id_us_plus((ID *)bgpic->ima); @@ -6839,9 +6844,9 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } if (v3d->localvd) { /*Base *base;*/ - + v3d->localvd->camera = sc->scene->camera; - + /* localview can become invalid during undo/redo steps, so we exit it when no could be found */ #if 0 /* XXX regionlocalview ? */ for (base= sc->scene->base.first; base; base= base->next) { @@ -6850,7 +6855,7 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc if (base==NULL) { v3d->lay= v3d->localvd->lay; v3d->layact= v3d->localvd->layact; - MEM_freeN(v3d->localvd); + MEM_freeN(v3d->localvd); v3d->localvd= NULL; } #endif @@ -6858,7 +6863,7 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc else if (v3d->scenelock) { v3d->lay = sc->scene->lay; } - + /* not very nice, but could help */ if ((v3d->layact & v3d->lay) == 0) v3d->layact = v3d->lay; @@ -6876,14 +6881,14 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc else if (sl->spacetype == SPACE_IPO) { SpaceIpo *sipo = (SpaceIpo *)sl; bDopeSheet *ads = sipo->ads; - + if (ads) { ads->source = restore_pointer_by_name(id_map, (ID *)ads->source, USER_REAL); - + if (ads->filter_grp) ads->filter_grp = restore_pointer_by_name(id_map, (ID *)ads->filter_grp, USER_IGNORE); } - + /* force recalc of list of channels (i.e. includes calculating F-Curve colors) * thus preventing the "black curves" problem post-undo */ @@ -6907,28 +6912,28 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } else if (sl->spacetype == SPACE_ACTION) { SpaceAction *saction = (SpaceAction *)sl; - + saction->action = restore_pointer_by_name(id_map, (ID *)saction->action, USER_REAL); saction->ads.source = restore_pointer_by_name(id_map, (ID *)saction->ads.source, USER_REAL); - + if (saction->ads.filter_grp) saction->ads.filter_grp = restore_pointer_by_name(id_map, (ID *)saction->ads.filter_grp, USER_IGNORE); - - - /* force recalc of list of channels, potentially updating the active action - * while we're at it (as it can only be updated that way) [#28962] + + + /* force recalc of list of channels, potentially updating the active action + * while we're at it (as it can only be updated that way) [#28962] */ saction->flag |= SACTION_TEMP_NEEDCHANSYNC; } else if (sl->spacetype == SPACE_IMAGE) { SpaceImage *sima = (SpaceImage *)sl; - + sima->image = restore_pointer_by_name(id_map, (ID *)sima->image, USER_REAL); - + /* this will be freed, not worth attempting to find same scene, * since it gets initialized later */ sima->iuser.scene = NULL; - + #if 0 /* Those are allocated and freed by space code, no need to handle them here. */ MEM_SAFE_FREE(sima->scopes.waveform_1); @@ -6937,7 +6942,7 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc MEM_SAFE_FREE(sima->scopes.vecscope); #endif sima->scopes.ok = 0; - + /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data * so assume that here we're doing for undo only... */ @@ -6946,7 +6951,7 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } else if (sl->spacetype == SPACE_SEQ) { SpaceSeq *sseq = (SpaceSeq *)sl; - + /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data * so assume that here we're doing for undo only... */ @@ -6955,25 +6960,25 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc else if (sl->spacetype == SPACE_NLA) { SpaceNla *snla = (SpaceNla *)sl; bDopeSheet *ads = snla->ads; - + if (ads) { ads->source = restore_pointer_by_name(id_map, (ID *)ads->source, USER_REAL); - + if (ads->filter_grp) ads->filter_grp = restore_pointer_by_name(id_map, (ID *)ads->filter_grp, USER_IGNORE); } } else if (sl->spacetype == SPACE_TEXT) { SpaceText *st = (SpaceText *)sl; - + st->text = restore_pointer_by_name(id_map, (ID *)st->text, USER_REAL); if (st->text == NULL) st->text = newmain->text.first; } else if (sl->spacetype == SPACE_SCRIPT) { SpaceScript *scpt = (SpaceScript *)sl; - + scpt->script = restore_pointer_by_name(id_map, (ID *)scpt->script, USER_REAL); - + /*sc->script = NULL; - 2.45 set to null, better re-run the script */ if (scpt->script) { SCRIPT_SET_NULL(scpt->script); @@ -6981,9 +6986,9 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } else if (sl->spacetype == SPACE_OUTLINER) { SpaceOops *so= (SpaceOops *)sl; - + so->search_tse.id = restore_pointer_by_name(id_map, so->search_tse.id, USER_IGNORE); - + if (so->treestore) { TreeStoreElem *tselem; BLI_mempool_iter iter; @@ -7008,14 +7013,14 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc SpaceNode *snode= (SpaceNode *)sl; bNodeTreePath *path, *path_next; bNodeTree *ntree; - + /* node tree can be stored locally in id too, link this first */ snode->id = restore_pointer_by_name(id_map, snode->id, USER_REAL); snode->from = restore_pointer_by_name(id_map, snode->from, USER_IGNORE); - + ntree = snode->id ? ntreeFromID(snode->id) : NULL; snode->nodetree = ntree ? ntree : restore_pointer_by_name(id_map, (ID *)snode->nodetree, USER_REAL); - + for (path = snode->treepath.first; path; path = path->next) { if (path == snode->treepath.first) { /* first nodetree in path is same as snode->nodetree */ @@ -7023,19 +7028,19 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } else path->nodetree= restore_pointer_by_name(id_map, (ID*)path->nodetree, USER_REAL); - + if (!path->nodetree) break; } - + /* remaining path entries are invalid, remove */ for (; path; path = path_next) { path_next = path->next; - + BLI_remlink(&snode->treepath, path); MEM_freeN(path); } - + /* edittree is just the last in the path, * set this directly since the path may have been shortened above */ if (snode->treepath.last) { @@ -7047,15 +7052,15 @@ void blo_lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *cursc } else if (sl->spacetype == SPACE_CLIP) { SpaceClip *sclip = (SpaceClip *)sl; - + sclip->clip = restore_pointer_by_name(id_map, (ID *)sclip->clip, USER_REAL); sclip->mask_info.mask = restore_pointer_by_name(id_map, (ID *)sclip->mask_info.mask, USER_REAL); - + sclip->scopes.ok = 0; } else if (sl->spacetype == SPACE_LOGIC) { SpaceLogic *slogic = (SpaceLogic *)sl; - + slogic->gpd = restore_pointer_by_name(id_map, (ID *)slogic->gpd, USER_REAL); } } @@ -7121,7 +7126,7 @@ static void direct_link_region(FileData *fd, ARegion *ar, int spacetype) } } } - + ar->v2d.tab_offset = NULL; ar->v2d.tab_num = 0; ar->v2d.tab_cur = 0; @@ -7143,11 +7148,11 @@ static void direct_link_region(FileData *fd, ARegion *ar, int spacetype) void blo_do_versions_view3d_split_250(View3D *v3d, ListBase *regions) { ARegion *ar; - + for (ar = regions->first; ar; ar = ar->next) { if (ar->regiontype==RGN_TYPE_WINDOW && ar->regiondata==NULL) { RegionView3D *rv3d; - + rv3d = ar->regiondata = MEM_callocN(sizeof(RegionView3D), "region v3d patch"); rv3d->persp = (char)v3d->persp; rv3d->view = (char)v3d->view; @@ -7156,7 +7161,7 @@ void blo_do_versions_view3d_split_250(View3D *v3d, ListBase *regions) copy_qt_qt(rv3d->viewquat, v3d->viewquat); } } - + /* this was not initialized correct always */ if (v3d->twtype == 0) v3d->twtype = V3D_MANIP_TRANSLATE; @@ -7170,13 +7175,13 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) ScrVert *sv; ScrEdge *se; bool wrong_id = false; - + link_list(fd, &(sc->vertbase)); link_list(fd, &(sc->edgebase)); link_list(fd, &(sc->areabase)); sc->regionbase.first = sc->regionbase.last= NULL; sc->context = NULL; - + sc->mainwin = sc->subwinactive= 0; /* indices */ sc->swap = 0; @@ -7189,22 +7194,22 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) se->v1 = se->v2; se->v2 = sv; } - + if (se->v1 == NULL) { printf("Error reading Screen %s... removing it.\n", sc->id.name+2); BLI_remlink(&sc->edgebase, se); wrong_id = true; } } - + /* areas */ for (sa = sc->areabase.first; sa; sa = sa->next) { SpaceLink *sl; ARegion *ar; - + link_list(fd, &(sa->spacedata)); link_list(fd, &(sa->regionbase)); - + BLI_listbase_clear(&sa->handlers); sa->type = NULL; /* spacetype callbacks */ sa->region_active_win = -1; @@ -7213,10 +7218,10 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) * free it, so don't allocate any new memory for such spacetypes. */ if (!BKE_spacetype_exists(sa->spacetype)) sa->spacetype = SPACE_EMPTY; - + for (ar = sa->regionbase.first; ar; ar = ar->next) direct_link_region(fd, ar, sa->spacetype); - + /* accident can happen when read/save new file with older version */ /* 2.50: we now always add spacedata for info */ if (sa->spacedata.first==NULL) { @@ -7241,25 +7246,25 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) for (ar = sl->regionbase.first; ar; ar = ar->next) direct_link_region(fd, ar, sl->spacetype); - + if (sl->spacetype == SPACE_VIEW3D) { View3D *v3d= (View3D*) sl; BGpic *bgpic; - + v3d->flag |= V3D_INVALID_BACKBUF; - + link_list(fd, &v3d->bgpicbase); - + /* should be do_versions except this doesnt fit well there */ if (v3d->bgpic) { bgpic = newdataadr(fd, v3d->bgpic); BLI_addtail(&v3d->bgpicbase, bgpic); v3d->bgpic = NULL; } - + for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) bgpic->iuser.ok = 1; - + if (v3d->gpd) { v3d->gpd = newdataadr(fd, v3d->gpd); direct_link_gpencil(fd, v3d->gpd); @@ -7270,7 +7275,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) BLI_listbase_clear(&v3d->afterdraw_xraytransp); v3d->properties_storage = NULL; v3d->defmaterial = NULL; - + /* render can be quite heavy, set to solid on load */ if (v3d->drawtype == OB_RENDER) v3d->drawtype = OB_SOLID; @@ -7280,23 +7285,23 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) v3d->fx_settings.dof = newdataadr(fd, v3d->fx_settings.dof); if (v3d->fx_settings.ssao) v3d->fx_settings.ssao = newdataadr(fd, v3d->fx_settings.ssao); - + blo_do_versions_view3d_split_250(v3d, &sl->regionbase); } else if (sl->spacetype == SPACE_IPO) { SpaceIpo *sipo = (SpaceIpo *)sl; - + sipo->ads = newdataadr(fd, sipo->ads); BLI_listbase_clear(&sipo->ghostCurves); } else if (sl->spacetype == SPACE_NLA) { SpaceNla *snla = (SpaceNla *)sl; - + snla->ads = newdataadr(fd, snla->ads); } else if (sl->spacetype == SPACE_OUTLINER) { SpaceOops *soops = (SpaceOops *) sl; - + /* use newdataadr_no_us and do not free old memory avoiding double * frees and use of freed memory. this could happen because of a * bug fixed in revision 58959 where the treestore memory address @@ -7305,7 +7310,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) soops->treestore = NULL; if (ts) { TreeStoreElem *elems = newdataadr_no_us(fd, ts->data); - + soops->treestore = BLI_mempool_create(sizeof(TreeStoreElem), ts->usedelem, 512, BLI_MEMPOOL_ALLOW_ITER); if (ts->usedelem && elems) { @@ -7331,8 +7336,8 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) sima->scopes.waveform_3 = NULL; sima->scopes.vecscope = NULL; sima->scopes.ok = 0; - - /* WARNING: gpencil data is no longer stored directly in sima after 2.5 + + /* WARNING: gpencil data is no longer stored directly in sima after 2.5 * so sacrifice a few old files for now to avoid crashes with new files! * committed: r28002 */ #if 0 @@ -7343,12 +7348,12 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_NODE) { SpaceNode *snode = (SpaceNode *)sl; - + if (snode->gpd) { snode->gpd = newdataadr(fd, snode->gpd); direct_link_gpencil(fd, snode->gpd); } - + link_list(fd, &snode->treepath); snode->edittree = NULL; snode->iofsd = NULL; @@ -7356,7 +7361,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_TEXT) { SpaceText *st= (SpaceText *)sl; - + st->drawcache = NULL; st->scroll_accum[0] = 0.0f; st->scroll_accum[1] = 0.0f; @@ -7367,7 +7372,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_LOGIC) { SpaceLogic *slogic = (SpaceLogic *)sl; - + /* XXX: this is new stuff, which shouldn't be directly linking to gpd... */ if (slogic->gpd) { slogic->gpd = newdataadr(fd, slogic->gpd); @@ -7376,7 +7381,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_SEQ) { SpaceSeq *sseq = (SpaceSeq *)sl; - + /* grease pencil data is not a direct data and can't be linked from direct_link* * functions, it should be linked from lib_link* functions instead * @@ -7400,7 +7405,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_BUTS) { SpaceButs *sbuts = (SpaceButs *)sl; - + sbuts->path= NULL; sbuts->texuser= NULL; sbuts->mainbo = sbuts->mainb; @@ -7409,13 +7414,13 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) else if (sl->spacetype == SPACE_CONSOLE) { SpaceConsole *sconsole = (SpaceConsole *)sl; ConsoleLine *cl, *cl_next; - + link_list(fd, &sconsole->scrollback); link_list(fd, &sconsole->history); - + //for (cl= sconsole->scrollback.first; cl; cl= cl->next) // cl->line= newdataadr(fd, cl->line); - + /* comma expressions, (e.g. expr1, expr2, expr3) evaluate each expression, * from left to right. the right-most expression sets the result of the comma * expression as a whole*/ @@ -7434,7 +7439,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_FILE) { SpaceFile *sfile = (SpaceFile *)sl; - + /* this sort of info is probably irrelevant for reloading... * plus, it isn't saved to files yet! */ @@ -7447,21 +7452,21 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) } else if (sl->spacetype == SPACE_CLIP) { SpaceClip *sclip = (SpaceClip *)sl; - + sclip->scopes.track_search = NULL; sclip->scopes.track_preview = NULL; sclip->scopes.ok = 0; } } - + BLI_listbase_clear(&sa->actionzones); - + sa->v1 = newdataadr(fd, sa->v1); sa->v2 = newdataadr(fd, sa->v2); sa->v3 = newdataadr(fd, sa->v3); sa->v4 = newdataadr(fd, sa->v4); } - + return wrong_id; } @@ -7471,7 +7476,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc) static void direct_link_library(FileData *fd, Library *lib, Main *main) { Main *newmain; - + /* check if the library was already read */ for (newmain = fd->mainlist->first; newmain; newmain = newmain->next) { if (newmain->curlib) { @@ -7479,10 +7484,10 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main) blo_reportf_wrap(fd->reports, RPT_WARNING, TIP_("Library '%s', '%s' had multiple instances, save and reload!"), lib->name, lib->filepath); - + change_idid_adr(fd->mainlist, fd, lib, newmain->curlib); /* change_idid_adr_fd(fd, lib, newmain->curlib); */ - + BLI_remlink(&main->library, lib); MEM_freeN(lib); @@ -7502,17 +7507,17 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main) /* make sure we have full path in lib->filepath */ BLI_strncpy(lib->filepath, lib->name, sizeof(lib->name)); BLI_cleanup_path(fd->relabase, lib->filepath); - + // printf("direct_link_library: name %s\n", lib->name); // printf("direct_link_library: filepath %s\n", lib->filepath); - + lib->packedfile = direct_link_packedfile(fd, lib->packedfile); - + /* new main */ newmain = BKE_main_new(); BLI_addtail(fd->mainlist, newmain); newmain->curlib = lib; - + lib->parent = NULL; } @@ -7561,7 +7566,7 @@ static void lib_link_speaker(FileData *fd, Main *main) if (spk->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(spk->id.properties, fd); lib_link_animdata(fd, &spk->id, spk->adt); - + spk->sound = newlibadr_us(fd, spk->id.lib, spk->sound); spk->id.tag &= ~LIB_TAG_NEED_LINK; @@ -7584,6 +7589,7 @@ static void direct_link_speaker(FileData *fd, Speaker *spk) static void direct_link_sound(FileData *fd, bSound *sound) { + sound->tags = 0; sound->handle = NULL; sound->playback_handle = NULL; @@ -7595,17 +7601,18 @@ static void direct_link_sound(FileData *fd, bSound *sound) if (fd->soundmap) { sound->waveform = newsoundadr(fd, sound->waveform); - } + sound->tags |= SOUND_TAGS_WAVEFORM_NO_RELOAD; + } else { sound->waveform = NULL; } - + if (sound->spinlock) { sound->spinlock = MEM_mallocN(sizeof(SpinLock), "sound_spinlock"); BLI_spin_init(sound->spinlock); } /* clear waveform loading flag */ - sound->flags &= ~SOUND_FLAGS_WAVEFORM_LOADING; + sound->tags &= ~SOUND_TAGS_WAVEFORM_LOADING; sound->packedfile = direct_link_packedfile(fd, sound->packedfile); sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile); @@ -7618,7 +7625,7 @@ static void lib_link_sound(FileData *fd, Main *main) IDP_LibLinkProperty(sound->id.properties, fd); sound->ipo = newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX deprecated - old animation system - + BKE_sound_load(main, sound); sound->id.tag &= ~LIB_TAG_NEED_LINK; @@ -7639,9 +7646,9 @@ static void lib_link_group(FileData *fd, Main *bmain) for (Group *group = bmain->group.first; group; group = group->id.next) { if (group->id.tag & LIB_TAG_NEED_LINK) { IDP_LibLinkProperty(group->id.properties, fd); - + bool add_us = false; - + for (GroupObject *go = group->gobject.first; go; go = go->next) { go->ob = newlibadr_real_us(fd, group->id.lib, go->ob); if (go->ob) { @@ -7670,9 +7677,9 @@ static void direct_link_movieReconstruction(FileData *fd, MovieTrackingReconstru static void direct_link_movieTracks(FileData *fd, ListBase *tracksbase) { MovieTrackingTrack *track; - + link_list(fd, tracksbase); - + for (track = tracksbase->first; track; track = track->next) { track->markers = newdataadr(fd, track->markers); } @@ -7732,7 +7739,7 @@ static void direct_link_movieclip(FileData *fd, MovieClip *clip) BLI_listbase_clear(&clip->tracking.dopesheet.coverage_segments); link_list(fd, &tracking->objects); - + for (object = tracking->objects.first; object; object = object->next) { direct_link_movieTracks(fd, &object->tracks); direct_link_moviePlaneTracks(fd, &object->plane_tracks); @@ -7766,9 +7773,9 @@ static void lib_link_movieclip(FileData *fd, Main *main) IDP_LibLinkProperty(clip->id.properties, fd); lib_link_animdata(fd, &clip->id, clip->adt); - + clip->gpd = newlibadr_us(fd, clip->id.lib, clip->gpd); - + lib_link_movieTracks(fd, clip, &tracking->tracks); lib_link_moviePlaneTracks(fd, clip, &tracking->plane_tracks); @@ -7891,32 +7898,32 @@ static void lib_link_linestyle(FileData *fd, Main *main) 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; + 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; + 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; + case LS_MODIFIER_DISTANCE_FROM_OBJECT: + { + LineStyleThicknessModifier_DistanceFromObject *tm = (LineStyleThicknessModifier_DistanceFromObject *)m; + tm->target = newlibadr(fd, linestyle->id.lib, tm->target); + } + break; } } for (int a = 0; a < MAX_MTEX; a++) { @@ -7939,171 +7946,171 @@ static void lib_link_linestyle(FileData *fd, Main *main) 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; - case LS_MODIFIER_TANGENT: - { - LineStyleColorModifier_Tangent *m = (LineStyleColorModifier_Tangent *)modifier; - m->color_ramp = newdataadr(fd, m->color_ramp); - } - break; - case LS_MODIFIER_NOISE: - { - LineStyleColorModifier_Noise *m = (LineStyleColorModifier_Noise *)modifier; - m->color_ramp = newdataadr(fd, m->color_ramp); - } - break; - case LS_MODIFIER_CREASE_ANGLE: - { - LineStyleColorModifier_CreaseAngle *m = (LineStyleColorModifier_CreaseAngle *)modifier; - m->color_ramp = newdataadr(fd, m->color_ramp); - } - break; - case LS_MODIFIER_CURVATURE_3D: - { - LineStyleColorModifier_Curvature_3D *m = (LineStyleColorModifier_Curvature_3D *)modifier; - m->color_ramp = newdataadr(fd, m->color_ramp); - } - break; + 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; + case LS_MODIFIER_TANGENT: + { + LineStyleColorModifier_Tangent *m = (LineStyleColorModifier_Tangent *)modifier; + m->color_ramp = newdataadr(fd, m->color_ramp); + } + break; + case LS_MODIFIER_NOISE: + { + LineStyleColorModifier_Noise *m = (LineStyleColorModifier_Noise *)modifier; + m->color_ramp = newdataadr(fd, m->color_ramp); + } + break; + case LS_MODIFIER_CREASE_ANGLE: + { + LineStyleColorModifier_CreaseAngle *m = (LineStyleColorModifier_CreaseAngle *)modifier; + m->color_ramp = newdataadr(fd, m->color_ramp); + } + break; + case LS_MODIFIER_CURVATURE_3D: + { + LineStyleColorModifier_Curvature_3D *m = (LineStyleColorModifier_Curvature_3D *)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; - case LS_MODIFIER_TANGENT: - { - LineStyleAlphaModifier_Tangent *m = (LineStyleAlphaModifier_Tangent *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; - case LS_MODIFIER_NOISE: - { - LineStyleAlphaModifier_Noise *m = (LineStyleAlphaModifier_Noise *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; - case LS_MODIFIER_CREASE_ANGLE: - { - LineStyleAlphaModifier_CreaseAngle *m = (LineStyleAlphaModifier_CreaseAngle *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; - case LS_MODIFIER_CURVATURE_3D: - { - LineStyleAlphaModifier_Curvature_3D *m = (LineStyleAlphaModifier_Curvature_3D *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; + 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; + case LS_MODIFIER_TANGENT: + { + LineStyleAlphaModifier_Tangent *m = (LineStyleAlphaModifier_Tangent *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; + case LS_MODIFIER_NOISE: + { + LineStyleAlphaModifier_Noise *m = (LineStyleAlphaModifier_Noise *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; + case LS_MODIFIER_CREASE_ANGLE: + { + LineStyleAlphaModifier_CreaseAngle *m = (LineStyleAlphaModifier_CreaseAngle *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; + case LS_MODIFIER_CURVATURE_3D: + { + LineStyleAlphaModifier_Curvature_3D *m = (LineStyleAlphaModifier_Curvature_3D *)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; - case LS_MODIFIER_TANGENT: - { - LineStyleThicknessModifier_Tangent *m = (LineStyleThicknessModifier_Tangent *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; - case LS_MODIFIER_CREASE_ANGLE: - { - LineStyleThicknessModifier_CreaseAngle *m = (LineStyleThicknessModifier_CreaseAngle *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; - case LS_MODIFIER_CURVATURE_3D: - { - LineStyleThicknessModifier_Curvature_3D *m = (LineStyleThicknessModifier_Curvature_3D *)modifier; - m->curve = newdataadr(fd, m->curve); - direct_link_curvemapping(fd, m->curve); - } - break; + 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; + case LS_MODIFIER_TANGENT: + { + LineStyleThicknessModifier_Tangent *m = (LineStyleThicknessModifier_Tangent *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; + case LS_MODIFIER_CREASE_ANGLE: + { + LineStyleThicknessModifier_CreaseAngle *m = (LineStyleThicknessModifier_CreaseAngle *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; + case LS_MODIFIER_CURVATURE_3D: + { + LineStyleThicknessModifier_Curvature_3D *m = (LineStyleThicknessModifier_Curvature_3D *)modifier; + m->curve = newdataadr(fd, m->curve); + direct_link_curvemapping(fd, m->curve); + } + break; } } @@ -8182,13 +8189,13 @@ static const char *dataname(short id_code) case ID_CF: return "Data from CF"; } return "Data from Lib Block"; - + } static BHead *read_data_into_oldnewmap(FileData *fd, BHead *bhead, const char *allocname) { bhead = blo_nextbhead(fd, bhead); - + while (bhead && bhead->code==DATA) { void *data; #if 0 @@ -8201,14 +8208,14 @@ static BHead *read_data_into_oldnewmap(FileData *fd, BHead *bhead, const char *a #else data = read_struct(fd, bhead, allocname); #endif - + if (data) { oldnewmap_insert(fd->datamap, bhead->old, data, 0); } - + bhead = blo_nextbhead(fd, bhead); } - + return bhead; } @@ -8297,13 +8304,13 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short *r_id = id; if (!id) return blo_nextbhead(fd, bhead); - + id->lib = main->curlib; id->us = ID_FAKE_USERS(id); id->icon_id = 0; id->newid = NULL; /* Needed because .blend may have been saved with crap value here... */ id->recalc = 0; - + /* this case cannot be direct_linked: it's just the ID part */ if (bhead->code == ID_ID) { /* That way, we know which datablock needs do_versions (required currently for linking). */ @@ -8314,10 +8321,10 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short /* need a name for the mallocN, just for debugging and sane prints on leaks */ allocname = dataname(GS(id->name)); - + /* read all data into fd->datamap */ bhead = read_data_into_oldnewmap(fd, bhead, allocname); - + /* init pointers direct data */ direct_link_id(fd, id); @@ -8429,14 +8436,14 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short direct_link_cachefile(fd, (CacheFile *)id); break; } - + oldnewmap_free_unused(fd->datamap); oldnewmap_clear(fd->datamap); - + if (wrong_id) { BKE_libblock_free(main, id); } - + return (bhead); } @@ -8445,7 +8452,7 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short static BHead *read_global(BlendFileData *bfd, FileData *fd, BHead *bhead) { FileGlobal *fg = read_struct(fd, bhead, "Global"); - + /* copy to bfd handle */ bfd->main->subversionfile = fg->subversion; bfd->main->upbgeversionfile = fg->upbgeversion; @@ -8454,33 +8461,33 @@ static BHead *read_global(BlendFileData *bfd, FileData *fd, BHead *bhead) bfd->main->minsubversionfile = fg->minsubversion; bfd->main->build_commit_timestamp = fg->build_commit_timestamp; BLI_strncpy(bfd->main->build_hash, fg->build_hash, sizeof(bfd->main->build_hash)); - + bfd->fileflags = fg->fileflags; bfd->globalf = fg->globalf; BLI_strncpy(bfd->filename, fg->filename, sizeof(bfd->filename)); - + /* error in 2.65 and older: main->name was not set if you save from startup (not after loading file) */ if (bfd->filename[0] == 0) { if (fd->fileversion < 265 || (fd->fileversion == 265 && fg->subversion < 1)) if ((G.fileflags & G_FILE_RECOVER)==0) BLI_strncpy(bfd->filename, BKE_main_blendfile_path(bfd->main), sizeof(bfd->filename)); - + /* early 2.50 version patch - filename not in FileGlobal struct at all */ if (fd->fileversion <= 250) BLI_strncpy(bfd->filename, BKE_main_blendfile_path(bfd->main), sizeof(bfd->filename)); } - + if (G.fileflags & G_FILE_RECOVER) BLI_strncpy(fd->relabase, fg->filename, sizeof(fd->relabase)); - + bfd->curscreen = fg->curscreen; bfd->curscene = fg->curscene; - + MEM_freeN(fg); - + fd->globalf = bfd->globalf; fd->fileflags = bfd->fileflags; - + return blo_nextbhead(fd, bhead); } @@ -8498,7 +8505,7 @@ static void link_global(FileData *fd, BlendFileData *bfd) static void convert_tface_mt(FileData *fd, Main *main) { Main *gmain; - + /* this is a delayed do_version (so it can create new materials) */ if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 3)) { //XXX hack, material.c uses G_MAIN all over the place, instead of main @@ -8506,11 +8513,11 @@ static void convert_tface_mt(FileData *fd, Main *main) // temporarily set G_MAIN to the current main gmain = G_MAIN; G_MAIN = main; - + if (!(do_version_tface(main))) { BKE_report(fd->reports, RPT_WARNING, "Texface conversion problem (see error in console)"); } - + //XXX hack, material.c uses G_MAIN allover the place, instead of main G_MAIN = gmain; } @@ -8522,12 +8529,12 @@ static void do_versions_userdef(FileData *fd, BlendFileData *bfd) { Main *bmain = bfd->main; UserDef *user = bfd->user; - + if (user == NULL) return; - + if (MAIN_VERSION_OLDER(bmain, 266, 4)) { bTheme *btheme; - + /* themes for Node and Sequence editor were not using grid color, but back. we copy this over then */ for (btheme = user->themes.first; btheme; btheme = btheme->next) { copy_v4_v4_char(btheme->tnode.grid, btheme->tnode.back); @@ -8548,7 +8555,7 @@ static void do_versions_userdef(FileData *fd, BlendFileData *bfd) static void do_versions(FileData *fd, Library *lib, Main *main) { /* WATCH IT!!!: pointers from libdata have not been converted */ - + if (G.debug & G_DEBUG) { char build_commit_datetime[32]; time_t temp_time = main->build_commit_timestamp; @@ -8564,7 +8571,7 @@ static void do_versions(FileData *fd, Library *lib, Main *main) fd->relabase, main->versionfile, main->subversionfile, build_commit_datetime, main->build_hash); } - + blo_do_versions_pre250(fd, lib, main); blo_do_versions_250(fd, lib, main); blo_do_versions_260(fd, lib, main); @@ -8588,7 +8595,7 @@ static void do_versions_after_linking(Main *main) static void lib_link_all(FileData *fd, Main *main) { oldnewmap_sort(fd); - + /* No load UI for undo memfiles */ if (fd->memfile == NULL) { lib_link_windowmanager(fd, main); @@ -8645,22 +8652,22 @@ static BHead *read_userdef(BlendFileData *bfd, FileData *fd, BHead *bhead) wmKeyMapItem *kmi; wmKeyMapDiffItem *kmdi; bAddon *addon; - + bfd->user = user= read_struct(fd, bhead, "user def"); - + /* User struct has separate do-version handling */ user->versionfile = bfd->main->versionfile; user->subversionfile = bfd->main->subversionfile; - + /* read all data into fd->datamap */ bhead = read_data_into_oldnewmap(fd, bhead, "user def"); - + if (user->keymaps.first) { /* backwards compatibility */ user->user_keymaps= user->keymaps; user->keymaps.first= user->keymaps.last= NULL; } - + link_list(fd, &user->themes); link_list(fd, &user->user_keymaps); link_list(fd, &user->addons); @@ -8670,20 +8677,20 @@ static BHead *read_userdef(BlendFileData *bfd, FileData *fd, BHead *bhead) keymap->modal_items= NULL; keymap->poll = NULL; keymap->flag &= ~KEYMAP_UPDATE; - + link_list(fd, &keymap->diff_items); link_list(fd, &keymap->items); - + for (kmdi=keymap->diff_items.first; kmdi; kmdi=kmdi->next) { kmdi->remove_item= newdataadr(fd, kmdi->remove_item); kmdi->add_item= newdataadr(fd, kmdi->add_item); - + if (kmdi->remove_item) direct_link_keymapitem(fd, kmdi->remove_item); if (kmdi->add_item) direct_link_keymapitem(fd, kmdi->add_item); } - + for (kmi=keymap->items.first; kmi; kmi=kmi->next) direct_link_keymapitem(fd, kmi); } @@ -8695,13 +8702,13 @@ static BHead *read_userdef(BlendFileData *bfd, FileData *fd, BHead *bhead) // XXX user->uifonts.first = user->uifonts.last= NULL; - + link_list(fd, &user->uistyles); - + /* free fd->datamap again */ oldnewmap_free_unused(fd->datamap); oldnewmap_clear(fd->datamap); - + return bhead; } @@ -8710,14 +8717,14 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath) BHead *bhead = blo_firstbhead(fd); BlendFileData *bfd; ListBase mainlist = {NULL, NULL}; - + bfd = MEM_callocN(sizeof(BlendFileData), "blendfiledata"); bfd->main = BKE_main_new(); BLI_addtail(&mainlist, bfd->main); fd->mainlist = &mainlist; - + bfd->main->versionfile = fd->fileversion; - + bfd->type = BLENFILETYPE_BLEND; BLI_strncpy(bfd->main->name, filepath, sizeof(bfd->main->name)); @@ -8747,62 +8754,62 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath) while (bhead) { switch (bhead->code) { - case DATA: - case DNA1: - case TEST: /* used as preview since 2.5x */ - case REND: - bhead = blo_nextbhead(fd, bhead); - break; - case GLOB: - bhead = read_global(bfd, fd, bhead); - break; - case USER: - if (fd->skip_flags & BLO_READ_SKIP_USERDEF) { - bhead = blo_nextbhead(fd, bhead); - } - else { - bhead = read_userdef(bfd, fd, bhead); - } - break; - case ENDB: - bhead = NULL; - break; - - case ID_ID: - /* Always adds to the most recently loaded ID_LI block, see direct_link_library. - * This is part of the file format definition. */ - if (fd->skip_flags & BLO_READ_SKIP_DATA) { - bhead = blo_nextbhead(fd, bhead); - } - else { - bhead = read_libblock(fd, mainlist.last, bhead, LIB_TAG_READ | LIB_TAG_EXTERN, NULL); - } - break; - /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */ - case ID_SCRN: - bhead->code = ID_SCR; - /* pass on to default */ - ATTR_FALLTHROUGH; - default: - if (fd->skip_flags & BLO_READ_SKIP_DATA) { + case DATA: + case DNA1: + case TEST: /* used as preview since 2.5x */ + case REND: bhead = blo_nextbhead(fd, bhead); - } - else { - bhead = read_libblock(fd, bfd->main, bhead, LIB_TAG_LOCAL, NULL); - } + break; + case GLOB: + bhead = read_global(bfd, fd, bhead); + break; + case USER: + if (fd->skip_flags & BLO_READ_SKIP_USERDEF) { + bhead = blo_nextbhead(fd, bhead); + } + else { + bhead = read_userdef(bfd, fd, bhead); + } + break; + case ENDB: + bhead = NULL; + break; + + case ID_ID: + /* Always adds to the most recently loaded ID_LI block, see direct_link_library. + * This is part of the file format definition. */ + if (fd->skip_flags & BLO_READ_SKIP_DATA) { + bhead = blo_nextbhead(fd, bhead); + } + else { + bhead = read_libblock(fd, mainlist.last, bhead, LIB_TAG_READ | LIB_TAG_EXTERN, NULL); + } + break; + /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */ + case ID_SCRN: + bhead->code = ID_SCR; + /* pass on to default */ + ATTR_FALLTHROUGH; + default: + if (fd->skip_flags & BLO_READ_SKIP_DATA) { + bhead = blo_nextbhead(fd, bhead); + } + else { + bhead = read_libblock(fd, bfd->main, bhead, LIB_TAG_LOCAL, NULL); + } } } - + /* do before read_libraries, but skip undo case */ if (fd->memfile == NULL) { do_versions(fd, NULL, bfd->main); do_versions_userdef(fd, bfd); } - + read_libraries(fd, &mainlist); - + blo_join_main(&mainlist); - + lib_link_all(fd, bfd->main); /* Skip in undo case. */ @@ -8820,9 +8827,9 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath) lib_verify_nodetree(bfd->main, true); fix_relpaths_library(fd->relabase, bfd->main); /* make all relative paths, relative to the open blend file */ - + link_global(fd, bfd); /* as last */ - + fd->mainlist = NULL; /* Safety, this is local variable, shall not be used afterward. */ return bfd; @@ -8838,7 +8845,7 @@ struct BHeadSort { static int verg_bheadsort(const void *v1, const void *v2) { const struct BHeadSort *x1=v1, *x2=v2; - + if (x1->old > x2->old) return 1; else if (x1->old < x2->old) return -1; return 0; @@ -8849,20 +8856,20 @@ static void sort_bhead_old_map(FileData *fd) BHead *bhead; struct BHeadSort *bhs; int tot = 0; - + for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) tot++; - + fd->tot_bheadmap = tot; if (tot == 0) return; - + bhs = fd->bheadmap = MEM_malloc_arrayN(tot, sizeof(struct BHeadSort), "BHeadSort"); - + for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead), bhs++) { bhs->bhead = bhead; bhs->old = bhead->old; } - + qsort(fd->bheadmap, tot, sizeof(struct BHeadSort), verg_bheadsort); } @@ -8886,19 +8893,19 @@ static BHead *find_bhead(FileData *fd, void *old) BHead *bhead; #endif struct BHeadSort *bhs, bhs_s; - + if (!old) return NULL; if (fd->bheadmap == NULL) sort_bhead_old_map(fd); - + bhs_s.old = old; bhs = bsearch(&bhs_s, fd->bheadmap, fd->tot_bheadmap, sizeof(struct BHeadSort), verg_bheadsort); if (bhs) return bhs->bhead; - + #if 0 for (bhead = blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) { if (bhead->old == old) @@ -8960,32 +8967,32 @@ static void expand_doit_library(void *fdhandle, Main *mainvar, void *old) BHead *bhead; FileData *fd = fdhandle; ID *id; - + bhead = find_bhead(fd, old); if (bhead) { /* from another library? */ if (bhead->code == ID_ID) { BHead *bheadlib= find_previous_lib(fd, bhead); - + if (bheadlib) { Library *lib = read_struct(fd, bheadlib, "Library"); Main *ptr = blo_find_main(fd, lib->name, fd->relabase); - + if (ptr->curlib == NULL) { const char *idname= bhead_id_name(fd, bhead); - + blo_reportf_wrap(fd->reports, RPT_WARNING, TIP_("LIB: Data refers to main .blend file: '%s' from %s"), idname, mainvar->curlib->filepath); return; } else id = is_yet_read(fd, ptr, bhead); - + if (id == NULL) { read_libblock(fd, ptr, bhead, LIB_TAG_READ | LIB_TAG_INDIRECT, NULL); // commented because this can print way too much // if (G.debug & G_DEBUG) printf("expand_doit: other lib %s\n", lib->name); - + /* for outliner dependency only */ ptr->curlib->parent = mainvar->curlib; } @@ -8996,10 +9003,10 @@ static void expand_doit_library(void *fdhandle, Main *mainvar, void *old) * lib_indirect.blend but lib.blend does too, linking in a Scene or Group from lib.blend can result in an * empty without the dupli group referenced. Once you save and reload the group would appear. - Campbell */ /* This crashes files, must look further into it */ - + /* Update: the issue is that in file reading, the oldnewmap is OK, but for existing data, it has to be * inserted in the map to be found! */ - + /* Update: previously it was checking for id->tag & LIB_TAG_PRE_EXISTING, however that * does not affect file reading. For file reading we may need to insert it into the libmap as well, * because you might have two files indirectly linking the same datablock, and in that case @@ -9009,11 +9016,11 @@ static void expand_doit_library(void *fdhandle, Main *mainvar, void *old) * change_idid_adr not detect the mapping was for an ID_ID datablock. */ oldnewmap_insert(fd->libmap, bhead->old, id, bhead->code); change_idid_adr_fd(fd, bhead->old, id); - + // commented because this can print way too much // if (G.debug & G_DEBUG) printf("expand_doit: already linked: %s lib: %s\n", id->name, lib->name); } - + MEM_freeN(lib); } } @@ -9082,14 +9089,14 @@ static void expand_idprops(FileData *fd, Main *mainvar, IDProperty *prop) static void expand_fmodifiers(FileData *fd, Main *mainvar, ListBase *list) { FModifier *fcm; - + for (fcm = list->first; fcm; fcm = fcm->next) { /* library data for specific F-Modifier types */ switch (fcm->type) { case FMODIFIER_TYPE_PYTHON: { FMod_Python *data = (FMod_Python *)fcm->data; - + expand_doit(fd, mainvar, data->script); break; @@ -9101,15 +9108,15 @@ static void expand_fmodifiers(FileData *fd, Main *mainvar, ListBase *list) static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list) { FCurve *fcu; - + for (fcu = list->first; fcu; fcu = fcu->next) { /* Driver targets if there is a driver */ if (fcu->driver) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar = driver->variables.first; dvar; dvar = dvar->next) { - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { // TODO: only expand those that are going to get used? expand_doit(fd, mainvar, dtar->id); @@ -9117,7 +9124,7 @@ static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list) DRIVER_TARGETS_LOOPER_END } } - + /* F-Curve Modifiers */ expand_fmodifiers(fd, mainvar, &fcu->modifiers); } @@ -9126,14 +9133,14 @@ static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list) static void expand_action(FileData *fd, Main *mainvar, bAction *act) { bActionChannel *chan; - + // XXX deprecated - old animation system -------------- for (chan=act->chanbase.first; chan; chan=chan->next) { expand_doit(fd, mainvar, chan->ipo); expand_constraint_channels(fd, mainvar, &chan->constraintChannels); } // --------------------------------------------------- - + /* F-Curves in Action */ expand_fcurves(fd, mainvar, &act->curves); @@ -9148,7 +9155,7 @@ static void expand_keyingsets(FileData *fd, Main *mainvar, ListBase *list) { KeyingSet *ks; KS_Path *ksp; - + /* expand the ID-pointers in KeyingSets's paths */ for (ks = list->first; ks; ks = ks->next) { for (ksp = ks->paths.first; ksp; ksp = ksp->next) { @@ -9160,17 +9167,17 @@ static void expand_keyingsets(FileData *fd, Main *mainvar, ListBase *list) static void expand_animdata_nlastrips(FileData *fd, Main *mainvar, ListBase *list) { NlaStrip *strip; - + for (strip= list->first; strip; strip= strip->next) { /* check child strips */ expand_animdata_nlastrips(fd, mainvar, &strip->strips); - + /* check F-Curves */ expand_fcurves(fd, mainvar, &strip->fcurves); - + /* check F-Modifiers */ expand_fmodifiers(fd, mainvar, &strip->modifiers); - + /* relink referenced action */ expand_doit(fd, mainvar, strip->act); } @@ -9179,32 +9186,32 @@ static void expand_animdata_nlastrips(FileData *fd, Main *mainvar, ListBase *lis static void expand_animdata(FileData *fd, Main *mainvar, AnimData *adt) { NlaTrack *nlt; - + /* own action */ expand_doit(fd, mainvar, adt->action); expand_doit(fd, mainvar, adt->tmpact); - + /* drivers - assume that these F-Curves have driver data to be in this list... */ expand_fcurves(fd, mainvar, &adt->drivers); - + /* nla-data - referenced actions */ - for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) + for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) expand_animdata_nlastrips(fd, mainvar, &nlt->strips); -} +} static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSettings *part) { int a; - + expand_doit(fd, mainvar, part->dup_ob); expand_doit(fd, mainvar, part->dup_group); expand_doit(fd, mainvar, part->eff_group); expand_doit(fd, mainvar, part->bb_ob); expand_doit(fd, mainvar, part->collision_group); - + if (part->adt) expand_animdata(fd, mainvar, part->adt); - + for (a = 0; a < MAX_MTEX; a++) { if (part->mtex[a]) { expand_doit(fd, mainvar, part->mtex[a]->tex); @@ -9247,7 +9254,7 @@ static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSetting static void expand_group(FileData *fd, Main *mainvar, Group *group) { GroupObject *go; - + for (go = group->gobject.first; go; go = go->next) { expand_doit(fd, mainvar, go->ob); } @@ -9256,7 +9263,7 @@ static void expand_group(FileData *fd, Main *mainvar, Group *group) static void expand_key(FileData *fd, Main *mainvar, Key *key) { expand_doit(fd, mainvar, key->ipo); // XXX deprecated - old animation system - + if (key->adt) expand_animdata(fd, mainvar, key->adt); } @@ -9265,13 +9272,13 @@ static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree) { bNode *node; bNodeSocket *sock; - + if (ntree->adt) expand_animdata(fd, mainvar, ntree->adt); - + if (ntree->gpd) expand_doit(fd, mainvar, ntree->gpd); - + for (node = ntree->nodes.first; node; node = node->next) { if (node->id && node->type != CMP_NODE_R_LAYERS) { expand_doit(fd, mainvar, node->id); @@ -9295,10 +9302,10 @@ static void expand_texture(FileData *fd, Main *mainvar, Tex *tex) { expand_doit(fd, mainvar, tex->ima); expand_doit(fd, mainvar, tex->ipo); // XXX deprecated - old animation system - + if (tex->adt) expand_animdata(fd, mainvar, tex->adt); - + if (tex->nodetree) expand_nodetree(fd, mainvar, tex->nodetree); } @@ -9314,22 +9321,22 @@ static void expand_brush(FileData *fd, Main *mainvar, Brush *brush) static void expand_material(FileData *fd, Main *mainvar, Material *ma) { int a; - + for (a = 0; a < MAX_MTEX; a++) { if (ma->mtex[a]) { expand_doit(fd, mainvar, ma->mtex[a]->tex); expand_doit(fd, mainvar, ma->mtex[a]->object); } } - + expand_doit(fd, mainvar, ma->ipo); // XXX deprecated - old animation system - + if (ma->adt) expand_animdata(fd, mainvar, ma->adt); - + if (ma->nodetree) expand_nodetree(fd, mainvar, ma->nodetree); - + if (ma->group) expand_doit(fd, mainvar, ma->group); } @@ -9337,19 +9344,19 @@ static void expand_material(FileData *fd, Main *mainvar, Material *ma) static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la) { int a; - + for (a = 0; a < MAX_MTEX; a++) { if (la->mtex[a]) { expand_doit(fd, mainvar, la->mtex[a]->tex); expand_doit(fd, mainvar, la->mtex[a]->object); } } - + expand_doit(fd, mainvar, la->ipo); // XXX deprecated - old animation system - + if (la->adt) expand_animdata(fd, mainvar, la->adt); - + if (la->nodetree) expand_nodetree(fd, mainvar, la->nodetree); } @@ -9358,7 +9365,7 @@ static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt) { expand_doit(fd, mainvar, lt->ipo); // XXX deprecated - old animation system expand_doit(fd, mainvar, lt->key); - + if (lt->adt) expand_animdata(fd, mainvar, lt->adt); } @@ -9367,19 +9374,19 @@ static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt) static void expand_world(FileData *fd, Main *mainvar, World *wrld) { int a; - + for (a = 0; a < MAX_MTEX; a++) { if (wrld->mtex[a]) { expand_doit(fd, mainvar, wrld->mtex[a]->tex); expand_doit(fd, mainvar, wrld->mtex[a]->object); } } - + expand_doit(fd, mainvar, wrld->ipo); // XXX deprecated - old animation system - + if (wrld->adt) expand_animdata(fd, mainvar, wrld->adt); - + if (wrld->nodetree) expand_nodetree(fd, mainvar, wrld->nodetree); } @@ -9388,11 +9395,11 @@ static void expand_world(FileData *fd, Main *mainvar, World *wrld) static void expand_mball(FileData *fd, Main *mainvar, MetaBall *mb) { int a; - + for (a = 0; a < mb->totcol; a++) { expand_doit(fd, mainvar, mb->mat[a]); } - + if (mb->adt) expand_animdata(fd, mainvar, mb->adt); } @@ -9400,11 +9407,11 @@ static void expand_mball(FileData *fd, Main *mainvar, MetaBall *mb) static void expand_curve(FileData *fd, Main *mainvar, Curve *cu) { int a; - + for (a = 0; a < cu->totcol; a++) { expand_doit(fd, mainvar, cu->mat[a]); } - + expand_doit(fd, mainvar, cu->vfont); expand_doit(fd, mainvar, cu->vfontb); expand_doit(fd, mainvar, cu->vfonti); @@ -9414,7 +9421,7 @@ static void expand_curve(FileData *fd, Main *mainvar, Curve *cu) expand_doit(fd, mainvar, cu->bevobj); expand_doit(fd, mainvar, cu->taperobj); expand_doit(fd, mainvar, cu->textoncurve); - + if (cu->adt) expand_animdata(fd, mainvar, cu->adt); } @@ -9424,17 +9431,17 @@ static void expand_mesh(FileData *fd, Main *mainvar, Mesh *me) CustomDataLayer *layer; TFace *tf; int a, i; - + if (me->adt) expand_animdata(fd, mainvar, me->adt); - + for (a = 0; a < me->totcol; a++) { expand_doit(fd, mainvar, me->mat[a]); } - + expand_doit(fd, mainvar, me->key); expand_doit(fd, mainvar, me->texcomesh); - + if (me->tface) { tf = me->tface; for (i=0; itotface; i++, tf++) { @@ -9492,13 +9499,13 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb) { tConstraintExpandData ced; bConstraint *curcon; - + /* relink all ID-blocks used by the constraints */ ced.fd = fd; ced.mainvar = mainvar; - + BKE_constraints_id_loop(lb, expand_constraint_cb, &ced); - + /* deprecated manual expansion stuff */ for (curcon = lb->first; curcon; curcon = curcon->next) { if (curcon->ipo) @@ -9509,10 +9516,10 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb) static void expand_pose(FileData *fd, Main *mainvar, bPose *pose) { bPoseChannel *chan; - + if (!pose) return; - + for (chan = pose->chanbase.first; chan; chan = chan->next) { expand_constraints(fd, mainvar, &chan->constraints); expand_idprops(fd, mainvar, chan->prop); @@ -9543,10 +9550,10 @@ static void expand_object_expandModifiers( void *userData, Object *UNUSED(ob), ID **idpoin, int UNUSED(cb_flag)) { struct { FileData *fd; Main *mainvar; } *data= userData; - + FileData *fd = data->fd; Main *mainvar = data->mainvar; - + expand_doit(fd, mainvar, *idpoin); } @@ -9559,56 +9566,56 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob) bActionStrip *strip; PartEff *paf; int a; - + expand_doit(fd, mainvar, ob->data); - + /* expand_object_expandModifier() */ if (ob->modifiers.first) { struct { FileData *fd; Main *mainvar; } data; data.fd = fd; data.mainvar = mainvar; - + modifiers_foreachIDLink(ob, expand_object_expandModifiers, (void *)&data); } - + expand_pose(fd, mainvar, ob->pose); expand_doit(fd, mainvar, ob->poselib); expand_constraints(fd, mainvar, &ob->constraints); - + expand_doit(fd, mainvar, ob->gpd); - + // XXX deprecated - old animation system (for version patching only) expand_doit(fd, mainvar, ob->ipo); expand_doit(fd, mainvar, ob->action); - + expand_constraint_channels(fd, mainvar, &ob->constraintChannels); - + for (strip=ob->nlastrips.first; strip; strip=strip->next) { expand_doit(fd, mainvar, strip->object); expand_doit(fd, mainvar, strip->act); expand_doit(fd, mainvar, strip->ipo); } // XXX deprecated - old animation system (for version patching only) - + if (ob->adt) expand_animdata(fd, mainvar, ob->adt); - + for (a = 0; a < ob->totcol; a++) { expand_doit(fd, mainvar, ob->mat[a]); } - + paf = blo_do_version_give_parteff_245(ob); - if (paf && paf->group) + if (paf && paf->group) expand_doit(fd, mainvar, paf->group); - + if (ob->dup_group) expand_doit(fd, mainvar, ob->dup_group); - + if (ob->proxy) expand_doit(fd, mainvar, ob->proxy); if (ob->proxy_group) expand_doit(fd, mainvar, ob->proxy_group); - + for (psys = ob->particlesystem.first; psys; psys = psys->next) expand_doit(fd, mainvar, psys->part); @@ -9618,14 +9625,14 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob) expand_doit(fd, mainvar, ms->fromObject); } } - + for (cont = ob->controllers.first; cont; cont = cont->next) { if (cont->type == CONT_PYTHON) { bPythonCont *pc = cont->data; expand_doit(fd, mainvar, pc->text); } } - + for (act = ob->actuators.first; act; act = act->next) { if (act->type == ACT_SOUND) { bSoundActuator *sa = act->data; @@ -9689,7 +9696,7 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob) expand_doit(fd, mainvar, sta->navmesh); } } - + if (ob->pd) { expand_doit(fd, mainvar, ob->pd->tex); expand_doit(fd, mainvar, ob->pd->f_source); @@ -9722,23 +9729,23 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) SceneRenderLayer *srl; FreestyleModuleConfig *module; FreestyleLineSet *lineset; - + for (base = sce->base.first; base; base = base->next) { expand_doit(fd, mainvar, base->object); } expand_doit(fd, mainvar, sce->camera); expand_doit(fd, mainvar, sce->world); - + if (sce->adt) expand_animdata(fd, mainvar, sce->adt); expand_keyingsets(fd, mainvar, &sce->keyingsets); - + if (sce->set) expand_doit(fd, mainvar, sce->set); - + if (sce->nodetree) expand_nodetree(fd, mainvar, sce->nodetree); - + for (srl = sce->r.layers.first; srl; srl = srl->next) { expand_doit(fd, mainvar, srl->mat_override); expand_doit(fd, mainvar, srl->light_override); @@ -9755,10 +9762,10 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) if (sce->gpd) expand_doit(fd, mainvar, sce->gpd); - + if (sce->ed) { Sequence *seq; - + SEQ_BEGIN (sce->ed, seq) { expand_idprops(fd, mainvar, seq->prop); @@ -9771,7 +9778,7 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) } SEQ_END } - + if (sce->rigidbody_world) { expand_doit(fd, mainvar, sce->rigidbody_world->group); expand_doit(fd, mainvar, sce->rigidbody_world->constraints); @@ -9789,7 +9796,7 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) static void expand_camera(FileData *fd, Main *mainvar, Camera *ca) { expand_doit(fd, mainvar, ca->ipo); // XXX deprecated - old animation system - + if (ca->adt) expand_animdata(fd, mainvar, ca->adt); } @@ -9911,10 +9918,10 @@ void BLO_expand_main(void *fdhandle, Main *mainvar) ID *id; int a; bool do_it = true; - + while (do_it) { do_it = false; - + a = set_listbasepointers(mainvar, lbarray); while (a--) { id = lbarray[a]->first; @@ -9923,91 +9930,91 @@ void BLO_expand_main(void *fdhandle, Main *mainvar) expand_idprops(fd, mainvar, id->properties); switch (GS(id->name)) { - case ID_OB: - expand_object(fd, mainvar, (Object *)id); - break; - case ID_ME: - expand_mesh(fd, mainvar, (Mesh *)id); - break; - case ID_CU: - expand_curve(fd, mainvar, (Curve *)id); - break; - case ID_MB: - expand_mball(fd, mainvar, (MetaBall *)id); - break; - case ID_SCE: - expand_scene(fd, mainvar, (Scene *)id); - break; - case ID_MA: - expand_material(fd, mainvar, (Material *)id); - break; - case ID_TE: - expand_texture(fd, mainvar, (Tex *)id); - break; - case ID_WO: - expand_world(fd, mainvar, (World *)id); - break; - case ID_LT: - expand_lattice(fd, mainvar, (Lattice *)id); - break; - case ID_LA: - expand_lamp(fd, mainvar, (Lamp *)id); - break; - case ID_KE: - expand_key(fd, mainvar, (Key *)id); - break; - case ID_CA: - expand_camera(fd, mainvar, (Camera *)id); - break; - case ID_SPK: - expand_speaker(fd, mainvar, (Speaker *)id); - break; - case ID_SO: - expand_sound(fd, mainvar, (bSound *)id); - break; - case ID_AR: - expand_armature(fd, mainvar, (bArmature *)id); - break; - case ID_AC: - expand_action(fd, mainvar, (bAction *)id); // XXX deprecated - old animation system - break; - case ID_GR: - expand_group(fd, mainvar, (Group *)id); - break; - case ID_NT: - expand_nodetree(fd, mainvar, (bNodeTree *)id); - break; - case ID_BR: - expand_brush(fd, mainvar, (Brush *)id); - break; - case ID_IP: - expand_ipo(fd, mainvar, (Ipo *)id); // XXX deprecated - old animation system - break; - case ID_PA: - expand_particlesettings(fd, mainvar, (ParticleSettings *)id); - break; - case ID_MC: - expand_movieclip(fd, mainvar, (MovieClip *)id); - break; - case ID_MSK: - expand_mask(fd, mainvar, (Mask *)id); - break; - case ID_LS: - expand_linestyle(fd, mainvar, (FreestyleLineStyle *)id); - break; - case ID_GD: - expand_gpencil(fd, mainvar, (bGPdata *)id); - break; - case ID_CF: - expand_cachefile(fd, mainvar, (CacheFile *)id); - break; - default: - break; + case ID_OB: + expand_object(fd, mainvar, (Object *)id); + break; + case ID_ME: + expand_mesh(fd, mainvar, (Mesh *)id); + break; + case ID_CU: + expand_curve(fd, mainvar, (Curve *)id); + break; + case ID_MB: + expand_mball(fd, mainvar, (MetaBall *)id); + break; + case ID_SCE: + expand_scene(fd, mainvar, (Scene *)id); + break; + case ID_MA: + expand_material(fd, mainvar, (Material *)id); + break; + case ID_TE: + expand_texture(fd, mainvar, (Tex *)id); + break; + case ID_WO: + expand_world(fd, mainvar, (World *)id); + break; + case ID_LT: + expand_lattice(fd, mainvar, (Lattice *)id); + break; + case ID_LA: + expand_lamp(fd, mainvar, (Lamp *)id); + break; + case ID_KE: + expand_key(fd, mainvar, (Key *)id); + break; + case ID_CA: + expand_camera(fd, mainvar, (Camera *)id); + break; + case ID_SPK: + expand_speaker(fd, mainvar, (Speaker *)id); + break; + case ID_SO: + expand_sound(fd, mainvar, (bSound *)id); + break; + case ID_AR: + expand_armature(fd, mainvar, (bArmature *)id); + break; + case ID_AC: + expand_action(fd, mainvar, (bAction *)id); // XXX deprecated - old animation system + break; + case ID_GR: + expand_group(fd, mainvar, (Group *)id); + break; + case ID_NT: + expand_nodetree(fd, mainvar, (bNodeTree *)id); + break; + case ID_BR: + expand_brush(fd, mainvar, (Brush *)id); + break; + case ID_IP: + expand_ipo(fd, mainvar, (Ipo *)id); // XXX deprecated - old animation system + break; + case ID_PA: + expand_particlesettings(fd, mainvar, (ParticleSettings *)id); + break; + case ID_MC: + expand_movieclip(fd, mainvar, (MovieClip *)id); + break; + case ID_MSK: + expand_mask(fd, mainvar, (Mask *)id); + break; + case ID_LS: + expand_linestyle(fd, mainvar, (FreestyleLineStyle *)id); + break; + case ID_GD: + expand_gpencil(fd, mainvar, (bGPdata *)id); + break; + case ID_CF: + expand_cachefile(fd, mainvar, (CacheFile *)id); + break; + default: + break; } - + do_it = true; id->tag &= ~LIB_TAG_NEED_EXPAND; - + } id = id->next; } @@ -10017,17 +10024,17 @@ void BLO_expand_main(void *fdhandle, Main *mainvar) /* ***************************** */ - + static bool object_in_any_scene(Main *mainvar, Object *ob) { Scene *sce; - + for (sce = mainvar->scene.first; sce; sce = sce->id.next) { if (BKE_scene_base_find(sce, ob)) { return true; } } - + return false; } @@ -10178,10 +10185,10 @@ static ID *link_named_part( else { id = NULL; } - + /* if we found the id but the id is NULL, this is really bad */ BLI_assert(!((bhead != NULL) && (id == NULL))); - + return id; } @@ -10222,7 +10229,7 @@ void BLO_library_link_copypaste(Main *mainl, BlendHandle *bh) { FileData *fd = (FileData *)(bh); BHead *bhead; - + for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) { ID *id = NULL; @@ -10354,23 +10361,23 @@ static Main *library_link_begin(Main *mainvar, FileData **fd, const char *filepa Main *mainl; (*fd)->mainlist = MEM_callocN(sizeof(ListBase), "FileData.mainlist"); - + /* clear for group instantiating tag */ BKE_main_id_tag_listbase(&(mainvar->group), LIB_TAG_DOIT, false); /* make mains */ blo_split_main((*fd)->mainlist, mainvar); - + /* which one do we need? */ mainl = blo_find_main(*fd, filepath, BKE_main_blendfile_path(mainvar)); - + /* needed for do_version */ mainl->versionfile = (*fd)->fileversion; read_file_version(*fd, mainl); #ifdef USE_GHASH_BHEAD read_file_bhead_idname_map_create(*fd); #endif - + return mainl; } @@ -10520,11 +10527,11 @@ static int mainvar_id_tag_any_check(Main *mainvar, const short tag) { ListBase *lbarray[MAX_LIBARRAY]; int a; - + a = set_listbasepointers(mainvar, lbarray); while (a--) { ID *id; - + for (id = lbarray[a]->first; id; id = id->next) { if (id->tag & tag) { return true; @@ -10542,13 +10549,13 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) GHash *loaded_ids = BLI_ghash_str_new(__func__); int a; bool do_it = true; - + /* expander now is callback function */ BLO_main_expander(expand_doit_library); - + while (do_it) { do_it = false; - + /* test 1: read libdata */ mainptr= mainl->next; while (mainptr) { @@ -10556,22 +10563,22 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) // printf("found LIB_TAG_READ %s (%s)\n", mainptr->curlib->id.name, mainptr->curlib->name); FileData *fd = mainptr->curlib->filedata; - + if (fd == NULL) { - + /* printf and reports for now... its important users know this */ - + /* if packed file... */ if (mainptr->curlib->packedfile) { PackedFile *pf = mainptr->curlib->packedfile; - + blo_reportf_wrap( basefd->reports, RPT_INFO, TIP_("Read packed library: '%s', parent '%s'"), mainptr->curlib->name, library_parent_filepath(mainptr->curlib)); fd = blo_openblendermemory(pf->data, pf->size, basefd->reports); - - + + /* needed for library_append and read_libraries */ BLI_strncpy(fd->relabase, mainptr->curlib->filepath, sizeof(fd->relabase)); } @@ -10592,12 +10599,12 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) printf(" absolute lib: %s\n", mainptr->curlib->filepath); printf(" relative lib: %s\n", mainptr->curlib->name); printf(" enter a new path:\n"); - + if (scanf("%1023s", newlib_path) > 0) { /* Warning, keep length in sync with FILE_MAX! */ BLI_strncpy(mainptr->curlib->name, newlib_path, sizeof(mainptr->curlib->name)); BLI_strncpy(mainptr->curlib->filepath, newlib_path, sizeof(mainptr->curlib->filepath)); BLI_cleanup_path(BKE_main_blendfile_path_from_global(), mainptr->curlib->filepath); - + fd = blo_openblenderfile(mainptr->curlib->filepath, basefd->reports); if (fd) { @@ -10607,7 +10614,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) } } } - + if (fd) { /* share the mainlist, so all libraries are added immediately in a * single list. it used to be that all FileData's had their own list, @@ -10616,15 +10623,15 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) fd->mainlist = mainlist; fd->reports = basefd->reports; - + if (fd->libmap) oldnewmap_free(fd->libmap); - + fd->libmap = oldnewmap_new(); - + mainptr->curlib->filedata = fd; mainptr->versionfile= fd->fileversion; - + /* subversion */ read_file_version(fd, mainptr); #ifdef USE_GHASH_BHEAD @@ -10639,7 +10646,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) mainptr->versionfile = mainptr->curlib->versionfile = mainl->versionfile; mainptr->subversionfile = mainptr->curlib->subversionfile = mainl->subversionfile; } - + if (fd == NULL) { blo_reportf_wrap(basefd->reports, RPT_WARNING, TIP_("Cannot find lib '%s'"), mainptr->curlib->filepath); @@ -10686,7 +10693,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) } BLO_expand_main(fd, mainptr); } - + mainptr = mainptr->next; } } @@ -10700,7 +10707,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) a = set_listbasepointers(mainptr, lbarray); while (a--) { ID *id, *idn = NULL; - + for (id = lbarray[a]->first; id; id = idn) { idn = id->next; if (id->tag & LIB_TAG_READ) { @@ -10715,13 +10722,13 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) mainptr->curlib->filepath, library_parent_filepath(mainptr->curlib)); change_idid_adr(mainlist, basefd, id, NULL); - + MEM_freeN(id); } } } } - + /* do versions, link, and free */ Main main_newid = {0}; for (mainptr = mainl->next; mainptr; mainptr = mainptr->next) { @@ -10737,10 +10744,10 @@ static void read_libraries(FileData *basefd, ListBase *mainlist) add_main_to_main(mainptr, &main_newid); } - + if (mainptr->curlib->filedata) lib_link_all(mainptr->curlib->filedata, mainptr); - + if (mainptr->curlib->filedata) blo_freefiledata(mainptr->curlib->filedata); mainptr->curlib->filedata = NULL; } @@ -10756,17 +10763,17 @@ BlendFileData *blo_read_blendafterruntime(int file, const char *name, int actual fd->filedes = file; fd->buffersize = actualsize; fd->read = fd_read_from_file; - + /* needed for library_append and read_libraries */ BLI_strncpy(fd->relabase, name, sizeof(fd->relabase)); - + fd = blo_decode_and_check(fd, reports); if (!fd) return NULL; - + fd->reports = reports; bfd = blo_read_file_internal(fd, ""); blo_freefiledata(fd); - + return bfd; } diff --git a/source/blender/blenloader/intern/readfile.h b/source/blender/blenloader/intern/readfile.h index 213a72be1bef..89623e00139b 100644 --- a/source/blender/blenloader/intern/readfile.h +++ b/source/blender/blenloader/intern/readfile.h @@ -64,23 +64,23 @@ typedef struct FileData { // now only in use for library appending char relabase[FILE_MAX]; - + // variables needed for reading from stream char headerdone; int inbuffer; - + // gzip stream for memory decompression z_stream strm; - + // general reading variables struct SDNA *filesdna; const struct SDNA *memsdna; const char *compflags; /* array of eSDNA_StructCompare */ - + int fileversion; int id_name_offs; /* used to retrieve ID names from (bhead+1) */ int globalf, fileflags; /* for do_versions patching */ - + eBLOReadSkip skip_flags; /* skip some data-blocks */ struct OldNewMap *datamap; @@ -90,13 +90,13 @@ typedef struct FileData { struct OldNewMap *movieclipmap; struct OldNewMap *soundmap; struct OldNewMap *packedmap; - + struct BHeadSort *bheadmap; int tot_bheadmap; /* see: USE_GHASH_BHEAD */ struct GHash *bhead_idname_hash; - + ListBase *mainlist; ListBase *old_mainlist; /* Used for undo. */ @@ -176,4 +176,3 @@ void blo_do_versions_upbge(struct FileData *fd, struct Library *lib, struct Main void do_versions_after_linking_270(struct Main *bmain); #endif - diff --git a/source/blender/blenloader/intern/runtime.c b/source/blender/blenloader/intern/runtime.c index ec496e1c866c..985e81698199 100644 --- a/source/blender/blenloader/intern/runtime.c +++ b/source/blender/blenloader/intern/runtime.c @@ -73,9 +73,9 @@ int BLO_is_a_runtime(const char *path) if (fd == -1) goto cleanup; - + lseek(fd, -12, SEEK_END); - + datastart = handle_read_msb_int(fd); if (datastart == -1) @@ -107,7 +107,7 @@ BlendFileData *BLO_read_runtime(const char *path, ReportList *reports) BKE_reportf(reports, RPT_ERROR, "Unable to open '%s': %s", path, strerror(errno)); goto cleanup; } - + actualsize = BLI_file_descriptor_size(fd); lseek(fd, -12, SEEK_END); @@ -132,11 +132,10 @@ BlendFileData *BLO_read_runtime(const char *path, ReportList *reports) bfd = blo_read_blendafterruntime(fd, path, actualsize - datastart, reports); fd = -1; // file was closed in blo_read_blendafterruntime() } - + cleanup: if (fd != -1) close(fd); - + return bfd; } - diff --git a/source/blender/blenloader/intern/undofile.c b/source/blender/blenloader/intern/undofile.c index e1ae267ea116..614a3be559b5 100644 --- a/source/blender/blenloader/intern/undofile.c +++ b/source/blender/blenloader/intern/undofile.c @@ -64,7 +64,7 @@ void BLO_memfile_free(MemFile *memfile) { MemFileChunk *chunk; - + while ((chunk = BLI_pophead(&memfile->chunks))) { if (chunk->is_identical == false) { MEM_freeN((void *)chunk->buf); @@ -79,7 +79,7 @@ void BLO_memfile_free(MemFile *memfile) void BLO_memfile_merge(MemFile *first, MemFile *second) { MemFileChunk *fc, *sc; - + fc = first->chunks.first; sc = second->chunks.first; while (fc || sc) { @@ -92,7 +92,7 @@ void BLO_memfile_merge(MemFile *first, MemFile *second) if (fc) fc = fc->next; if (sc) sc = sc->next; } - + BLO_memfile_free(first); } diff --git a/source/blender/blenloader/intern/versioning_250.c b/source/blender/blenloader/intern/versioning_250.c index 369d17273292..cc46555383e2 100644 --- a/source/blender/blenloader/intern/versioning_250.c +++ b/source/blender/blenloader/intern/versioning_250.c @@ -633,20 +633,6 @@ static void do_version_constraints_radians_degrees_250(ListBase *lb) } } -/* NOTE: this version patch is intended for versions < 2.52.2, but was initially introduced in 2.27 already */ -static void do_versions_seq_unique_name_all_strips(Scene *sce, ListBase *seqbasep) -{ - Sequence * seq = seqbasep->first; - - while (seq) { - BKE_sequence_base_unique_name_recursive(&sce->ed->seqbase, seq); - if (seq->seqbase.first) { - do_versions_seq_unique_name_all_strips(sce, &seq->seqbase); - } - seq = seq->next; - } -} - static void do_version_bone_roll_256(Bone *bone) { Bone *child; @@ -670,7 +656,7 @@ static bNodeSocket *do_versions_node_group_add_socket_2_56_2(bNodeTree *ngroup, { // bNodeSocketType *stype = ntreeGetSocketType(type); bNodeSocket *gsock = MEM_callocN(sizeof(bNodeSocket), "bNodeSocket"); - + BLI_strncpy(gsock->name, name, sizeof(gsock->name)); gsock->type = type; @@ -680,14 +666,14 @@ static bNodeSocket *do_versions_node_group_add_socket_2_56_2(bNodeTree *ngroup, /* assign new unique index */ gsock->own_index = ngroup->cur_index++; gsock->limit = (in_out==SOCK_IN ? 0xFFF : 1); - + // if (stype->value_structsize > 0) // gsock->default_value = MEM_callocN(stype->value_structsize, "default socket value"); - + BLI_addtail(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, gsock); - + ngroup->update |= (in_out==SOCK_IN ? NTREE_UPDATE_GROUP_IN : NTREE_UPDATE_GROUP_OUT); - + return gsock; } @@ -703,10 +689,10 @@ static void do_versions_socket_default_value_259(bNodeSocket *sock) bNodeSocketValueFloat *valfloat; bNodeSocketValueVector *valvector; bNodeSocketValueRGBA *valrgba; - + if (sock->default_value) return; - + switch (sock->type) { case SOCK_FLOAT: valfloat = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueFloat), "default socket value"); @@ -1304,10 +1290,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) if (sce->r.mblur_samples == 0) sce->r.mblur_samples = sce->r.osa; - if (sce->ed && sce->ed->seqbase.first) { - do_versions_seq_unique_name_all_strips(sce, &sce->ed->seqbase); - } - sce = sce->id.next; } } @@ -2330,13 +2312,13 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) bNode *node; bNodeSocket *sock, *gsock; bNodeLink *link; - + /* node sockets are not exposed automatically any more, * this mimics the old behavior by adding all unlinked sockets to groups. */ for (ntree=bmain->nodetree.first; ntree; ntree=ntree->id.next) { /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */ - + /* first make sure the own_index for new sockets is valid */ for (node=ntree->nodes.first; node; node=node->next) { for (sock = node->inputs.first; sock; sock = sock->next) @@ -2346,17 +2328,17 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) if (sock->own_index >= ntree->cur_index) ntree->cur_index = sock->own_index+1; } - + /* add ntree->inputs/ntree->outputs sockets for all unlinked sockets in the group tree. */ for (node=ntree->nodes.first; node; node=node->next) { for (sock = node->inputs.first; sock; sock = sock->next) { if (!sock->link && !nodeSocketIsHidden(sock)) { - + gsock = do_versions_node_group_add_socket_2_56_2(ntree, sock->name, sock->type, SOCK_IN); - + /* initialize the default socket value */ copy_v4_v4(gsock->ns.vec, sock->ns.vec); - + /* XXX nodeAddLink does not work with incomplete (node==NULL) links any longer, * have to create these directly here. These links are updated again in subsequent do_version! */ @@ -2367,17 +2349,17 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) link->tonode = node; link->tosock = sock; ntree->update |= NTREE_UPDATE_LINKS; - + sock->link = link; } } for (sock = node->outputs.first; sock; sock = sock->next) { if (nodeCountSocketLinks(ntree, sock)==0 && !nodeSocketIsHidden(sock)) { gsock = do_versions_node_group_add_socket_2_56_2(ntree, sock->name, sock->type, SOCK_OUT); - + /* initialize the default socket value */ copy_v4_v4(gsock->ns.vec, sock->ns.vec); - + /* XXX nodeAddLink does not work with incomplete (node==NULL) links any longer, * have to create these directly here. These links are updated again in subsequent do_version! */ @@ -2388,12 +2370,12 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) link->tonode = NULL; link->tosock = gsock; ntree->update |= NTREE_UPDATE_LINKS; - + gsock->link = link; } } } - + /* XXX The external group node sockets needs to adjust their own_index to point at * associated ntree inputs/outputs internal sockets. However, this can only happen * after lib-linking (needs access to internal node group tree)! @@ -2699,19 +2681,19 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *bmain) FOREACH_NODETREE(bmain, ntree, id) { bNode *node; bNodeSocket *sock; - + for (node=ntree->nodes.first; node; node=node->next) { for (sock = node->inputs.first; sock; sock = sock->next) do_versions_socket_default_value_259(sock); for (sock = node->outputs.first; sock; sock = sock->next) do_versions_socket_default_value_259(sock); } - + for (sock = ntree->inputs.first; sock; sock = sock->next) do_versions_socket_default_value_259(sock); for (sock = ntree->outputs.first; sock; sock = sock->next) do_versions_socket_default_value_259(sock); - + ntree->update |= NTREE_UPDATE; } FOREACH_NODETREE_END diff --git a/source/blender/blenloader/intern/versioning_260.c b/source/blender/blenloader/intern/versioning_260.c index 41736d39d82e..b774d0580bd5 100644 --- a/source/blender/blenloader/intern/versioning_260.c +++ b/source/blender/blenloader/intern/versioning_260.c @@ -2650,10 +2650,10 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *bmain) } } } - + if (!MAIN_VERSION_ATLEAST(bmain, 269, 9)) { Object *ob; - + for (ob = bmain->object.first; ob; ob = ob->id.next) { ModifierData *md; for (md = ob->modifiers.first; md; md = md->next) { diff --git a/source/blender/blenloader/intern/versioning_270.c b/source/blender/blenloader/intern/versioning_270.c index 6d352bd7b130..7b7877250847 100644 --- a/source/blender/blenloader/intern/versioning_270.c +++ b/source/blender/blenloader/intern/versioning_270.c @@ -172,7 +172,7 @@ static void do_version_constraints_stretch_to_limits(ListBase *lb) static void do_version_action_editor_properties_region(ListBase *regionbase) { ARegion *ar; - + for (ar = regionbase->first; ar; ar = ar->next) { if (ar->regiontype == RGN_TYPE_UI) { /* already exists */ @@ -181,13 +181,13 @@ static void do_version_action_editor_properties_region(ListBase *regionbase) else if (ar->regiontype == RGN_TYPE_WINDOW) { /* add new region here */ ARegion *arnew = MEM_callocN(sizeof(ARegion), "buttons for action"); - + BLI_insertlinkbefore(regionbase, ar, arnew); - + arnew->regiontype = RGN_TYPE_UI; arnew->alignment = RGN_ALIGN_RIGHT; arnew->flag = RGN_FLAG_HIDDEN; - + return; } } @@ -198,7 +198,7 @@ static void do_version_bones_super_bbone(ListBase *lb) for (Bone *bone = lb->first; bone; bone = bone->next) { bone->scaleIn = 1.0f; bone->scaleOut = 1.0f; - + do_version_bones_super_bbone(&bone->childbase); } } @@ -290,7 +290,7 @@ static void do_versions_compositor_render_passes(bNodeTree *ntree) static char *replace_bbone_easing_rnapath(char *old_path) { char *new_path = NULL; - + /* NOTE: This will break paths for any bones/custom-properties * which happen be named after the bbone property id's */ @@ -298,7 +298,7 @@ static char *replace_bbone_easing_rnapath(char *old_path) new_path = BLI_str_replaceN(old_path, "bbone_in", "bbone_easein"); else if (strstr(old_path, "bbone_out")) new_path = BLI_str_replaceN(old_path, "bbone_out", "bbone_easeout"); - + if (new_path) { MEM_freeN(old_path); return new_path; @@ -308,13 +308,25 @@ static char *replace_bbone_easing_rnapath(char *old_path) } } +/* NOTE: this version patch is intended for versions < 2.52.2, but was initially introduced in 2.27 already. + * But in 2.79 another case generating non-unique names was discovered (see T55668, involving Meta strips)... */ +static void do_versions_seq_unique_name_all_strips(Scene *sce, ListBase *seqbasep) +{ + for (Sequence *seq = seqbasep->first; seq != NULL; seq = seq->next) { + BKE_sequence_base_unique_name_recursive(&sce->ed->seqbase, seq); + if (seq->seqbase.first != NULL) { + do_versions_seq_unique_name_all_strips(sce, &seq->seqbase); + } + } +} + static void do_version_bbone_easing_fcurve_fix(ID *UNUSED(id), FCurve *fcu, void *UNUSED(user_data)) { /* F-Curve's path (for bbone_in/out) */ if (fcu->rna_path) { fcu->rna_path = replace_bbone_easing_rnapath(fcu->rna_path); } - + /* Driver -> Driver Vars (for bbone_in/out) */ if (fcu->driver) { for (DriverVar *dvar = fcu->driver->variables.first; dvar; dvar = dvar->next) { @@ -327,13 +339,13 @@ static void do_version_bbone_easing_fcurve_fix(ID *UNUSED(id), FCurve *fcu, void DRIVER_TARGETS_LOOPER_END; } } - + /* FModifiers -> Stepped (for frame_start/end) */ if (fcu->modifiers.first) { for (FModifier *fcm = fcu->modifiers.first; fcm; fcm = fcm->next) { if (fcm->type == FMODIFIER_TYPE_STEPPED) { FMod_Stepped *data = fcm->data; - + /* Modifier doesn't work if the modifier's copy of start/end frame are both 0 * as those were only getting written to the fcm->data copy (T52009) */ @@ -694,7 +706,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) } } } - + if (!MAIN_VERSION_ATLEAST(bmain, 273, 3)) { ParticleSettings *part; for (part = bmain->particle.first; part; part = part->id.next) { @@ -1122,63 +1134,63 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) if (!MAIN_VERSION_ATLEAST(bmain, 276, 4)) { for (Scene *scene = bmain->scene.first; scene; scene = scene->id.next) { ToolSettings *ts = scene->toolsettings; - + if (ts->gp_sculpt.brush[0].size == 0) { GP_BrushEdit_Settings *gset = &ts->gp_sculpt; GP_EditBrush_Data *brush; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH]; brush->size = 25; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS]; brush->size = 25; brush->strength = 0.5f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_GRAB]; brush->size = 50; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH]; brush->size = 25; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST]; brush->size = 50; brush->strength = 0.3f; // XXX? brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH]; brush->size = 50; brush->strength = 0.5f; // XXX? brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE]; brush->size = 25; brush->strength = 0.5f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_CLONE]; brush->size = 50; brush->strength = 1.0f; } - + if (!DNA_struct_elem_find(fd->filesdna, "ToolSettings", "char", "gpencil_v3d_align")) { #if 0 /* XXX: Cannot do this, as we get random crashes... */ if (scene->gpd) { bGPdata *gpd = scene->gpd; - + /* Copy over the settings stored in the GP datablock linked to the scene, for minimal disruption */ ts->gpencil_v3d_align = 0; - + if (gpd->flag & GP_DATA_VIEWALIGN) ts->gpencil_v3d_align |= GP_PROJECT_VIEWSPACE; if (gpd->flag & GP_DATA_DEPTH_VIEW) ts->gpencil_v3d_align |= GP_PROJECT_DEPTH_VIEW; if (gpd->flag & GP_DATA_DEPTH_STROKE) ts->gpencil_v3d_align |= GP_PROJECT_DEPTH_STROKE; - + if (gpd->flag & GP_DATA_DEPTH_STROKE_ENDPOINTS) ts->gpencil_v3d_align |= GP_PROJECT_DEPTH_STROKE_ENDPOINTS; } @@ -1187,17 +1199,17 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) ts->gpencil_v3d_align = GP_PROJECT_VIEWSPACE; } #endif - + ts->gpencil_v3d_align = GP_PROJECT_VIEWSPACE; ts->gpencil_v2d_align = GP_PROJECT_VIEWSPACE; ts->gpencil_seq_align = GP_PROJECT_VIEWSPACE; ts->gpencil_ima_align = GP_PROJECT_VIEWSPACE; } } - + for (bGPdata *gpd = bmain->gpencil.first; gpd; gpd = gpd->id.next) { bool enabled = false; - + /* Ensure that the datablock's onionskinning toggle flag * stays in sync with the status of the actual layers */ @@ -1206,7 +1218,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) enabled = true; } } - + if (enabled) gpd->flag |= GP_DATA_SHOW_ONIONSKINS; else @@ -1327,7 +1339,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) do_version_action_editor_properties_region(&saction->regionbase); } } - + /* active spacedata info must be handled too... */ if (sa->spacetype == SPACE_ACTION) { do_version_action_editor_properties_region(&sa->regionbase); @@ -1349,7 +1361,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) /* see do_version_bones_super_bbone()... */ pchan->scaleIn = 1.0f; pchan->scaleOut = 1.0f; - + /* also make sure some legacy (unused for over a decade) flags are unset, * so that we can reuse them for stuff that matters now... * (i.e. POSE_IK_MAT, (unknown/unused x 4), POSE_HAS_IK) @@ -1469,19 +1481,19 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) /* set color attributes */ copy_v4_v4(palcolor->color, gpl->color); copy_v4_v4(palcolor->fill, gpl->fill); - + if (gpl->flag & GP_LAYER_HIDE) palcolor->flag |= PC_COLOR_HIDE; if (gpl->flag & GP_LAYER_LOCKED) palcolor->flag |= PC_COLOR_LOCKED; if (gpl->flag & GP_LAYER_ONIONSKIN) palcolor->flag |= PC_COLOR_ONIONSKIN; if (gpl->flag & GP_LAYER_VOLUMETRIC) palcolor->flag |= PC_COLOR_VOLUMETRIC; if (gpl->flag & GP_LAYER_HQ_FILL) palcolor->flag |= PC_COLOR_HQ_FILL; - + /* set layer opacity to 1 */ gpl->opacity = 1.0f; - + /* set tint color */ ARRAY_SET_ITEMS(gpl->tintcolor, 0.0f, 0.0f, 0.0f, 0.0f); - + /* flush relevant layer-settings to strokes */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) { for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) { @@ -1490,7 +1502,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) gps->palcolor = NULL; gps->flag |= GP_STROKE_RECALC_COLOR; gps->thickness = gpl->thickness; - + /* set alpha strength to 1 */ for (int i = 0; i < gps->totpoints; i++) { gps->points[i].strength = 1.0f; @@ -1498,7 +1510,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) } } } - + /* set thickness to 0 (now it is a factor to override stroke thickness) */ gpl->thickness = 0.0f; } @@ -1826,6 +1838,14 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *bmain) } } } + + if (!MAIN_VERSION_ATLEAST(bmain, 279, 6)) { + for (Scene *sce = bmain->scene.first; sce != NULL; sce = sce->id.next) { + if (sce->ed != NULL && sce->ed->seqbase.first != NULL) { + do_versions_seq_unique_name_all_strips(sce, &sce->ed->seqbase); + } + } + } } void do_versions_after_linking_270(Main *bmain) @@ -1843,7 +1863,7 @@ void do_versions_after_linking_270(Main *bmain) } } FOREACH_NODETREE_END } - + if (!MAIN_VERSION_ATLEAST(bmain, 279, 2)) { /* B-Bones (bbone_in/out -> bbone_easein/out) + Stepped FMod Frame Start/End fix */ /* if (!DNA_struct_elem_find(fd->filesdna, "Bone", "float", "bbone_easein")) */ diff --git a/source/blender/blenloader/intern/versioning_defaults.c b/source/blender/blenloader/intern/versioning_defaults.c index 29e3c926153d..558c709d14cf 100644 --- a/source/blender/blenloader/intern/versioning_defaults.c +++ b/source/blender/blenloader/intern/versioning_defaults.c @@ -108,7 +108,7 @@ void BLO_update_defaults_startup_blend(Main *bmain) sculpt->flags |= SCULPT_DYNTOPO_COLLAPSE; sculpt->detail_size = 12; } - + if (ts->vpaint) { VPaint *vp = ts->vpaint; vp->radial_symm[0] = vp->radial_symm[1] = vp->radial_symm[2] = 1; @@ -122,17 +122,17 @@ void BLO_update_defaults_startup_blend(Main *bmain) if (ts->gp_sculpt.brush[0].size == 0) { GP_BrushEdit_Settings *gset = &ts->gp_sculpt; GP_EditBrush_Data *brush; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH]; brush->size = 25; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS]; brush->size = 25; brush->strength = 0.5f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH]; brush->size = 25; brush->strength = 0.5f; @@ -142,28 +142,28 @@ void BLO_update_defaults_startup_blend(Main *bmain) brush->size = 50; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH]; brush->size = 25; brush->strength = 0.3f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST]; brush->size = 50; brush->strength = 0.3f; // XXX? brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH]; brush->size = 50; brush->strength = 0.5f; // XXX? brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE]; brush->size = 25; brush->strength = 0.5f; brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; } - + ts->gpencil_v3d_align = GP_PROJECT_VIEWSPACE; ts->gpencil_v2d_align = GP_PROJECT_VIEWSPACE; ts->gpencil_seq_align = GP_PROJECT_VIEWSPACE; @@ -311,4 +311,3 @@ void BLO_update_defaults_startup_blend(Main *bmain) } } } - diff --git a/source/blender/blenloader/intern/versioning_legacy.c b/source/blender/blenloader/intern/versioning_legacy.c index ee8a0c05980a..93ae727c39f5 100644 --- a/source/blender/blenloader/intern/versioning_legacy.c +++ b/source/blender/blenloader/intern/versioning_legacy.c @@ -1597,33 +1597,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *bmain) } } - if (bmain->versionfile <= 231) { - /* new bit flags for showing/hiding grid floor and axes */ - bScreen *sc = bmain->screen.first; - - while (sc) { - ScrArea *sa = sc->areabase.first; - while (sa) { - SpaceLink *sl = sa->spacedata.first; - while (sl) { - if (sl->spacetype == SPACE_VIEW3D) { - View3D *v3d = (View3D*) sl; - - if (v3d->gridflag == 0) { - v3d->gridflag |= V3D_SHOW_X; - v3d->gridflag |= V3D_SHOW_Y; - v3d->gridflag |= V3D_SHOW_FLOOR; - v3d->gridflag &= ~V3D_SHOW_Z; - } - } - sl = sl->next; - } - sa = sa->next; - } - sc = sc->id.next; - } - } - if (bmain->versionfile <= 231) { Material *ma = bmain->mat.first; bScreen *sc = bmain->screen.first; diff --git a/source/blender/blenloader/intern/versioning_upbge.c b/source/blender/blenloader/intern/versioning_upbge.c index ced82114dadc..8fa1af0eca21 100644 --- a/source/blender/blenloader/intern/versioning_upbge.c +++ b/source/blender/blenloader/intern/versioning_upbge.c @@ -167,17 +167,6 @@ void blo_do_versions_upbge(FileData *fd, Library *lib, Main *main) } if (!MAIN_VERSION_UPBGE_ATLEAST(main, 1, 5)) { - for (bScreen *sc = main->screen.first; sc; sc = sc->id.next) { - for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) { - for (SpaceLink *sl = sa->spacedata.first; sl; sl = sl->next) { - if (sl->spacetype == SPACE_VIEW3D) { - View3D *v3d = (View3D *)sl; - v3d->flag3 = V3D_SHOW_MIST; - } - } - } - } - if (!DNA_struct_elem_find(fd->filesdna, "Object", "float", "lodfactor")) { for (Object *ob = main->object.first; ob; ob = ob->id.next) { ob->lodfactor = 1.0f; @@ -277,6 +266,7 @@ void blo_do_versions_upbge(FileData *fd, Library *lib, Main *main) } } } + if (!MAIN_VERSION_UPBGE_ATLEAST(main, 2, 4)) { FOREACH_NODETREE(main, ntree, id) { if (ntree->type == NTREE_SHADER) { @@ -301,12 +291,23 @@ void blo_do_versions_upbge(FileData *fd, Library *lib, Main *main) } } } FOREACH_NODETREE_END - + if (!DNA_struct_elem_find(fd->filesdna, "Lamp", "float", "cutoff")) { for (Lamp *lamp = main->lamp.first; lamp; lamp = lamp->id.next) { lamp->radius = 8.0f; lamp->cutoff = 0.001f; } } + + for (bScreen *sc = main->screen.first; sc; sc = sc->id.next) { + for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) { + for (SpaceLink *sl = sa->spacedata.first; sl; sl = sl->next) { + if (sl->spacetype == SPACE_VIEW3D) { + View3D *v3d = (View3D *)sl; + v3d->flag2 |= V3D_SHOW_MIST; + } + } + } + } } } diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c index 49455041e34b..247f3fd420b9 100644 --- a/source/blender/blenloader/intern/writefile.c +++ b/source/blender/blenloader/intern/writefile.c @@ -342,10 +342,6 @@ typedef struct { * Will be NULL for UNDO. */ WriteWrap *ww; - -#ifdef USE_BMESH_SAVE_AS_COMPAT - bool use_mesh_compat; /* option to save with older mesh format */ -#endif } WriteData; static WriteData *writedata_new(WriteWrap *ww) @@ -1082,6 +1078,13 @@ static void write_nodetree_nolib(WriteData *wd, bNodeTree *ntree) } writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage); } + else if ((ntree->type == NTREE_COMPOSIT) && (node->type == CMP_NODE_CRYPTOMATTE)) { + NodeCryptomatte *nc = (NodeCryptomatte *)node->storage; + if (nc->matte_id) { + writedata(wd, DATA, strlen(nc->matte_id) + 1, nc->matte_id); + } + writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage); + } else { writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage); } @@ -2224,12 +2227,6 @@ static void write_customdata( static void write_mesh(WriteData *wd, Mesh *mesh) { -#ifdef USE_BMESH_SAVE_AS_COMPAT - const bool save_for_old_blender = wd->use_mesh_compat; /* option to save with older mesh format */ -#else - const bool save_for_old_blender = false; -#endif - CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE]; CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE]; CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE]; @@ -2238,19 +2235,17 @@ static void write_mesh(WriteData *wd, Mesh *mesh) if (mesh->id.us > 0 || wd->use_memfile) { /* write LibData */ - if (!save_for_old_blender) { + { /* write a copy of the mesh, don't modify in place because it is * not thread safe for threaded renders that are reading this */ Mesh *old_mesh = mesh; Mesh copy_mesh = *mesh; mesh = ©_mesh; -#ifdef USE_BMESH_SAVE_WITHOUT_MFACE /* cache only - don't write */ mesh->mface = NULL; mesh->totface = 0; memset(&mesh->fdata, 0, sizeof(mesh->fdata)); -#endif /* USE_BMESH_SAVE_WITHOUT_MFACE */ /** * Those calls: @@ -2261,11 +2256,7 @@ static void write_mesh(WriteData *wd, Mesh *mesh) */ CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff)); CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff)); -#ifndef USE_BMESH_SAVE_WITHOUT_MFACE /* Do not copy org fdata in this case!!! */ - CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff)); -#else flayers = flayers_buff; -#endif CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff)); CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff)); @@ -2290,73 +2281,6 @@ static void write_mesh(WriteData *wd, Mesh *mesh) /* restore pointer */ mesh = old_mesh; } - else { - -#ifdef USE_BMESH_SAVE_AS_COMPAT - /* write a copy of the mesh, don't modify in place because it is - * not thread safe for threaded renders that are reading this */ - Mesh *old_mesh = mesh; - Mesh copy_mesh = *mesh; - mesh = ©_mesh; - - mesh->mpoly = NULL; - mesh->mface = NULL; - mesh->totface = 0; - mesh->totpoly = 0; - mesh->totloop = 0; - CustomData_reset(&mesh->fdata); - CustomData_reset(&mesh->pdata); - CustomData_reset(&mesh->ldata); - mesh->edit_btmesh = NULL; - - /* now fill in polys to mfaces */ - /* XXX This breaks writing design, by using temp allocated memory, which will likely generate - * duplicates in stored 'old' addresses. - * This is very bad, but do not see easy way to avoid this, aside from generating those data - * outside of save process itself. - * Maybe we can live with this, though? - */ - mesh->totface = BKE_mesh_mpoly_to_mface( - &mesh->fdata, &old_mesh->ldata, &old_mesh->pdata, - mesh->totface, old_mesh->totloop, old_mesh->totpoly); - - BKE_mesh_update_customdata_pointers(mesh, false); - - CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff)); - CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff)); - CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff)); -#if 0 - CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff)); - CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff)); -#endif - - writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh); - write_iddata(wd, &mesh->id); - - /* direct data */ - if (mesh->adt) { - write_animdata(wd, mesh->adt); - } - - writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat); - /* writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect); */ /* pre-bmesh NULL's */ - - write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0); - write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0); - write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0); - /* harmless for older blender versioins but _not_ writing these keeps file size down */ -#if 0 - write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0); - write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0); -#endif - - CustomData_free(&mesh->fdata, mesh->totface); - flayers = NULL; - - /* restore pointer */ - mesh = old_mesh; -#endif /* USE_BMESH_SAVE_AS_COMPAT */ - } } if (vlayers && vlayers != vlayers_buff) { @@ -3884,10 +3808,6 @@ static bool write_file_handle( wd = mywrite_begin(ww, compare, current); -#ifdef USE_BMESH_SAVE_AS_COMPAT - wd->use_mesh_compat = (write_flags & G_FILE_MESH_COMPAT) != 0; -#endif - #ifdef USE_NODE_COMPAT_CUSTOMNODES /* don't write compatibility data on undo */ if (!current) { diff --git a/source/blender/bmesh/CMakeLists.txt b/source/blender/bmesh/CMakeLists.txt index 320bebc99581..bd3eb4cc1acc 100644 --- a/source/blender/bmesh/CMakeLists.txt +++ b/source/blender/bmesh/CMakeLists.txt @@ -119,9 +119,9 @@ set(SRC intern/bmesh_polygon_edgenet.c intern/bmesh_polygon_edgenet.h intern/bmesh_private.h - intern/bmesh_queries.c - intern/bmesh_queries.h - intern/bmesh_queries_inline.h + intern/bmesh_query.c + intern/bmesh_query.h + intern/bmesh_query_inline.h intern/bmesh_structure.c intern/bmesh_structure.h intern/bmesh_structure_inline.h diff --git a/source/blender/bmesh/bmesh.h b/source/blender/bmesh/bmesh.h index b84a3d5e5598..8b0b8a282f5e 100644 --- a/source/blender/bmesh/bmesh.h +++ b/source/blender/bmesh/bmesh.h @@ -98,7 +98,7 @@ * * These are accessible through the iterator api, which is covered later in this document * - * See source/blender/bmesh/bmesh_queries.h for more misc. queries. + * See source/blender/bmesh/bmesh_query.h for more misc. queries. * * * \section bm_api The BMesh API @@ -246,7 +246,7 @@ extern "C" { #include "intern/bmesh_operators.h" #include "intern/bmesh_polygon.h" #include "intern/bmesh_polygon_edgenet.h" -#include "intern/bmesh_queries.h" +#include "intern/bmesh_query.h" #include "intern/bmesh_walkers.h" #include "intern/bmesh_inline.h" diff --git a/source/blender/bmesh/intern/bmesh_mods.c b/source/blender/bmesh/intern/bmesh_mods.c index a10f2e2bb3f0..dfa3486227f5 100644 --- a/source/blender/bmesh/intern/bmesh_mods.c +++ b/source/blender/bmesh/intern/bmesh_mods.c @@ -1104,4 +1104,3 @@ BMVert *BM_face_loop_separate_multi(BMesh *bm, BMLoop **larr, int larr_len) { return bmesh_kernel_unglue_region_make_vert_multi(bm, larr, larr_len); } - diff --git a/source/blender/bmesh/intern/bmesh_operator_api_inline.h b/source/blender/bmesh/intern/bmesh_operator_api_inline.h index eb1c161f19d2..a453cfa1769a 100644 --- a/source/blender/bmesh/intern/bmesh_operator_api_inline.h +++ b/source/blender/bmesh/intern/bmesh_operator_api_inline.h @@ -168,7 +168,7 @@ BLI_INLINE float BMO_slot_map_float_get(BMOpSlot *slot, const void *element) data = BMO_slot_map_data_get(slot, element); if (data) { - return **(float **)data; + return *(float *)data; } else { return 0.0f; @@ -183,7 +183,7 @@ BLI_INLINE int BMO_slot_map_int_get(BMOpSlot *slot, const void *element) data = BMO_slot_map_data_get(slot, element); if (data) { - return **(int **)data; + return *(int *)data; } else { return 0; @@ -198,7 +198,7 @@ BLI_INLINE bool BMO_slot_map_bool_get(BMOpSlot *slot, const void *element) data = BMO_slot_map_data_get(slot, element); if (data) { - return **(bool **)data; + return *(bool *)data; } else { return false; diff --git a/source/blender/bmesh/intern/bmesh_queries.c b/source/blender/bmesh/intern/bmesh_query.c similarity index 99% rename from source/blender/bmesh/intern/bmesh_queries.c rename to source/blender/bmesh/intern/bmesh_query.c index 5ce4b236d031..33ad7836893d 100644 --- a/source/blender/bmesh/intern/bmesh_queries.c +++ b/source/blender/bmesh/intern/bmesh_query.c @@ -20,7 +20,7 @@ * ***** END GPL LICENSE BLOCK ***** */ -/** \file blender/bmesh/intern/bmesh_queries.c +/** \file blender/bmesh/intern/bmesh_query.c * \ingroup bmesh * * This file contains functions for answering common diff --git a/source/blender/bmesh/intern/bmesh_queries.h b/source/blender/bmesh/intern/bmesh_query.h similarity index 98% rename from source/blender/bmesh/intern/bmesh_queries.h rename to source/blender/bmesh/intern/bmesh_query.h index e602c63da948..51956761d8f4 100644 --- a/source/blender/bmesh/intern/bmesh_queries.h +++ b/source/blender/bmesh/intern/bmesh_query.h @@ -20,10 +20,10 @@ * ***** END GPL LICENSE BLOCK ***** */ -#ifndef __BMESH_QUERIES_H__ -#define __BMESH_QUERIES_H__ +#ifndef __BMESH_QUERY_H__ +#define __BMESH_QUERY_H__ -/** \file blender/bmesh/intern/bmesh_queries.h +/** \file blender/bmesh/intern/bmesh_query.h * \ingroup bmesh */ @@ -196,6 +196,6 @@ int BM_mesh_calc_edge_groups( /* not really any good place to put this */ float bmesh_subd_falloff_calc(const int falloff, float val) ATTR_WARN_UNUSED_RESULT; -#include "bmesh_queries_inline.h" +#include "bmesh_query_inline.h" -#endif /* __BMESH_QUERIES_H__ */ +#endif /* __BMESH_QUERY_H__ */ diff --git a/source/blender/bmesh/intern/bmesh_queries_inline.h b/source/blender/bmesh/intern/bmesh_query_inline.h similarity index 96% rename from source/blender/bmesh/intern/bmesh_queries_inline.h rename to source/blender/bmesh/intern/bmesh_query_inline.h index 09cf39b526d8..92be3639dce1 100644 --- a/source/blender/bmesh/intern/bmesh_queries_inline.h +++ b/source/blender/bmesh/intern/bmesh_query_inline.h @@ -18,13 +18,13 @@ * ***** END GPL LICENSE BLOCK ***** */ -/** \file blender/bmesh/intern/bmesh_queries_inline.h +/** \file blender/bmesh/intern/bmesh_query_inline.h * \ingroup bmesh */ -#ifndef __BMESH_QUERIES_INLINE_H__ -#define __BMESH_QUERIES_INLINE_H__ +#ifndef __BMESH_QUERY_INLINE_H__ +#define __BMESH_QUERY_INLINE_H__ /** * Returns whether or not a given vertex is @@ -166,4 +166,4 @@ BLI_INLINE bool BM_vert_is_wire_endpoint(const BMVert *v) return false; } -#endif /* __BMESH_QUERIES_INLINE_H__ */ +#endif /* __BMESH_QUERY_INLINE_H__ */ diff --git a/source/blender/bmesh/operators/bmo_beautify.c b/source/blender/bmesh/operators/bmo_beautify.c index c68d92ea5e03..00b2b8a5d1b7 100644 --- a/source/blender/bmesh/operators/bmo_beautify.c +++ b/source/blender/bmesh/operators/bmo_beautify.c @@ -82,4 +82,3 @@ void bmo_beautify_fill_exec(BMesh *bm, BMOperator *op) BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom.out", BM_EDGE | BM_FACE, ELE_NEW); } - diff --git a/source/blender/bmesh/operators/bmo_smooth_laplacian.c b/source/blender/bmesh/operators/bmo_smooth_laplacian.c index 2a7b85ac8fd0..317045b303cd 100644 --- a/source/blender/bmesh/operators/bmo_smooth_laplacian.c +++ b/source/blender/bmesh/operators/bmo_smooth_laplacian.c @@ -543,4 +543,3 @@ void bmo_smooth_laplacian_vert_exec(BMesh *bm, BMOperator *op) delete_laplacian_system(sys); } - diff --git a/source/blender/bmesh/operators/bmo_subdivide.c b/source/blender/bmesh/operators/bmo_subdivide.c index 90cbe9a5d76e..c8ba2134a730 100644 --- a/source/blender/bmesh/operators/bmo_subdivide.c +++ b/source/blender/bmesh/operators/bmo_subdivide.c @@ -1363,6 +1363,9 @@ void bmo_bisect_edges_exec(BMesh *bm, BMOperator *op) bmo_subd_init_shape_info(bm, ¶ms); + /* tag edges in map */ + BMO_slot_map_to_flag(bm, op->slots_in, "edge_percents", BM_EDGE, EDGE_PERCENT); + /* go through and split edges */ BMO_ITER (e, &siter, op->slots_in, "edges", BM_EDGE) { bm_subdivide_multicut(bm, e, ¶ms, e->v1, e->v2); diff --git a/source/blender/bmesh/tools/bmesh_beautify.c b/source/blender/bmesh/tools/bmesh_beautify.c index d3972363bb4f..5d535cc75032 100644 --- a/source/blender/bmesh/tools/bmesh_beautify.c +++ b/source/blender/bmesh/tools/bmesh_beautify.c @@ -456,4 +456,3 @@ void BM_mesh_beautify_fill( TIMEIT_END(beautify_fill); #endif } - diff --git a/source/blender/bmesh/tools/bmesh_bevel.c b/source/blender/bmesh/tools/bmesh_bevel.c index 33380cee18e6..adfcb8dc68f7 100644 --- a/source/blender/bmesh/tools/bmesh_bevel.c +++ b/source/blender/bmesh/tools/bmesh_bevel.c @@ -4930,7 +4930,7 @@ static void find_even_superellipse_chords_general(int seg, float r, double *xval double sum; double temp; - bool precision_reached; + bool precision_reached = true; bool seg_odd = seg % 2; bool rbig; diff --git a/source/blender/bmesh/tools/bmesh_intersect.c b/source/blender/bmesh/tools/bmesh_intersect.c index 88467e60dc0f..b1a8c3ccb860 100644 --- a/source/blender/bmesh/tools/bmesh_intersect.c +++ b/source/blender/bmesh/tools/bmesh_intersect.c @@ -1233,7 +1233,7 @@ bool BM_mesh_intersect( if (BM_vert_in_edge(e, v_prev)) { BMEdge *e_split; - v_prev = BM_edge_split(bm, e, v_prev, &e_split, CLAMPIS(fac, 0.0f, 1.0f)); + v_prev = BM_edge_split(bm, e, v_prev, &e_split, clamp_f(fac, 0.0f, 1.0f)); BLI_assert(BM_vert_in_edge(e, v_end)); if (!BM_edge_exists(v_prev, vi) && diff --git a/source/blender/collada/DocumentExporter.cpp b/source/blender/collada/DocumentExporter.cpp index 669faa8358be..bf29ec42c42b 100644 --- a/source/blender/collada/DocumentExporter.cpp +++ b/source/blender/collada/DocumentExporter.cpp @@ -169,7 +169,7 @@ static COLLADABU::NativeString make_temp_filepath(const char *name, const char * BLI_make_file_string(NULL, tempfile, tempdir, name); if (extension) { - BLI_ensure_extension(tempfile, FILE_MAX, extension); + BLI_path_extension_ensure(tempfile, FILE_MAX, extension); } COLLADABU::NativeString native_filename = diff --git a/source/blender/collada/ErrorHandler.h b/source/blender/collada/ErrorHandler.h index 3b3797e935a2..2e648f54c4e4 100644 --- a/source/blender/collada/ErrorHandler.h +++ b/source/blender/collada/ErrorHandler.h @@ -53,4 +53,3 @@ class ErrorHandler : public COLLADASaxFWL::IErrorHandler /** Hold error status. */ bool mError; }; - diff --git a/source/blender/collada/ExtraHandler.h b/source/blender/collada/ExtraHandler.h index 4dda862b3cc9..826557ebaab3 100644 --- a/source/blender/collada/ExtraHandler.h +++ b/source/blender/collada/ExtraHandler.h @@ -83,4 +83,3 @@ class ExtraHandler : public COLLADASaxFWL::IExtraDataCallbackHandler ExtraTags* currentExtraTags; std::string currentElement; }; - diff --git a/source/blender/collada/GeometryExporter.cpp b/source/blender/collada/GeometryExporter.cpp index 0be3f8cdd2b2..5f310c26da3f 100644 --- a/source/blender/collada/GeometryExporter.cpp +++ b/source/blender/collada/GeometryExporter.cpp @@ -933,5 +933,3 @@ COLLADASW::URI GeometryExporter::makeUrl(std::string id) { return COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, id); } - - diff --git a/source/blender/collada/SceneExporter.cpp b/source/blender/collada/SceneExporter.cpp index 4e08548449f3..a0d1b6b53339 100644 --- a/source/blender/collada/SceneExporter.cpp +++ b/source/blender/collada/SceneExporter.cpp @@ -242,4 +242,3 @@ void SceneExporter::writeNodes(bContext *C, Object *ob, Scene *sce) if (ob->type != OB_ARMATURE) colladaNode.end(); } - diff --git a/source/blender/collada/collada_internal.cpp b/source/blender/collada/collada_internal.cpp index f2cc56777d84..14f3e811797f 100644 --- a/source/blender/collada/collada_internal.cpp +++ b/source/blender/collada/collada_internal.cpp @@ -357,4 +357,3 @@ std::string get_morph_id(Object *ob) { return translate_id(id_name(ob)) + "-morph"; } - diff --git a/source/blender/compositor/CMakeLists.txt b/source/blender/compositor/CMakeLists.txt index 3e1dd83112a9..0ad53d3ab804 100644 --- a/source/blender/compositor/CMakeLists.txt +++ b/source/blender/compositor/CMakeLists.txt @@ -182,6 +182,11 @@ set(SRC operations/COM_SunBeamsOperation.cpp operations/COM_SunBeamsOperation.h + nodes/COM_CryptomatteNode.cpp + nodes/COM_CryptomatteNode.h + operations/COM_CryptomatteOperation.cpp + operations/COM_CryptomatteOperation.h + nodes/COM_CornerPinNode.cpp nodes/COM_CornerPinNode.h nodes/COM_PlaneTrackDeformNode.cpp diff --git a/source/blender/compositor/intern/COM_CPUDevice.cpp b/source/blender/compositor/intern/COM_CPUDevice.cpp index 970338d41ccb..d3991245c22c 100644 --- a/source/blender/compositor/intern/COM_CPUDevice.cpp +++ b/source/blender/compositor/intern/COM_CPUDevice.cpp @@ -40,4 +40,3 @@ void CPUDevice::execute(WorkPackage *work) executionGroup->finalizeChunkExecution(chunkNumber, NULL); } - diff --git a/source/blender/compositor/intern/COM_CPUDevice.h b/source/blender/compositor/intern/COM_CPUDevice.h index f98a75e5978e..b938b5fc5880 100644 --- a/source/blender/compositor/intern/COM_CPUDevice.h +++ b/source/blender/compositor/intern/COM_CPUDevice.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CPUDevice_h -#define _COM_CPUDevice_h +#ifndef __COM_CPUDEVICE_H__ +#define __COM_CPUDEVICE_H__ #include "COM_Device.h" diff --git a/source/blender/compositor/intern/COM_ChunkOrder.h b/source/blender/compositor/intern/COM_ChunkOrder.h index 0310933e5c54..f61816c65113 100644 --- a/source/blender/compositor/intern/COM_ChunkOrder.h +++ b/source/blender/compositor/intern/COM_ChunkOrder.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ChunkOrder_h_ -#define _COM_ChunkOrder_h_ +#ifndef __COM_CHUNKORDER_H__ +#define __COM_CHUNKORDER_H__ #include "COM_ChunkOrderHotspot.h" class ChunkOrder { @@ -34,7 +34,7 @@ class ChunkOrder { ChunkOrder(); void determineDistance(ChunkOrderHotspot **hotspots, unsigned int numberOfHotspots); friend bool operator<(const ChunkOrder &a, const ChunkOrder &b); - + void setChunkNumber(unsigned int chunknumber) { this->m_number = chunknumber; } void setX(int x) { this->m_x = x; } void setY(int y) { this->m_y = y; } diff --git a/source/blender/compositor/intern/COM_ChunkOrderHotspot.h b/source/blender/compositor/intern/COM_ChunkOrderHotspot.h index 09e9fa44c3b7..620980518ef0 100644 --- a/source/blender/compositor/intern/COM_ChunkOrderHotspot.h +++ b/source/blender/compositor/intern/COM_ChunkOrderHotspot.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ChunkOrderHotSpot_h_ -#define _COM_ChunkOrderHotSpot_h_ +#ifndef __COM_CHUNKORDERHOTSPOT_H__ +#define __COM_CHUNKORDERHOTSPOT_H__ #ifdef WITH_CXX_GUARDEDALLOC #include "MEM_guardedalloc.h" diff --git a/source/blender/compositor/intern/COM_CompositorContext.h b/source/blender/compositor/intern/COM_CompositorContext.h index d58e85024140..b43e163870c4 100644 --- a/source/blender/compositor/intern/COM_CompositorContext.h +++ b/source/blender/compositor/intern/COM_CompositorContext.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CompositorContext_h -#define _COM_CompositorContext_h +#ifndef __COM_COMPOSITORCONTEXT_H__ +#define __COM_COMPOSITORCONTEXT_H__ #include #include @@ -126,7 +126,7 @@ class CompositorContext { * @brief get the scene of the context */ const RenderData *getRenderData() const { return this->m_rd; } - + void setScene(Scene *scene) { m_scene = scene; } Scene *getScene() const { return m_scene; } @@ -196,7 +196,7 @@ class CompositorContext { void setViewName(const char *viewName) { this->m_viewName = viewName; } int getChunksize() const { return this->getbNodeTree()->chunksize; } - + void setFastCalculation(bool fastCalculation) {this->m_fastCalculation = fastCalculation;} bool isFastCalculation() const { return this->m_fastCalculation; } bool isGroupnodeBufferEnabled() const { return (this->getbNodeTree()->flag & NTREE_COM_GROUPNODE_BUFFER) != 0; } diff --git a/source/blender/compositor/intern/COM_Converter.cpp b/source/blender/compositor/intern/COM_Converter.cpp index 3d49443c146f..c9181905908b 100644 --- a/source/blender/compositor/intern/COM_Converter.cpp +++ b/source/blender/compositor/intern/COM_Converter.cpp @@ -55,6 +55,7 @@ extern "C" { #include "COM_Converter.h" #include "COM_CornerPinNode.h" #include "COM_CropNode.h" +#include "COM_CryptomatteNode.h" #include "COM_DefocusNode.h" #include "COM_DespeckleNode.h" #include "COM_DifferenceMatteNode.h" @@ -406,6 +407,9 @@ Node *Converter::convert(bNode *b_node) case CMP_NODE_SUNBEAMS: node = new SunBeamsNode(b_node); break; + case CMP_NODE_CRYPTOMATTE: + node = new CryptomatteNode(b_node); + break; } return node; } @@ -414,7 +418,7 @@ NodeOperation *Converter::convertDataType(NodeOperationOutput *from, NodeOperati { DataType fromDatatype = from->getDataType(); DataType toDatatype = to->getDataType(); - + if (fromDatatype == COM_DT_VALUE && toDatatype == COM_DT_COLOR) { return new ConvertValueToColorOperation(); } @@ -433,7 +437,7 @@ NodeOperation *Converter::convertDataType(NodeOperationOutput *from, NodeOperati else if (fromDatatype == COM_DT_VECTOR && toDatatype == COM_DT_COLOR) { return new ConvertVectorToColorOperation(); } - + return NULL; } diff --git a/source/blender/compositor/intern/COM_Converter.h b/source/blender/compositor/intern/COM_Converter.h index 7ed5616d899e..d0b888e24a0f 100644 --- a/source/blender/compositor/intern/COM_Converter.h +++ b/source/blender/compositor/intern/COM_Converter.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_Converter_h -#define _COM_Converter_h +#ifndef __COM_CONVERTER_H__ +#define __COM_CONVERTER_H__ #ifdef WITH_CXX_GUARDEDALLOC # include "MEM_guardedalloc.h" @@ -50,14 +50,14 @@ class Converter { * @see Node */ static Node *convert(bNode *b_node); - + /** * @brief True if the node is considered 'fast'. * * Slow nodes will be skipped if fast execution is required. */ static bool is_fast_node(bNode *b_node); - + /** * @brief This method will add a datetype conversion rule when the to-socket does not support the from-socket actual data type. * @@ -68,7 +68,7 @@ class Converter { * @see NodeLink - a link between two sockets */ static NodeOperation *convertDataType(NodeOperationOutput *from, NodeOperationInput *to); - + /** * @brief This method will add a resolution rule based on the settings of the NodeInput. * diff --git a/source/blender/compositor/intern/COM_Debug.cpp b/source/blender/compositor/intern/COM_Debug.cpp index b95b7500ccab..45c51bf1c985 100644 --- a/source/blender/compositor/intern/COM_Debug.cpp +++ b/source/blender/compositor/intern/COM_Debug.cpp @@ -118,7 +118,7 @@ void DebugInfo::execution_group_finished(const ExecutionGroup *group) int DebugInfo::graphviz_operation(const ExecutionSystem *system, const NodeOperation *operation, const ExecutionGroup *group, char *str, int maxlen) { int len = 0; - + std::string fillcolor = "gainsboro"; if (operation->isViewerOperation()) { const ViewerOperation *viewer = (const ViewerOperation *)operation; @@ -141,14 +141,14 @@ int DebugInfo::graphviz_operation(const ExecutionSystem *system, const NodeOpera else if (operation->isWriteBufferOperation()) { fillcolor = "darkorange"; } - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "// OPERATION: %p\r\n", operation); if (group) len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "\"O_%p_%p\"", operation, group); else len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "\"O_%p\"", operation); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, " [fillcolor=%s,style=filled,shape=record,label=\"{", fillcolor.c_str()); - + int totinputs = operation->getNumberOfInputSockets(); if (totinputs != 0) { len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "{"); @@ -173,11 +173,11 @@ int DebugInfo::graphviz_operation(const ExecutionSystem *system, const NodeOpera len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "}"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "|"); } - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "%s\\n(%s)", m_op_names[operation].c_str(), typeid(*operation).name()); - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, " (%u,%u)", operation->getWidth(), operation->getHeight()); - + int totoutputs = operation->getNumberOfOutputSockets(); if (totoutputs != 0) { len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "|"); @@ -204,7 +204,7 @@ int DebugInfo::graphviz_operation(const ExecutionSystem *system, const NodeOpera } len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "}\"]"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "\r\n"); - + return len; } @@ -233,7 +233,7 @@ int DebugInfo::graphviz_legend_group(const char *name, const char *color, const int DebugInfo::graphviz_legend(char *str, int maxlen) { int len = 0; - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "{\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "rank = sink;\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "Legend [shape=none, margin=0, label=<\r\n"); @@ -266,26 +266,27 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma { char strbuf[64]; int len = 0; - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "digraph compositorexecution {\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "ranksep=1.5\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "rankdir=LR\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "splines=false\r\n"); - + #if 0 for (ExecutionSystem::Operations::const_iterator it = system->m_operations.begin(); - it != system->m_operations.end(); ++it) { + it != system->m_operations.end(); ++it) + { NodeOperation *op = *it; len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "// OPERATION: %s\r\n", node->getbNode()->typeinfo->ui_name); } #endif - + int totops = system->m_operations.size(); int totgroups = system->m_groups.size(); std::map > op_groups; for (int i = 0; i < totgroups; ++i) { const ExecutionGroup *group = system->m_groups[i]; - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "// GROUP: %d\r\n", i); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "subgraph cluster_%d{\r\n", i); /* used as a check for executing group */ @@ -302,41 +303,41 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "color=black\r\n"); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "fillcolor=chartreuse4\r\n"); } - + for (ExecutionGroup::Operations::const_iterator it = group->m_operations.begin(); it != group->m_operations.end(); ++it) { NodeOperation *operation = *it; - + sprintf(strbuf, "_%p", group); op_groups[operation].push_back(std::string(strbuf)); - + len += graphviz_operation(system, operation, group, str + len, maxlen > len ? maxlen - len : 0); } - + // len += snprintf(str+len, maxlen>len ? maxlen-len : 0, "// OUTPUTOPERATION: %p\r\n", group->getOutputOperation()); // len += snprintf(str+len, maxlen>len ? maxlen-len : 0, " O_%p\r\n", group->getOutputOperation()); len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "}\r\n"); } - + /* operations not included in any group */ for (int j = 0; j < totops; ++j) { NodeOperation *operation = system->m_operations[j]; if (op_groups.find(operation) != op_groups.end()) continue; - + op_groups[operation].push_back(std::string("")); - + len += graphviz_operation(system, operation, 0, str + len, maxlen > len ? maxlen - len : 0); } - + for (int i = 0; i < totops; i++) { NodeOperation *operation = system->m_operations[i]; - + if (operation->isReadBufferOperation()) { ReadBufferOperation *read = (ReadBufferOperation *)operation; WriteBufferOperation *write = read->getMemoryProxy()->getWriteBufferOperation(); std::vector &read_groups = op_groups[read]; std::vector &write_groups = op_groups[write]; - + for (int k = 0; k < write_groups.size(); ++k) { for (int l = 0; l < read_groups.size(); ++l) { len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "\"O_%p%s\" -> \"O_%p%s\" [style=dotted]\r\n", write, write_groups[k].c_str(), read, read_groups[l].c_str()); @@ -344,17 +345,17 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma } } } - + for (int i = 0; i < totops; i++) { NodeOperation *op = system->m_operations[i]; - + for (NodeOperation::Inputs::const_iterator it = op->m_inputs.begin(); it != op->m_inputs.end(); ++it) { NodeOperationInput *to = *it; NodeOperationOutput *from = to->getLink(); - + if (!from) continue; - + std::string color; switch (from->getDataType()) { case COM_DT_VALUE: @@ -367,12 +368,12 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma color = "orange"; break; } - + NodeOperation *to_op = &to->getOperation(); NodeOperation *from_op = &from->getOperation(); std::vector &from_groups = op_groups[from_op]; std::vector &to_groups = op_groups[to_op]; - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "// CONNECTION: %p.%p -> %p.%p\r\n", from_op, from, to_op, to); for (int k = 0; k < from_groups.size(); ++k) { @@ -385,11 +386,11 @@ bool DebugInfo::graphviz_system(const ExecutionSystem *system, char *str, int ma } } } - + len += graphviz_legend(str + len, maxlen > len ? maxlen - len : 0); - + len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "}\r\n"); - + return (len < maxlen); } @@ -399,11 +400,11 @@ void DebugInfo::graphviz(const ExecutionSystem *system) if (graphviz_system(system, str, sizeof(str) - 1)) { char basename[FILE_MAX]; char filename[FILE_MAX]; - + BLI_snprintf(basename, sizeof(basename), "compositor_%d.dot", m_file_index); BLI_join_dirfile(filename, sizeof(filename), BKE_tempdir_session(), basename); ++m_file_index; - + FILE *fp = BLI_fopen(filename, "wb"); fputs(str, fp); fclose(fp); diff --git a/source/blender/compositor/intern/COM_Debug.h b/source/blender/compositor/intern/COM_Debug.h index 4b4894d36cfd..8a5014afb964 100644 --- a/source/blender/compositor/intern/COM_Debug.h +++ b/source/blender/compositor/intern/COM_Debug.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_Debug_h -#define _COM_Debug_h +#ifndef __COM_DEBUG_H__ +#define __COM_DEBUG_H__ #include #include @@ -39,27 +39,27 @@ class DebugInfo { EG_RUNNING, EG_FINISHED } GroupState; - + typedef std::map NodeNameMap; typedef std::map OpNameMap; typedef std::map GroupStateMap; - + static std::string node_name(const Node *node); static std::string operation_name(const NodeOperation *op); - + static void convert_started(); static void execute_started(const ExecutionSystem *system); - + static void node_added(const Node *node); static void node_to_operations(const Node *node); static void operation_added(const NodeOperation *operation); static void operation_read_write_buffer(const NodeOperation *operation); - + static void execution_group_started(const ExecutionGroup *group); static void execution_group_finished(const ExecutionGroup *group); - + static void graphviz(const ExecutionSystem *system); - + #ifdef COM_DEBUG protected: static int graphviz_operation(const ExecutionSystem *system, const NodeOperation *operation, const ExecutionGroup *group, char *str, int maxlen); @@ -68,7 +68,7 @@ class DebugInfo { static int graphviz_legend_group(const char *name, const char *color, const char *style, char *str, int maxlen); static int graphviz_legend(char *str, int maxlen); static bool graphviz_system(const ExecutionSystem *system, char *str, int maxlen); - + private: static int m_file_index; static NodeNameMap m_node_names; /**< map nodes to usable names for debug output */ diff --git a/source/blender/compositor/intern/COM_Device.cpp b/source/blender/compositor/intern/COM_Device.cpp index ee59976f45d4..7d2045e3c7b4 100644 --- a/source/blender/compositor/intern/COM_Device.cpp +++ b/source/blender/compositor/intern/COM_Device.cpp @@ -21,4 +21,3 @@ */ #include "COM_Device.h" - diff --git a/source/blender/compositor/intern/COM_Device.h b/source/blender/compositor/intern/COM_Device.h index 62653357fdfc..202ca1d0b4f9 100644 --- a/source/blender/compositor/intern/COM_Device.h +++ b/source/blender/compositor/intern/COM_Device.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_Device_h -#define _COM_Device_h +#ifndef __COM_DEVICE_H__ +#define __COM_DEVICE_H__ #include "COM_WorkPackage.h" @@ -34,11 +34,11 @@ class Device { public: /** - * @brief Declaration of the virtual destructor + * @brief Declaration of the virtual destructor * @note resolve warning gcc 4.7 */ virtual ~Device() {} - + /** * @brief initialize the device */ diff --git a/source/blender/compositor/intern/COM_ExecutionGroup.cpp b/source/blender/compositor/intern/COM_ExecutionGroup.cpp index 8a8193bcb625..5a651f078685 100644 --- a/source/blender/compositor/intern/COM_ExecutionGroup.cpp +++ b/source/blender/compositor/intern/COM_ExecutionGroup.cpp @@ -73,16 +73,16 @@ CompositorPriority ExecutionGroup::getRenderPriotrity() bool ExecutionGroup::canContainOperation(NodeOperation *operation) { if (!this->m_initialized) { return true; } - + if (operation->isReadBufferOperation()) { return true; } if (operation->isWriteBufferOperation()) { return false; } if (operation->isSetOperation()) { return true; } - + /* complex groups don't allow further ops (except read buffer and values, see above) */ if (m_complex) { return false; } /* complex ops can't be added to other groups (except their own, which they initialize, see above) */ if (operation->isComplex()) { return false; } - + return true; } @@ -90,16 +90,16 @@ bool ExecutionGroup::addOperation(NodeOperation *operation) { if (!canContainOperation(operation)) return false; - + if (!operation->isReadBufferOperation() && !operation->isWriteBufferOperation()) { m_complex = operation->isComplex(); m_openCL = operation->isOpenCL(); m_singleThreaded = operation->isSingleThreaded(); m_initialized = true; } - + m_operations.push_back(operation); - + return true; } @@ -382,7 +382,7 @@ void ExecutionGroup::finalizeChunkExecution(int chunkNumber, MemoryBuffer **memo { if (this->m_chunkExecutionStates[chunkNumber] == COM_ES_SCHEDULED) this->m_chunkExecutionStates[chunkNumber] = COM_ES_EXECUTED; - + atomic_add_and_fetch_u(&this->m_chunksFinished, 1); if (memoryBuffers) { for (unsigned int index = 0; index < this->m_cachedMaxReadBufferOffset; index++) { diff --git a/source/blender/compositor/intern/COM_ExecutionGroup.h b/source/blender/compositor/intern/COM_ExecutionGroup.h index 0f84dccb7119..88c702b84775 100644 --- a/source/blender/compositor/intern/COM_ExecutionGroup.h +++ b/source/blender/compositor/intern/COM_ExecutionGroup.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ExecutionGroup_h -#define _COM_ExecutionGroup_h +#ifndef __COM_EXECUTIONGROUP_H__ +#define __COM_EXECUTIONGROUP_H__ #include "COM_Node.h" #include "COM_NodeOperation.h" @@ -65,89 +65,89 @@ typedef enum ChunkExecutionState { class ExecutionGroup { public: typedef std::vector Operations; - + private: // fields - + /** * @brief list of operations in this ExecutionGroup */ Operations m_operations; - + /** * @brief is this ExecutionGroup an input ExecutionGroup * an input execution group is a group that is at the end of the calculation (the output is important for the user) */ int m_isOutput; - + /** * @brief Width of the output */ unsigned int m_width; - + /** * @brief Height of the output */ unsigned int m_height; - + /** * @brief size of a single chunk, being Width or of height * a chunk is always a square, except at the edges of the MemoryBuffer */ unsigned int m_chunkSize; - + /** * @brief number of chunks in the x-axis */ unsigned int m_numberOfXChunks; - + /** * @brief number of chunks in the y-axis */ unsigned int m_numberOfYChunks; - + /** * @brief total number of chunks */ unsigned int m_numberOfChunks; - + /** * @brief contains this ExecutionGroup a complex NodeOperation. */ bool m_complex; - + /** * @brief can this ExecutionGroup be scheduled on an OpenCLDevice */ bool m_openCL; - + /** * @brief Is this Execution group SingleThreaded */ bool m_singleThreaded; - + /** * @brief what is the maximum number field of all ReadBufferOperation in this ExecutionGroup. * @note this is used to construct the MemoryBuffers that will be passed during execution. */ unsigned int m_cachedMaxReadBufferOffset; - + /** * @brief a cached vector of all read operations in the execution group. */ Operations m_cachedReadOperations; - + /** * @brief reference to the original bNodeTree, this field is only set for the 'top' execution group. * @note can only be used to call the callbacks for progress, status and break */ const bNodeTree *m_bTree; - + /** * @brief total number of chunks that have been calculated for this ExecutionGroup */ unsigned int m_chunksFinished; - + /** * @brief the chunkExecutionStates holds per chunk the execution state. this state can be * - COM_ES_NOT_SCHEDULED: not scheduled @@ -155,7 +155,7 @@ class ExecutionGroup { * - COM_ES_EXECUTED: executed */ ChunkExecutionState *m_chunkExecutionStates; - + /** * @brief indicator when this ExecutionGroup has valid Operations in its vector for Execution * @note When building the ExecutionGroup Operations are added via recursion. First a WriteBufferOperations is added, then the @@ -184,7 +184,7 @@ class ExecutionGroup { * @param operation the operation to be added */ bool canContainOperation(NodeOperation *operation); - + /** * @brief calculate the actual chunk size of this execution group. * @note A chunk size is an unsigned int that is both the height and width of a chunk. @@ -192,21 +192,21 @@ class ExecutionGroup { * @note by the calling method. */ unsigned int determineChunkSize(); - - + + /** * @brief Determine the rect (minx, maxx, miny, maxy) of a chunk at a position. * @note Only gives useful results ater the determination of the chunksize * @see determineChunkSize() */ void determineChunkRect(rcti *rect, const unsigned int xChunk, const unsigned int yChunk) const; - + /** * @brief determine the number of chunks, based on the chunkSize, width and height. * @note The result are stored in the fields numberOfChunks, numberOfXChunks, numberOfYChunks */ void determineNumberOfChunks(); - + /** * @brief try to schedule a specific chunk. * @note scheduling succeeds when all input requirements are met and the chunks hasn't been scheduled yet. @@ -236,7 +236,7 @@ class ExecutionGroup { * @param chunknumber */ bool scheduleChunk(unsigned int chunkNumber); - + /** * @brief determine the area of interest of a certain input area * @note This method only evaluates a single ReadBufferOperation @@ -250,7 +250,7 @@ class ExecutionGroup { public: // constructors ExecutionGroup(); - + // methods /** * @brief add an operation to this ExecutionGroup @@ -261,7 +261,7 @@ class ExecutionGroup { * @return True if the operation was successfully added */ bool addOperation(NodeOperation *operation); - + /** * @brief is this ExecutionGroup an output ExecutionGroup * @note An OutputExecution group are groups containing a @@ -281,47 +281,47 @@ class ExecutionGroup { * @param resolution */ void determineResolution(unsigned int resolution[2]); - + /** * @brief set the resolution of this executiongroup * @param resolution */ void setResolution(unsigned int resolution[2]) { this->m_width = resolution[0]; this->m_height = resolution[1]; } - + /** * @brief get the width of this execution group */ unsigned int getWidth() const { return m_width; } - + /** * @brief get the height of this execution group */ unsigned int getHeight() const { return m_height; } - + /** * @brief does this ExecutionGroup contains a complex NodeOperation */ bool isComplex() const { return m_complex; } - - + + /** * @brief get the output operation of this ExecutionGroup * @return NodeOperation *output operation */ NodeOperation *getOutputOperation() const; - + /** * @brief compose multiple chunks into a single chunk * @return Memorybuffer *consolidated chunk */ MemoryBuffer *constructConsolidatedMemoryBuffer(MemoryProxy *memoryProxy, rcti *output); - + /** * @brief initExecution is called just before the execution of the whole graph will be done. * @note The implementation will calculate the chunkSize of this execution group. */ void initExecution(); - + /** * @brief get all inputbuffers needed to calculate an chunk * @note all inputbuffers must be executed @@ -352,14 +352,14 @@ class ExecutionGroup { * @param memorybuffers */ void finalizeChunkExecution(int chunkNumber, MemoryBuffer **memoryBuffers); - + /** * @brief deinitExecution is called just after execution the whole graph. * @note It will release all needed resources */ void deinitExecution(); - - + + /** * @brief schedule an ExecutionGroup * @note this method will return when all chunks have been calculated, or the execution has breaked (by user) @@ -375,7 +375,7 @@ class ExecutionGroup { * @param system */ void execute(ExecutionSystem *system); - + /** * @brief this method determines the MemoryProxy's where this execution group depends on. * @note After this method determineDependingAreaOfInterest can be called to determine @@ -383,7 +383,7 @@ class ExecutionGroup { * @param memoryProxies result */ void determineDependingMemoryProxies(vector *memoryProxies); - + /** * @brief Determine the rect (minx, maxx, miny, maxy) of a chunk. * @note Only gives useful results ater the determination of the chunksize diff --git a/source/blender/compositor/intern/COM_ExecutionSystem.cpp b/source/blender/compositor/intern/COM_ExecutionSystem.cpp index 8e8539e30162..07f7979629cf 100644 --- a/source/blender/compositor/intern/COM_ExecutionSystem.cpp +++ b/source/blender/compositor/intern/COM_ExecutionSystem.cpp @@ -132,7 +132,7 @@ void ExecutionSystem::execute() editingtree->stats_draw(editingtree->sdh, IFACE_("Compositing | Initializing execution")); DebugInfo::execute_started(this); - + unsigned int order = 0; for (vector::iterator iter = this->m_operations.begin(); iter != this->m_operations.end(); ++iter) { NodeOperation *operation = *iter; diff --git a/source/blender/compositor/intern/COM_ExecutionSystem.h b/source/blender/compositor/intern/COM_ExecutionSystem.h index 2c67a5f7b7f3..0990df31c559 100644 --- a/source/blender/compositor/intern/COM_ExecutionSystem.h +++ b/source/blender/compositor/intern/COM_ExecutionSystem.h @@ -22,8 +22,8 @@ class ExecutionGroup; -#ifndef _COM_ExecutionSystem_h -#define _COM_ExecutionSystem_h +#ifndef __COM_EXECUTIONSYSTEM_H__ +#define __COM_EXECUTIONSYSTEM_H__ #include "DNA_color_types.h" #include "DNA_node_types.h" @@ -114,7 +114,7 @@ class ExecutionSystem { public: typedef std::vector Operations; typedef std::vector Groups; - + private: /** * @brief the context used during execution @@ -136,7 +136,7 @@ class ExecutionSystem { * find all execution group with output nodes */ void findOutputExecutionGroup(vector *result, CompositorPriority priority) const; - + /** * find all execution group with output nodes */ @@ -185,4 +185,4 @@ class ExecutionSystem { #endif }; -#endif /* _COM_ExecutionSystem_h */ +#endif /* __COM_EXECUTIONSYSTEM_H__ */ diff --git a/source/blender/compositor/intern/COM_MemoryBuffer.h b/source/blender/compositor/intern/COM_MemoryBuffer.h index 27baca0ab6f4..5f6485475d04 100644 --- a/source/blender/compositor/intern/COM_MemoryBuffer.h +++ b/source/blender/compositor/intern/COM_MemoryBuffer.h @@ -22,8 +22,8 @@ class MemoryBuffer; -#ifndef _COM_MemoryBuffer_h_ -#define _COM_MemoryBuffer_h_ +#ifndef __COM_MEMORYBUFFER_H__ +#define __COM_MEMORYBUFFER_H__ #include "COM_ExecutionGroup.h" #include "COM_MemoryProxy.h" @@ -64,29 +64,29 @@ class MemoryBuffer { * @brief proxy of the memory (same for all chunks in the same buffer) */ MemoryProxy *m_memoryProxy; - + /** * @brief the type of buffer COM_DT_VALUE, COM_DT_VECTOR, COM_DT_COLOR */ DataType m_datatype; - - + + /** * @brief region of this buffer inside relative to the MemoryProxy */ rcti m_rect; - + /** * brief refers to the chunknumber within the executiongroup where related to the MemoryProxy * @see memoryProxy */ unsigned int m_chunkNumber; - + /** * @brief state of the buffer */ MemoryBufferState m_state; - + /** * @brief the actual float buffer/data */ @@ -106,7 +106,7 @@ class MemoryBuffer { * @brief construct new MemoryBuffer for a chunk */ MemoryBuffer(MemoryProxy *memoryProxy, unsigned int chunkNumber, rcti *rect); - + /** * @brief construct new temporarily MemoryBuffer for an area */ @@ -121,7 +121,7 @@ class MemoryBuffer { * @brief destructor */ ~MemoryBuffer(); - + /** * @brief read the ChunkNumber of this MemoryBuffer */ @@ -134,7 +134,7 @@ class MemoryBuffer { * @note buffer should already be available in memory */ float *getBuffer() { return this->m_buffer; } - + /** * @brief after execution the state will be set to available by calling this method */ @@ -142,14 +142,14 @@ class MemoryBuffer { { this->m_state = COM_MB_AVAILABLE; } - + inline void wrap_pixel(int &x, int &y, MemoryBufferExtend extend_x, MemoryBufferExtend extend_y) { int w = this->m_width; int h = this->m_height; x = x - m_rect.xmin; y = y - m_rect.ymin; - + switch (extend_x) { case COM_MB_CLIP: break; @@ -161,7 +161,7 @@ class MemoryBuffer { x = (x >= 0.0f ? (x % w) : (x % w) + w); break; } - + switch (extend_y) { case COM_MB_CLIP: break; @@ -174,7 +174,7 @@ class MemoryBuffer { break; } } - + inline void wrap_pixel(float &x, float &y, MemoryBufferExtend extend_x, MemoryBufferExtend extend_y) { float w = (float)this->m_width; @@ -249,7 +249,7 @@ class MemoryBuffer { float *buffer = &this->m_buffer[offset]; memcpy(result, buffer, sizeof(float) * this->m_num_channels); } - + void writePixel(int x, int y, const float color[4]); void addPixel(int x, int y, const float color[4]); inline void readBilinear(float *result, float x, float y, @@ -271,12 +271,12 @@ class MemoryBuffer { } void readEWA(float *result, const float uv[2], const float derivatives[2][2]); - + /** * @brief is this MemoryBuffer a temporarily buffer (based on an area, not on a chunk) */ inline const bool isTemporarily() const { return this->m_state == COM_MB_TEMPORARILY; } - + /** * @brief add the content from otherBuffer to this MemoryBuffer * @param otherBuffer source buffer @@ -285,29 +285,29 @@ class MemoryBuffer { * uninitialized values in areas where the buffers don't overlap. */ void copyContentFrom(MemoryBuffer *otherBuffer); - + /** * @brief get the rect of this MemoryBuffer */ rcti *getRect() { return &this->m_rect; } - + /** * @brief get the width of this MemoryBuffer */ int getWidth() const; - + /** * @brief get the height of this MemoryBuffer */ int getHeight() const; - + /** * @brief clear the buffer. Make all pixels black transparent. */ void clear(); - + MemoryBuffer *duplicate(); - + float getMaximumValue(); float getMaximumValue(rcti *rect); private: diff --git a/source/blender/compositor/intern/COM_MemoryProxy.cpp b/source/blender/compositor/intern/COM_MemoryProxy.cpp index 138b508c45b3..b995f556db2d 100644 --- a/source/blender/compositor/intern/COM_MemoryProxy.cpp +++ b/source/blender/compositor/intern/COM_MemoryProxy.cpp @@ -48,4 +48,3 @@ void MemoryProxy::free() this->m_buffer = NULL; } } - diff --git a/source/blender/compositor/intern/COM_MemoryProxy.h b/source/blender/compositor/intern/COM_MemoryProxy.h index 755d513c72ff..a628c09fa1f4 100644 --- a/source/blender/compositor/intern/COM_MemoryProxy.h +++ b/source/blender/compositor/intern/COM_MemoryProxy.h @@ -23,8 +23,8 @@ class MemoryProxy; -#ifndef _COM_MemoryProxy_h_ -#define _COM_MemoryProxy_h_ +#ifndef __COM_MEMORYPROXY_H__ +#define __COM_MEMORYPROXY_H__ #include "COM_ExecutionGroup.h" class ExecutionGroup; @@ -42,17 +42,17 @@ class MemoryProxy { * @brief reference to the ouput operation of the executiongroup */ WriteBufferOperation *m_writeBufferOperation; - + /** * @brief reference to the executor. the Execution group that can fill a chunk */ ExecutionGroup *m_executor; - + /** * @brief datatype of this MemoryProxy */ /* DataType m_datatype; */ /* UNUSED */ - + /** * @brief channel information of this buffer */ @@ -70,7 +70,7 @@ class MemoryProxy { public: MemoryProxy(DataType type); - + /** * @brief set the ExecutionGroup that can be scheduled to calculate a certain chunk. * @param group the ExecutionGroup to set diff --git a/source/blender/compositor/intern/COM_Node.cpp b/source/blender/compositor/intern/COM_Node.cpp index a374403fef7f..67b64baa26e0 100644 --- a/source/blender/compositor/intern/COM_Node.cpp +++ b/source/blender/compositor/intern/COM_Node.cpp @@ -54,7 +54,7 @@ Node::Node(bNode *editorNode, bool create_sockets) : DataType dt = COM_DT_VALUE; if (input->type == SOCK_RGBA) dt = COM_DT_COLOR; if (input->type == SOCK_VECTOR) dt = COM_DT_VECTOR; - + this->addInputSocket(dt, input); input = input->next; } @@ -63,7 +63,7 @@ Node::Node(bNode *editorNode, bool create_sockets) : DataType dt = COM_DT_VALUE; if (output->type == SOCK_RGBA) dt = COM_DT_COLOR; if (output->type == SOCK_VECTOR) dt = COM_DT_VECTOR; - + this->addOutputSocket(dt, output); output = output->next; } @@ -96,7 +96,7 @@ void Node::addInputSocket(DataType datatype, bNodeSocket *bSocket) void Node::addOutputSocket(DataType datatype) { this->addOutputSocket(datatype, NULL); - + } void Node::addOutputSocket(DataType datatype, bNodeSocket *bSocket) { diff --git a/source/blender/compositor/intern/COM_Node.h b/source/blender/compositor/intern/COM_Node.h index 1c28292fb2e8..1b78e7fec6d3 100644 --- a/source/blender/compositor/intern/COM_Node.h +++ b/source/blender/compositor/intern/COM_Node.h @@ -45,13 +45,13 @@ class Node { public: typedef std::vector Inputs; typedef std::vector Outputs; - + private: /** * @brief stores the reference to the SDNA bNode struct */ bNodeTree *m_editorNodeTree; - + /** * @brief stores the reference to the SDNA bNode struct */ @@ -82,7 +82,7 @@ class Node { * @brief get access to the vector of input sockets */ const Inputs &getInputSockets() const { return this->m_inputsockets; } - + /** * @brief get access to the vector of input sockets */ @@ -101,14 +101,14 @@ class Node { * @brief get the reference to the SDNA bNodeTree struct */ bNodeTree *getbNodeTree() const {return m_editorNodeTree;} - + /** * @brief set the reference to the bNode * @note used in Node instances to receive the storage/settings and complex node for highlight during execution * @param bNode */ void setbNode(bNode *node) {this->m_editorNode = node;} - + /** * @brief set the reference to the bNodeTree * @param bNodeTree @@ -131,35 +131,35 @@ class Node { * the index of the needed outputsocket */ NodeOutput *getOutputSocket(const unsigned int index) const; - + /** * get the reference to the first outputsocket * @param index * the index of the needed outputsocket */ inline NodeOutput *getOutputSocket() const { return getOutputSocket(0); } - + /** * get the reference to a certain inputsocket * @param index * the index of the needed inputsocket */ NodeInput *getInputSocket(const unsigned int index) const; - + /** Check if this is an input node * An input node is a node that only has output sockets and no input sockets */ bool isInputNode() const { return m_inputsockets.empty(); } - + /** * @brief Is this node in the active group (the group that is being edited) * @param isInActiveGroup */ void setIsInActiveGroup(bool value) { this->m_inActiveGroup = value; } - + /** * @brief Is this node part of the active group - * the active group is the group that is currently being edited. When no group is edited, + * the active group is the group that is currently being edited. When no group is edited, * the active group will be the main tree (all nodes that are not part of a group will be active) * @return bool [false:true] */ @@ -174,7 +174,7 @@ class Node { * @param context reference to the CompositorContext */ virtual void convertToOperations(NodeConverter &converter, const CompositorContext &context) const = 0; - + /** * Create dummy warning operation, use when we can't get the source data. */ @@ -185,10 +185,10 @@ class Node { * into valid outputs, without this the compositor system gets confused and crashes, see [#32490] */ void convertToOperations_invalid(NodeConverter *compiler) const; - + void setInstanceKey(bNodeInstanceKey instance_key) { m_instanceKey = instance_key; } bNodeInstanceKey getInstanceKey() const { return m_instanceKey; } - + protected: /** * @brief add an NodeInput to the collection of inputsockets @@ -197,7 +197,7 @@ class Node { */ void addInputSocket(DataType datatype); void addInputSocket(DataType datatype, bNodeSocket *socket); - + /** * @brief add an NodeOutput to the collection of outputsockets * @note may only be called in an constructor @@ -205,7 +205,7 @@ class Node { */ void addOutputSocket(DataType datatype); void addOutputSocket(DataType datatype, bNodeSocket *socket); - + bNodeSocket *getEditorInputSocket(int editorNodeInputSocketIndex); bNodeSocket *getEditorOutputSocket(int editorNodeOutputSocketIndex); }; @@ -219,26 +219,26 @@ class NodeInput { private: Node *m_node; bNodeSocket *m_editorSocket; - + DataType m_datatype; - + /** * @brief link connected to this NodeInput. * An input socket can only have a single link */ NodeOutput *m_link; - + public: NodeInput(Node *node, bNodeSocket *b_socket, DataType datatype); - + Node *getNode() const { return this->m_node; } DataType getDataType() const { return m_datatype; } bNodeSocket *getbNodeSocket() const { return this->m_editorSocket; } - + void setLink(NodeOutput *link); bool isLinked() const { return m_link; } NodeOutput *getLink() { return m_link; } - + float getEditorValueFloat(); void getEditorValueColor(float *value); void getEditorValueVector(float *value); @@ -253,16 +253,16 @@ class NodeOutput { private: Node *m_node; bNodeSocket *m_editorSocket; - + DataType m_datatype; - + public: NodeOutput(Node *node, bNodeSocket *b_socket, DataType datatype); - + Node *getNode() const { return this->m_node; } DataType getDataType() const { return m_datatype; } bNodeSocket *getbNodeSocket() const { return this->m_editorSocket; } - + float getEditorValueFloat(); void getEditorValueColor(float *value); void getEditorValueVector(float *value); diff --git a/source/blender/compositor/intern/COM_NodeConverter.cpp b/source/blender/compositor/intern/COM_NodeConverter.cpp index df8a7e6353c6..1b62466f81fc 100644 --- a/source/blender/compositor/intern/COM_NodeConverter.cpp +++ b/source/blender/compositor/intern/COM_NodeConverter.cpp @@ -73,13 +73,13 @@ NodeOperation *NodeConverter::setInvalidOutput(NodeOutput *output) { /* this is a really bad situation - bring on the pink! - so artists know this is bad */ const float warning_color[4] = {1.0f, 0.0f, 1.0f, 1.0f}; - + SetColorOperation *operation = new SetColorOperation(); operation->setChannels(warning_color); - + m_builder->addOperation(operation); m_builder->mapOutputSocket(output, operation->getOutputSocket()); - + return operation; } @@ -87,9 +87,9 @@ NodeOperationOutput *NodeConverter::addInputProxy(NodeInput *input, bool use_con { SocketProxyOperation *proxy = new SocketProxyOperation(input->getDataType(), use_conversion); m_builder->addOperation(proxy); - + m_builder->mapInputSocket(input, proxy->getInputSocket(0)); - + return proxy->getOutputSocket(); } @@ -97,9 +97,9 @@ NodeOperationInput *NodeConverter::addOutputProxy(NodeOutput *output, bool use_c { SocketProxyOperation *proxy = new SocketProxyOperation(output->getDataType(), use_conversion); m_builder->addOperation(proxy); - + m_builder->mapOutputSocket(output, proxy->getOutputSocket()); - + return proxy->getInputSocket(0); } @@ -107,7 +107,7 @@ void NodeConverter::addInputValue(NodeOperationInput *input, float value) { SetValueOperation *operation = new SetValueOperation(); operation->setValue(value); - + m_builder->addOperation(operation); m_builder->addLink(operation->getOutputSocket(), input); } @@ -116,7 +116,7 @@ void NodeConverter::addInputColor(NodeOperationInput *input, const float value[4 { SetColorOperation *operation = new SetColorOperation(); operation->setChannels(value); - + m_builder->addOperation(operation); m_builder->addLink(operation->getOutputSocket(), input); } @@ -125,7 +125,7 @@ void NodeConverter::addInputVector(NodeOperationInput *input, const float value[ { SetVectorOperation *operation = new SetVectorOperation(); operation->setVector(value); - + m_builder->addOperation(operation); m_builder->addLink(operation->getOutputSocket(), input); } @@ -134,7 +134,7 @@ void NodeConverter::addOutputValue(NodeOutput *output, float value) { SetValueOperation *operation = new SetValueOperation(); operation->setValue(value); - + m_builder->addOperation(operation); m_builder->mapOutputSocket(output, operation->getOutputSocket()); } @@ -143,7 +143,7 @@ void NodeConverter::addOutputColor(NodeOutput *output, const float value[4]) { SetColorOperation *operation = new SetColorOperation(); operation->setChannels(value); - + m_builder->addOperation(operation); m_builder->mapOutputSocket(output, operation->getOutputSocket()); } @@ -152,7 +152,7 @@ void NodeConverter::addOutputVector(NodeOutput *output, const float value[3]) { SetVectorOperation *operation = new SetVectorOperation(); operation->setVector(value); - + m_builder->addOperation(operation); m_builder->mapOutputSocket(output, operation->getOutputSocket()); } diff --git a/source/blender/compositor/intern/COM_NodeConverter.h b/source/blender/compositor/intern/COM_NodeConverter.h index fb7529ae2a76..4fb6b70ad1b8 100644 --- a/source/blender/compositor/intern/COM_NodeConverter.h +++ b/source/blender/compositor/intern/COM_NodeConverter.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_NodeCompiler_h -#define _COM_NodeCompiler_h +#ifndef __COM_NODECONVERTER_H__ +#define __COM_NODECONVERTER_H__ #ifdef WITH_CXX_GUARDEDALLOC # include "MEM_guardedalloc.h" @@ -44,28 +44,28 @@ class ViewerOperation; class NodeConverter { public: NodeConverter(NodeOperationBuilder *builder); - + /** Insert a new operation into the operations graph. * The operation must be created by the node. */ void addOperation(NodeOperation *operation); - + /** Map input socket of the node to an operation socket. * Links between nodes will then generate equivalent links between * the mapped operation sockets. - * + * * \note A \a Node input can be mapped to multiple \a NodeOperation inputs. */ void mapInputSocket(NodeInput *node_socket, NodeOperationInput *operation_socket); /** Map output socket of the node to an operation socket. * Links between nodes will then generate equivalent links between * the mapped operation sockets. - * + * * \note A \a Node output can only be mapped to one \a NodeOperation output. * Any existing operation output mapping will be replaced. */ void mapOutputSocket(NodeOutput *node_socket, NodeOperationOutput *operation_socket); - + /** Create a proxy operation for a node input. * This operation will be removed later and replaced * by direct links between the connected operations. @@ -76,39 +76,39 @@ class NodeConverter { * by direct links between the connected operations. */ NodeOperationInput *addOutputProxy(NodeOutput *output, bool use_conversion); - + /** Define a constant input value. */ void addInputValue(NodeOperationInput *input, float value); /** Define a constant input color. */ void addInputColor(NodeOperationInput *input, const float value[4]); /** Define a constant input vector. */ void addInputVector(NodeOperationInput *input, const float value[3]); - + /** Define a constant output value. */ void addOutputValue(NodeOutput *output, float value); /** Define a constant output color. */ void addOutputColor(NodeOutput *output, const float value[4]); /** Define a constant output vector. */ void addOutputVector(NodeOutput *output, const float value[3]); - + /** Add an explicit link between two operations. */ void addLink(NodeOperationOutput *from, NodeOperationInput *to); - + /** Add a preview operation for a operation output. */ void addPreview(NodeOperationOutput *output); /** Add a preview operation for a node input. */ void addNodeInputPreview(NodeInput *input); - + /** When a node has no valid data * @note missing image / group pointer, or missing renderlayer from EXR */ NodeOperation *setInvalidOutput(NodeOutput *output); - + /** Define a viewer operation as the active output, if possible */ void registerViewer(ViewerOperation *viewer); /** The currently active viewer output operation */ ViewerOperation *active_viewer() const; - + private: /** The internal builder for storing the results of the graph construction. */ NodeOperationBuilder *m_builder; @@ -118,4 +118,4 @@ class NodeConverter { #endif }; -#endif /* _COM_NodeCompiler_h */ +#endif /* __COM_NODECONVERTER_H__ */ diff --git a/source/blender/compositor/intern/COM_NodeGraph.cpp b/source/blender/compositor/intern/COM_NodeGraph.cpp index 5196108818b7..d78450074ed7 100644 --- a/source/blender/compositor/intern/COM_NodeGraph.cpp +++ b/source/blender/compositor/intern/COM_NodeGraph.cpp @@ -82,16 +82,16 @@ void NodeGraph::add_node(Node *node, bNodeTree *b_ntree, bNodeInstanceKey key, b node->setbNodeTree(b_ntree); node->setInstanceKey(key); node->setIsInActiveGroup(is_active_group); - + m_nodes.push_back(node); - + DebugInfo::node_added(node); } void NodeGraph::add_link(NodeOutput *fromSocket, NodeInput *toSocket) { m_links.push_back(Link(fromSocket, toSocket)); - + /* register with the input */ toSocket->setLink(fromSocket); } @@ -99,10 +99,10 @@ void NodeGraph::add_link(NodeOutput *fromSocket, NodeInput *toSocket) void NodeGraph::add_bNodeTree(const CompositorContext &context, int nodes_start, bNodeTree *tree, bNodeInstanceKey parent_key) { const bNodeTree *basetree = context.getbNodeTree(); - + /* update viewers in the active edittree as well the base tree (for backdrop) */ bool is_active_group = (parent_key.value == basetree->active_viewer_key.value); - + /* add all nodes of the tree to the node list */ for (bNode *node = (bNode *)tree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, tree, node); @@ -123,13 +123,13 @@ void NodeGraph::add_bNode(const CompositorContext &context, bNodeTree *b_ntree, add_proxies_mute(b_ntree, b_node, key, is_active_group); return; } - + /* replace slow nodes with proxies for fast execution */ if (context.isFastCalculation() && !Converter::is_fast_node(b_node)) { add_proxies_skip(b_ntree, b_node, key, is_active_group); return; } - + /* special node types */ if (b_node->type == NODE_GROUP) { add_proxies_group(context, b_node, key); @@ -181,15 +181,15 @@ void NodeGraph::add_bNodeLink(const NodeRange &node_range, bNodeLink *b_nodelink return; if ((b_nodelink->fromsock->flag & SOCK_UNAVAIL) || (b_nodelink->tosock->flag & SOCK_UNAVAIL)) return; - + /* Note: a DNA input socket can have multiple NodeInput in the compositor tree! (proxies) * The output then gets linked to each one of them. */ - + NodeOutput *output = find_output(node_range, b_nodelink->fromsock); if (!output) return; - + NodeInputs inputs = find_inputs(node_range, b_nodelink->tosock); for (NodeInputs::const_iterator it = inputs.begin(); it != inputs.end(); ++it) { NodeInput *input = *it; @@ -213,13 +213,13 @@ void NodeGraph::add_proxies_skip(bNodeTree *b_ntree, bNode *b_node, bNodeInstanc { for (bNodeSocket *output = (bNodeSocket *)b_node->outputs.first; output; output = output->next) { bNodeSocket *input; - + /* look for first input with matching datatype for each output */ for (input = (bNodeSocket *)b_node->inputs.first; input; input = input->next) { if (input->type == output->type) break; } - + if (input) { SocketProxyNode *proxy = new SocketProxyNode(b_node, input, output, true); add_node(proxy, b_ntree, key, is_active_group); @@ -231,11 +231,11 @@ void NodeGraph::add_proxies_group_inputs(bNode *b_node, bNode *b_node_io) { bNodeTree *b_group_tree = (bNodeTree *)b_node->id; BLI_assert(b_group_tree); /* should have been checked in advance */ - + /* not important for proxies */ bNodeInstanceKey key = NODE_INSTANCE_KEY_BASE; bool is_active_group = false; - + for (bNodeSocket *b_sock_io = (bNodeSocket *)b_node_io->outputs.first; b_sock_io; b_sock_io = b_sock_io->next) { bNodeSocket *b_sock_group = find_b_node_input(b_node, b_sock_io->identifier); if (b_sock_group) { @@ -249,11 +249,11 @@ void NodeGraph::add_proxies_group_outputs(bNode *b_node, bNode *b_node_io, bool { bNodeTree *b_group_tree = (bNodeTree *)b_node->id; BLI_assert(b_group_tree); /* should have been checked in advance */ - + /* not important for proxies */ bNodeInstanceKey key = NODE_INSTANCE_KEY_BASE; bool is_active_group = false; - + for (bNodeSocket *b_sock_io = (bNodeSocket *)b_node_io->inputs.first; b_sock_io; b_sock_io = b_sock_io->next) { bNodeSocket *b_sock_group = find_b_node_output(b_node, b_sock_io->identifier); if (b_sock_group) { @@ -286,11 +286,11 @@ void NodeGraph::add_proxies_group(const CompositorContext &context, bNode *b_nod for (bNode *b_node_io = (bNode *)b_group_tree->nodes.first; b_node_io; b_node_io = b_node_io->next) { if (b_node_io->type == NODE_GROUP_INPUT) add_proxies_group_inputs(b_node, b_node_io); - + if (b_node_io->type == NODE_GROUP_OUTPUT && (b_node_io->flag & NODE_DO_OUTPUT)) add_proxies_group_outputs(b_node, b_node_io, context.isGroupnodeBufferEnabled()); } - + add_bNodeTree(context, nodes_start, b_group_tree, key); } diff --git a/source/blender/compositor/intern/COM_NodeGraph.h b/source/blender/compositor/intern/COM_NodeGraph.h index fe8740fee971..4513a7721d6c 100644 --- a/source/blender/compositor/intern/COM_NodeGraph.h +++ b/source/blender/compositor/intern/COM_NodeGraph.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_NodeGraph_h -#define _COM_NodeGraph_h +#ifndef __COM_NODEGRAPH_H__ +#define __COM_NODEGRAPH_H__ #include #include @@ -48,69 +48,69 @@ class NodeGraph { private: NodeOutput *m_from; NodeInput *m_to; - + public: Link(NodeOutput *from, NodeInput *to) : m_from(from), m_to(to) {} - + NodeOutput *getFromSocket() const { return m_from; } NodeInput *getToSocket() const { return m_to; } }; - + typedef std::vector Nodes; typedef Nodes::iterator NodeIterator; typedef std::vector Links; - + private: Nodes m_nodes; Links m_links; - + public: NodeGraph(); ~NodeGraph(); - + const Nodes &nodes() const { return m_nodes; } const Links &links() const { return m_links; } - + void from_bNodeTree(const CompositorContext &context, bNodeTree *tree); - + protected: typedef std::pair NodeRange; typedef std::vector NodeInputs; - + static bNodeSocket *find_b_node_input(bNode *b_node, const char *identifier); static bNodeSocket *find_b_node_output(bNode *b_node, const char *identifier); - + void add_node(Node *node, bNodeTree *b_ntree, bNodeInstanceKey key, bool is_active_group); void add_link(NodeOutput *fromSocket, NodeInput *toSocket); - + void add_bNodeTree(const CompositorContext &context, int nodes_start, bNodeTree *tree, bNodeInstanceKey parent_key); - + void add_bNode(const CompositorContext &context, bNodeTree *b_ntree, bNode *b_node, bNodeInstanceKey key, bool is_active_group); - + NodeInputs find_inputs(const NodeRange &node_range, bNodeSocket *b_socket); NodeOutput *find_output(const NodeRange &node_range, bNodeSocket *b_socket); void add_bNodeLink(const NodeRange &node_range, bNodeLink *bNodeLink); - + /* **** Special proxy node type conversions **** */ /* These nodes are not represented in the node graph themselves, * but converted into a number of proxy links */ - + void add_proxies_mute(bNodeTree *b_ntree, bNode *b_node, bNodeInstanceKey key, bool is_active_group); void add_proxies_skip(bNodeTree *b_ntree, bNode *b_node, bNodeInstanceKey key, bool is_active_group); - + void add_proxies_group_inputs(bNode *b_node, bNode *b_node_io); void add_proxies_group_outputs(bNode *b_node, bNode *b_node_io, bool use_buffer); void add_proxies_group(const CompositorContext &context, bNode *b_node, bNodeInstanceKey key); void add_proxies_reroute(bNodeTree *b_ntree, bNode *b_node, bNodeInstanceKey key, bool is_active_group); - + #ifdef WITH_CXX_GUARDEDALLOC MEM_CXX_CLASS_ALLOC_FUNCS("COM:NodeGraph") #endif }; -#endif /* _COM_NodeGraph_h */ +#endif /* __COM_NODEGRAPH_H__ */ diff --git a/source/blender/compositor/intern/COM_NodeOperation.cpp b/source/blender/compositor/intern/COM_NodeOperation.cpp index 496a27b379c0..1063386aa58b 100644 --- a/source/blender/compositor/intern/COM_NodeOperation.cpp +++ b/source/blender/compositor/intern/COM_NodeOperation.cpp @@ -83,7 +83,7 @@ void NodeOperation::determineResolution(unsigned int resolution[2], unsigned int { unsigned int temp[2]; unsigned int temp2[2]; - + for (unsigned int index = 0; index < m_inputs.size(); index++) { NodeOperationInput *input = m_inputs[index]; if (input->isConnected()) { diff --git a/source/blender/compositor/intern/COM_NodeOperation.h b/source/blender/compositor/intern/COM_NodeOperation.h index 1f3c72a820e2..9ab9156e7e45 100644 --- a/source/blender/compositor/intern/COM_NodeOperation.h +++ b/source/blender/compositor/intern/COM_NodeOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_Operation_h -#define _COM_Operation_h +#ifndef __COM_NODEOPERATION_H__ +#define __COM_NODEOPERATION_H__ #include #include @@ -81,11 +81,11 @@ class NodeOperation : public SocketReader { public: typedef std::vector Inputs; typedef std::vector Outputs; - + private: Inputs m_inputs; Outputs m_outputs; - + /** * @brief the index of the input socket that will be used to determine the resolution */ @@ -115,7 +115,7 @@ class NodeOperation : public SocketReader { * @see NodeOperation.getMutex retrieve a pointer to this mutex. */ ThreadMutex m_mutex; - + /** * @brief reference to the editing bNodeTree, used for break and update callback */ @@ -125,21 +125,21 @@ class NodeOperation : public SocketReader { * @brief set to truth when resolution for this operation is set */ bool m_isResolutionSet; - + public: virtual ~NodeOperation(); - + unsigned int getNumberOfInputSockets() const { return m_inputs.size(); } unsigned int getNumberOfOutputSockets() const { return m_outputs.size(); } NodeOperationOutput *getOutputSocket(unsigned int index) const; NodeOperationOutput *getOutputSocket() const { return getOutputSocket(0); } NodeOperationInput *getInputSocket(unsigned int index) const; - + /** Check if this is an input operation * An input operation is an operation that only has output sockets and no input sockets */ bool isInputOperation() const { return m_inputs.empty(); } - + /** * @brief determine the resolution of this node * @note this method will not set the resolution, this is the responsibility of the caller @@ -167,7 +167,7 @@ class NodeOperation : public SocketReader { void setbNodeTree(const bNodeTree *tree) { this->m_btree = tree; } virtual void initExecution(); - + /** * @brief when a chunk is executed by a CPUDevice, this method is called * @ingroup execution @@ -231,7 +231,7 @@ class NodeOperation : public SocketReader { this->m_isResolutionSet = true; } } - + void getConnectedInputSockets(Inputs *sockets); @@ -288,14 +288,14 @@ class NodeOperation : public SocketReader { * @see ExecutionGroup.addOperation */ bool isOpenCL() const { return this->m_openCL; } - + virtual bool isViewerOperation() const { return false; } virtual bool isPreviewOperation() const { return false; } virtual bool isFileOutputOperation() const { return false; } virtual bool isProxyOperation() const { return false; } - + virtual bool useDatatypeConversion() const { return true; } - + inline bool isBreaked() const { return this->m_btree->test_break(this->m_btree->tbh); } @@ -319,7 +319,7 @@ class NodeOperation : public SocketReader { void initMutex(); void lockMutex(); void unlockMutex(); - + /** * @brief set whether this operation is complex * @@ -345,35 +345,35 @@ class NodeOperation : public SocketReader { class NodeOperationInput { private: NodeOperation *m_operation; - + /** Datatype of this socket. Is used for automatically data transformation. * @section data-conversion */ DataType m_datatype; - + /** Resize mode of this socket */ InputResizeMode m_resizeMode; - + /** Connected output */ NodeOperationOutput *m_link; - + public: NodeOperationInput(NodeOperation *op, DataType datatype, InputResizeMode resizeMode = COM_SC_CENTER); - + NodeOperation &getOperation() const { return *m_operation; } DataType getDataType() const { return m_datatype; } - + void setLink(NodeOperationOutput *link) { m_link = link; } NodeOperationOutput *getLink() const { return m_link; } bool isConnected() const { return m_link; } - + void setResizeMode(InputResizeMode resizeMode) { this->m_resizeMode = resizeMode; } InputResizeMode getResizeMode() const { return this->m_resizeMode; } - + SocketReader *getReader(); - + void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + #ifdef WITH_CXX_GUARDEDALLOC MEM_CXX_CLASS_ALLOC_FUNCS("COM:NodeOperation") #endif @@ -383,18 +383,18 @@ class NodeOperationInput { class NodeOperationOutput { private: NodeOperation *m_operation; - + /** Datatype of this socket. Is used for automatically data transformation. * @section data-conversion */ DataType m_datatype; - + public: NodeOperationOutput(NodeOperation *op, DataType datatype); - + NodeOperation &getOperation() const { return *m_operation; } DataType getDataType() const { return m_datatype; } - + /** * @brief determine the resolution of this data going through this socket * @param resolution the result of this operation diff --git a/source/blender/compositor/intern/COM_NodeOperationBuilder.cpp b/source/blender/compositor/intern/COM_NodeOperationBuilder.cpp index fc1584e3dbb4..f282037823aa 100644 --- a/source/blender/compositor/intern/COM_NodeOperationBuilder.cpp +++ b/source/blender/compositor/intern/COM_NodeOperationBuilder.cpp @@ -58,18 +58,18 @@ void NodeOperationBuilder::convertToOperations(ExecutionSystem *system) { /* interface handle for nodes */ NodeConverter converter(this); - + for (int index = 0; index < m_graph.nodes().size(); index++) { Node *node = (Node *)m_graph.nodes()[index]; - + m_current_node = node; - + DebugInfo::node_to_operations(node); node->convertToOperations(converter, *m_context); } - + m_current_node = NULL; - + /* The input map constructed by nodes maps operation inputs to node inputs. * Inverting yields a map of node inputs to all connected operation inputs, * so multiple operations can use the same node input. @@ -77,12 +77,12 @@ void NodeOperationBuilder::convertToOperations(ExecutionSystem *system) OpInputInverseMap inverse_input_map; for (InputSocketMap::const_iterator it = m_input_map.begin(); it != m_input_map.end(); ++it) inverse_input_map[it->second].push_back(it->first); - + for (NodeGraph::Links::const_iterator it = m_graph.links().begin(); it != m_graph.links().end(); ++it) { const NodeGraph::Link &link = *it; NodeOutput *from = link.getFromSocket(); NodeInput *to = link.getToSocket(); - + NodeOperationOutput *op_from = find_operation_output(m_output_map, from); const OpInputs &op_to_list = find_operation_inputs(inverse_input_map, to); if (!op_from || op_to_list.empty()) { @@ -94,36 +94,36 @@ void NodeOperationBuilder::convertToOperations(ExecutionSystem *system) */ continue; } - + for (OpInputs::const_iterator it = op_to_list.begin(); it != op_to_list.end(); ++it) { NodeOperationInput *op_to = *it; addLink(op_from, op_to); } } - + add_operation_input_constants(); - + resolve_proxies(); - + add_datatype_conversions(); - + determineResolutions(); - + /* surround complex ops with read/write buffer */ add_complex_operation_buffers(); - + /* links not available from here on */ /* XXX make m_links a local variable to avoid confusion! */ m_links.clear(); - + prune_operations(); - + /* ensure topological (link-based) order of nodes */ /*sort_operations();*/ /* not needed yet */ - + /* create execution groups */ group_operations(); - + /* transfer resulting operations to the system */ system->set_operations(m_operations, m_groups); } @@ -137,7 +137,7 @@ void NodeOperationBuilder::mapInputSocket(NodeInput *node_socket, NodeOperationI { BLI_assert(m_current_node); BLI_assert(node_socket->getNode() == m_current_node); - + /* note: this maps operation sockets to node sockets. * for resolving links the map will be inverted first in convertToOperations, * to get a list of links for each node input socket. @@ -149,7 +149,7 @@ void NodeOperationBuilder::mapOutputSocket(NodeOutput *node_socket, NodeOperatio { BLI_assert(m_current_node); BLI_assert(node_socket->getNode() == m_current_node); - + m_output_map[node_socket] = operation_socket; } @@ -157,9 +157,9 @@ void NodeOperationBuilder::addLink(NodeOperationOutput *from, NodeOperationInput { if (to->isConnected()) return; - + m_links.push_back(Link(from, to)); - + /* register with the input */ to->setLink(from); } @@ -171,7 +171,7 @@ void NodeOperationBuilder::removeInputLink(NodeOperationInput *to) if (link.to() == to) { /* unregister with the input */ to->setLink(NULL); - + m_links.erase(it); return; } @@ -200,7 +200,7 @@ NodeOperationOutput *NodeOperationBuilder::find_operation_output(const OutputSoc PreviewOperation *NodeOperationBuilder::make_preview_operation() const { BLI_assert(m_current_node); - + if (!(m_current_node->getbNode()->flag & NODE_PREVIEW)) return NULL; /* previews only in the active group */ @@ -209,7 +209,7 @@ PreviewOperation *NodeOperationBuilder::make_preview_operation() const /* do not calculate previews of hidden nodes */ if (m_current_node->getbNode()->flag & NODE_HIDDEN) return NULL; - + bNodeInstanceHash *previews = m_context->getPreviewHash(); if (previews) { PreviewOperation *operation = new PreviewOperation(m_context->getViewSettings(), m_context->getDisplaySettings()); @@ -217,7 +217,7 @@ PreviewOperation *NodeOperationBuilder::make_preview_operation() const operation->verifyPreview(previews, m_current_node->getInstanceKey()); return operation; } - + return NULL; } @@ -226,7 +226,7 @@ void NodeOperationBuilder::addPreview(NodeOperationOutput *output) PreviewOperation *operation = make_preview_operation(); if (operation) { addOperation(operation); - + addLink(output, operation->getInputSocket(0)); } } @@ -236,7 +236,7 @@ void NodeOperationBuilder::addNodeInputPreview(NodeInput *input) PreviewOperation *operation = make_preview_operation(); if (operation) { addOperation(operation); - + mapInputSocket(input, operation->getInputSocket(0)); } } @@ -247,7 +247,7 @@ void NodeOperationBuilder::registerViewer(ViewerOperation *viewer) if (m_current_node->isInActiveGroup()) { /* deactivate previous viewer */ m_active_viewer->setActive(false); - + m_active_viewer = viewer; viewer->setActive(true); } @@ -269,13 +269,13 @@ void NodeOperationBuilder::add_datatype_conversions() Links convert_links; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; - + /* proxy operations can skip data type conversion */ NodeOperation *from_op = &link.from()->getOperation(); NodeOperation *to_op = &link.to()->getOperation(); if (!(from_op->useDatatypeConversion() || to_op->useDatatypeConversion())) continue; - + if (link.from()->getDataType() != link.to()->getDataType()) convert_links.push_back(link); } @@ -284,7 +284,7 @@ void NodeOperationBuilder::add_datatype_conversions() NodeOperation *converter = Converter::convertDataType(link.from(), link.to()); if (converter) { addOperation(converter); - + removeInputLink(link.to()); addLink(link.from(), converter->getInputSocket(0)); addLink(converter->getOutputSocket(0), link.to()); @@ -322,7 +322,7 @@ void NodeOperationBuilder::add_input_constant_value(NodeOperationInput *input, N value = node_input->getEditorValueFloat(); else value = 0.0f; - + SetValueOperation *op = new SetValueOperation(); op->setValue(value); addOperation(op); @@ -335,7 +335,7 @@ void NodeOperationBuilder::add_input_constant_value(NodeOperationInput *input, N node_input->getEditorValueColor(value); else zero_v4(value); - + SetColorOperation *op = new SetColorOperation(); op->setChannels(value); addOperation(op); @@ -348,7 +348,7 @@ void NodeOperationBuilder::add_input_constant_value(NodeOperationInput *input, N node_input->getEditorValueVector(value); else zero_v3(value); - + SetVectorOperation *op = new SetVectorOperation(); op->setVector(value); addOperation(op); @@ -370,17 +370,17 @@ void NodeOperationBuilder::resolve_proxies() proxy_links.push_back(link); } } - + for (Links::const_iterator it = proxy_links.begin(); it != proxy_links.end(); ++it) { const Link &link = *it; - + NodeOperationInput *to = link.to(); NodeOperationOutput *from = link.from(); do { /* walk upstream bypassing the proxy operation */ from = from->getOperation().getInputSocket(0)->getLink(); } while (from && from->getOperation().isProxyOperation()); - + removeInputLink(to); /* we may not have a final proxy input link, * in that case it just gets dropped @@ -395,7 +395,7 @@ void NodeOperationBuilder::determineResolutions() /* determine all resolutions of the operations (Width/Height) */ for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; - + if (op->isOutputOperation(m_context->isRendering()) && !op->isPreviewOperation()) { unsigned int resolution[2] = {0, 0}; unsigned int preferredResolution[2] = {0, 0}; @@ -403,10 +403,10 @@ void NodeOperationBuilder::determineResolutions() op->setResolution(resolution); } } - + for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; - + if (op->isOutputOperation(m_context->isRendering()) && op->isPreviewOperation()) { unsigned int resolution[2] = {0, 0}; unsigned int preferredResolution[2] = {0, 0}; @@ -414,13 +414,13 @@ void NodeOperationBuilder::determineResolutions() op->setResolution(resolution); } } - + /* add convert resolution operations when needed */ { Links convert_links; for (Links::const_iterator it = m_links.begin(); it != m_links.end(); ++it) { const Link &link = *it; - + if (link.to()->getResizeMode() != COM_SC_NO_RESIZE) { NodeOperation &from_op = link.from()->getOperation(); NodeOperation &to_op = link.to()->getOperation(); @@ -464,35 +464,35 @@ void NodeOperationBuilder::add_input_buffers(NodeOperation * /*operation*/, { if (!input->isConnected()) return; - + NodeOperationOutput *output = input->getLink(); if (output->getOperation().isReadBufferOperation()) { /* input is already buffered, no need to add another */ return; } - + /* this link will be replaced below */ removeInputLink(input); - + /* check of other end already has write operation, otherwise add a new one */ WriteBufferOperation *writeoperation = find_attached_write_buffer_operation(output); if (!writeoperation) { writeoperation = new WriteBufferOperation(output->getDataType()); writeoperation->setbNodeTree(m_context->getbNodeTree()); addOperation(writeoperation); - + addLink(output, writeoperation->getInputSocket(0)); - + writeoperation->readResolutionFromInputSocket(); } - + /* add readbuffer op for the input */ ReadBufferOperation *readoperation = new ReadBufferOperation(output->getDataType()); readoperation->setMemoryProxy(writeoperation->getMemoryProxy()); this->addOperation(readoperation); - + addLink(readoperation->getOutputSocket(), input); - + readoperation->readResolutionFromWriteBuffer(); } @@ -502,11 +502,11 @@ void NodeOperationBuilder::add_output_buffers(NodeOperation *operation, NodeOper OpInputs targets = cache_output_links(output); if (targets.empty()) return; - + WriteBufferOperation *writeOperation = NULL; for (OpInputs::const_iterator it = targets.begin(); it != targets.end(); ++it) { NodeOperationInput *target = *it; - + /* try to find existing write buffer operation */ if (target->getOperation().isWriteBufferOperation()) { BLI_assert(writeOperation == NULL); /* there should only be one write op connected */ @@ -517,30 +517,30 @@ void NodeOperationBuilder::add_output_buffers(NodeOperation *operation, NodeOper removeInputLink(target); } } - + /* if no write buffer operation exists yet, create a new one */ if (!writeOperation) { writeOperation = new WriteBufferOperation(operation->getOutputSocket()->getDataType()); writeOperation->setbNodeTree(m_context->getbNodeTree()); addOperation(writeOperation); - + addLink(output, writeOperation->getInputSocket(0)); } - + writeOperation->readResolutionFromInputSocket(); - + /* add readbuffer op for every former connected input */ for (OpInputs::const_iterator it = targets.begin(); it != targets.end(); ++it) { NodeOperationInput *target = *it; if (&target->getOperation() == writeOperation) continue; /* skip existing write op links */ - + ReadBufferOperation *readoperation = new ReadBufferOperation(operation->getOutputSocket()->getDataType()); readoperation->setMemoryProxy(writeOperation->getMemoryProxy()); addOperation(readoperation); - + addLink(readoperation->getOutputSocket(), target); - + readoperation->readResolutionFromWriteBuffer(); } } @@ -554,15 +554,15 @@ void NodeOperationBuilder::add_complex_operation_buffers() for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) if ((*it)->isComplex()) complex_ops.push_back(*it); - + for (Operations::const_iterator it = complex_ops.begin(); it != complex_ops.end(); ++it) { NodeOperation *op = *it; - + DebugInfo::operation_read_write_buffer(op); - + for (int index = 0; index < op->getNumberOfInputSockets(); index++) add_input_buffers(op, op->getInputSocket(index)); - + for (int index = 0; index < op->getNumberOfOutputSockets(); index++) add_output_buffers(op, op->getOutputSocket(index)); } @@ -575,13 +575,13 @@ static void find_reachable_operations_recursive(Tags &reachable, NodeOperation * if (reachable.find(op) != reachable.end()) return; reachable.insert(op); - + for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); if (input->isConnected()) find_reachable_operations_recursive(reachable, &input->getLink()->getOperation()); } - + /* associated write-buffer operations are executed as well */ if (op->isReadBufferOperation()) { ReadBufferOperation *read_op = (ReadBufferOperation *)op; @@ -595,17 +595,17 @@ void NodeOperationBuilder::prune_operations() Tags reachable; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; - + /* output operations are primary executed operations */ if (op->isOutputOperation(m_context->isRendering())) find_reachable_operations_recursive(reachable, op); } - + /* delete unreachable operations */ Operations reachable_ops; for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; - + if (reachable.find(op) != reachable.end()) reachable_ops.push_back(op); else @@ -621,13 +621,13 @@ static void sort_operations_recursive(NodeOperationBuilder::Operations &sorted, if (visited.find(op) != visited.end()) return; visited.insert(op); - + for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); if (input->isConnected()) sort_operations_recursive(sorted, visited, &input->getLink()->getOperation()); } - + sorted.push_back(op); } @@ -636,10 +636,10 @@ void NodeOperationBuilder::sort_operations() Operations sorted; sorted.reserve(m_operations.size()); Tags visited; - + for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) sort_operations_recursive(sorted, visited, *it); - + m_operations = sorted; } @@ -648,10 +648,10 @@ static void add_group_operations_recursive(Tags &visited, NodeOperation *op, Exe if (visited.find(op) != visited.end()) return; visited.insert(op); - + if (!group->addOperation(op)) return; - + /* add all eligible input ops to the group */ for (int i = 0; i < op->getNumberOfInputSockets(); ++i) { NodeOperationInput *input = op->getInputSocket(i); @@ -664,10 +664,10 @@ ExecutionGroup *NodeOperationBuilder::make_group(NodeOperation *op) { ExecutionGroup *group = new ExecutionGroup(); m_groups.push_back(group); - + Tags visited; add_group_operations_recursive(visited, op, group); - + return group; } @@ -675,17 +675,17 @@ void NodeOperationBuilder::group_operations() { for (Operations::const_iterator it = m_operations.begin(); it != m_operations.end(); ++it) { NodeOperation *op = *it; - + if (op->isOutputOperation(m_context->isRendering())) { ExecutionGroup *group = make_group(op); group->setOutputExecutionGroup(true); } - + /* add new groups for associated memory proxies where needed */ if (op->isReadBufferOperation()) { ReadBufferOperation *read_op = (ReadBufferOperation *)op; MemoryProxy *memproxy = read_op->getMemoryProxy(); - + if (memproxy->getExecutor() == NULL) { ExecutionGroup *group = make_group(memproxy->getWriteBufferOperation()); memproxy->setExecutor(group); diff --git a/source/blender/compositor/intern/COM_NodeOperationBuilder.h b/source/blender/compositor/intern/COM_NodeOperationBuilder.h index 2bb5b94c57f3..71622b1e9bb0 100644 --- a/source/blender/compositor/intern/COM_NodeOperationBuilder.h +++ b/source/blender/compositor/intern/COM_NodeOperationBuilder.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_NodeCompilerImpl_h -#define _COM_NodeCompilerImpl_h +#ifndef __COM_NODEOPERATIONBUILDER_H__ +#define __COM_NODEOPERATIONBUILDER_H__ #include #include @@ -52,48 +52,48 @@ class NodeOperationBuilder { private: NodeOperationOutput *m_from; NodeOperationInput *m_to; - + public: Link(NodeOperationOutput *from, NodeOperationInput *to) : m_from(from), m_to(to) {} - + NodeOperationOutput *from() const { return m_from; } NodeOperationInput *to() const { return m_to; } }; - + typedef std::vector Operations; typedef std::vector Links; typedef std::vector Groups; - + typedef std::map InputSocketMap; typedef std::map OutputSocketMap; - + typedef std::vector OpInputs; typedef std::map OpInputInverseMap; - + private: const CompositorContext *m_context; NodeGraph m_graph; - + Operations m_operations; Links m_links; Groups m_groups; - + /** Maps operation inputs to node inputs */ InputSocketMap m_input_map; /** Maps node outputs to operation outputs */ OutputSocketMap m_output_map; - + Node *m_current_node; - + /** Operation that will be writing to the viewer image * Only one operation can occupy this place at a time, * to avoid race conditions */ ViewerOperation *m_active_viewer; - + public: NodeOperationBuilder(const CompositorContext *context, bNodeTree *b_nodetree); ~NodeOperationBuilder(); @@ -103,43 +103,43 @@ class NodeOperationBuilder { void convertToOperations(ExecutionSystem *system); void addOperation(NodeOperation *operation); - + /** Map input socket of the current node to an operation socket */ void mapInputSocket(NodeInput *node_socket, NodeOperationInput *operation_socket); /** Map output socket of the current node to an operation socket */ void mapOutputSocket(NodeOutput *node_socket, NodeOperationOutput *operation_socket); - + void addLink(NodeOperationOutput *from, NodeOperationInput *to); void removeInputLink(NodeOperationInput *to); - + /** Add a preview operation for a operation output */ void addPreview(NodeOperationOutput *output); /** Add a preview operation for a node input */ void addNodeInputPreview(NodeInput *input); - + /** Define a viewer operation as the active output, if possible */ void registerViewer(ViewerOperation *viewer); /** The currently active viewer output operation */ ViewerOperation *active_viewer() const { return m_active_viewer; } - + protected: static NodeInput *find_node_input(const InputSocketMap &map, NodeOperationInput *op_input); static const OpInputs &find_operation_inputs(const OpInputInverseMap &map, NodeInput *node_input); static NodeOperationOutput *find_operation_output(const OutputSocketMap &map, NodeOutput *node_output); - + /** Add datatype conversion where needed */ void add_datatype_conversions(); - + /** Construct a constant value operation for every unconnected input */ void add_operation_input_constants(); void add_input_constant_value(NodeOperationInput *input, NodeInput *node_input); - + /** Replace proxy operations with direct links */ void resolve_proxies(); - + /** Calculate resolution for each operation */ void determineResolutions(); - + /** Helper function to store connected inputs for replacement */ OpInputs cache_output_links(NodeOperationOutput *output) const; /** Find a connected write buffer operation to an OpOutput */ @@ -148,17 +148,17 @@ class NodeOperationBuilder { void add_complex_operation_buffers(); void add_input_buffers(NodeOperation *operation, NodeOperationInput *input); void add_output_buffers(NodeOperation *operation, NodeOperationOutput *output); - + /** Remove unreachable operations */ void prune_operations(); - + /** Sort operations by link dependencies */ void sort_operations(); - + /** Create execution groups */ void group_operations(); ExecutionGroup *make_group(NodeOperation *op); - + private: PreviewOperation *make_preview_operation() const; @@ -167,4 +167,4 @@ class NodeOperationBuilder { #endif }; -#endif /* _COM_NodeCompilerImpl_h */ +#endif /* __COM_NODEOPERATIONBUILDER_H__ */ diff --git a/source/blender/compositor/intern/COM_OpenCLDevice.cpp b/source/blender/compositor/intern/COM_OpenCLDevice.cpp index 54044f747fb8..881c7b8f49ab 100644 --- a/source/blender/compositor/intern/COM_OpenCLDevice.cpp +++ b/source/blender/compositor/intern/COM_OpenCLDevice.cpp @@ -74,7 +74,7 @@ void OpenCLDevice::execute(WorkPackage *work) chunkNumber, inputBuffers, outputBuffer); delete outputBuffer; - + executionGroup->finalizeChunkExecution(chunkNumber, inputBuffers); } cl_mem OpenCLDevice::COM_clAttachMemoryBufferToKernelParameter(cl_kernel kernel, int parameterIndex, int offsetIndex, @@ -106,7 +106,7 @@ cl_mem OpenCLDevice::COM_clAttachMemoryBufferToKernelParameter(cl_kernel kernel, ReadBufferOperation *reader) { cl_int error; - + MemoryBuffer *result = reader->getInputMemoryBuffer(inputMemoryBuffers); const cl_image_format *imageFormat = determineImageFormat(result); diff --git a/source/blender/compositor/intern/COM_OpenCLDevice.h b/source/blender/compositor/intern/COM_OpenCLDevice.h index 78d3c66cb5c8..a3a5cd36902f 100644 --- a/source/blender/compositor/intern/COM_OpenCLDevice.h +++ b/source/blender/compositor/intern/COM_OpenCLDevice.h @@ -22,8 +22,8 @@ class OpenCLDevice; -#ifndef _COM_OpenCLDevice_h -#define _COM_OpenCLDevice_h +#ifndef __COM_OPENCLDEVICE_H__ +#define __COM_OPENCLDEVICE_H__ #include "COM_Device.h" #include "clew.h" @@ -42,17 +42,17 @@ class OpenCLDevice : public Device { * @brief opencl context */ cl_context m_context; - + /** * @brief opencl device */ cl_device_id m_device; - + /** * @brief opencl program */ cl_program m_program; - + /** * @brief opencl command queue */ @@ -72,8 +72,8 @@ class OpenCLDevice : public Device { * @param vendorID */ OpenCLDevice(cl_context context, cl_device_id device, cl_program program, cl_int vendorId); - - + + /** * @brief initialize the device * During initialization the OpenCL cl_command_queue is created @@ -81,13 +81,13 @@ class OpenCLDevice : public Device { * @see queue */ bool initialize(); - + /** * @brief deinitialize the device * During deintiialization the command queue is cleared */ void deinitialize(); - + /** * @brief execute a WorkPackage * @param work the WorkPackage to execute diff --git a/source/blender/compositor/intern/COM_SingleThreadedOperation.cpp b/source/blender/compositor/intern/COM_SingleThreadedOperation.cpp index 27d4d0951e8f..9ab67a400553 100644 --- a/source/blender/compositor/intern/COM_SingleThreadedOperation.cpp +++ b/source/blender/compositor/intern/COM_SingleThreadedOperation.cpp @@ -49,7 +49,7 @@ void SingleThreadedOperation::deinitExecution() void *SingleThreadedOperation::initializeTileData(rcti *rect) { if (this->m_cachedInstance) return this->m_cachedInstance; - + lockMutex(); if (this->m_cachedInstance == NULL) { // diff --git a/source/blender/compositor/intern/COM_SingleThreadedOperation.h b/source/blender/compositor/intern/COM_SingleThreadedOperation.h index 82d0b04e064e..b582e47dba79 100644 --- a/source/blender/compositor/intern/COM_SingleThreadedOperation.h +++ b/source/blender/compositor/intern/COM_SingleThreadedOperation.h @@ -20,14 +20,14 @@ * Monique Dewanchand */ -#ifndef _COM_SingleThreadedOperation_h -#define _COM_SingleThreadedOperation_h +#ifndef __COM_SINGLETHREADEDOPERATION_H__ +#define __COM_SINGLETHREADEDOPERATION_H__ #include "COM_NodeOperation.h" class SingleThreadedOperation : public NodeOperation { private: MemoryBuffer *m_cachedInstance; - + protected: inline bool isCached() { return this->m_cachedInstance != NULL; @@ -35,17 +35,17 @@ class SingleThreadedOperation : public NodeOperation { public: SingleThreadedOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -54,7 +54,7 @@ class SingleThreadedOperation : public NodeOperation { void *initializeTileData(rcti *rect); virtual MemoryBuffer *createMemoryBuffer(rcti *rect) = 0; - + int isSingleThreaded() { return true; } }; #endif diff --git a/source/blender/compositor/intern/COM_SocketReader.cpp b/source/blender/compositor/intern/COM_SocketReader.cpp index 7517abc14308..e28bd4c7d3d1 100644 --- a/source/blender/compositor/intern/COM_SocketReader.cpp +++ b/source/blender/compositor/intern/COM_SocketReader.cpp @@ -21,5 +21,3 @@ */ #include "COM_SocketReader.h" - - diff --git a/source/blender/compositor/intern/COM_SocketReader.h b/source/blender/compositor/intern/COM_SocketReader.h index ff72d9251844..af6b891e7abf 100644 --- a/source/blender/compositor/intern/COM_SocketReader.h +++ b/source/blender/compositor/intern/COM_SocketReader.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SocketReader_h -#define _COM_SocketReader_h +#ifndef __COM_SOCKETREADER_H__ +#define __COM_SOCKETREADER_H__ #include "BLI_rect.h" #include "COM_defines.h" @@ -121,4 +121,4 @@ class SocketReader { #endif }; -#endif /* _COM_SocketReader_h */ +#endif /* __COM_SOCKETREADER_H__ */ diff --git a/source/blender/compositor/intern/COM_WorkPackage.h b/source/blender/compositor/intern/COM_WorkPackage.h index 970a69b38d8e..b0a74a1b0ee0 100644 --- a/source/blender/compositor/intern/COM_WorkPackage.h +++ b/source/blender/compositor/intern/COM_WorkPackage.h @@ -22,8 +22,8 @@ class WorkPackage; -#ifndef _COM_WorkPackage_h_ -#define _COM_WorkPackage_h_ +#ifndef __COM_WORKPACKAGE_H__ +#define __COM_WORKPACKAGE_H__ class ExecutionGroup; #include "COM_ExecutionGroup.h" diff --git a/source/blender/compositor/intern/COM_WorkScheduler.cpp b/source/blender/compositor/intern/COM_WorkScheduler.cpp index ce45b9fdbe94..4136983e13ce 100644 --- a/source/blender/compositor/intern/COM_WorkScheduler.cpp +++ b/source/blender/compositor/intern/COM_WorkScheduler.cpp @@ -85,7 +85,7 @@ void *WorkScheduler::thread_execute_cpu(void *data) device->execute(work); delete work; } - + return NULL; } @@ -93,12 +93,12 @@ void *WorkScheduler::thread_execute_gpu(void *data) { Device *device = (Device *)data; WorkPackage *work; - + while ((work = (WorkPackage *)BLI_thread_queue_pop(g_gpuqueue))) { device->execute(work); delete work; } - + return NULL; } #endif diff --git a/source/blender/compositor/intern/COM_WorkScheduler.h b/source/blender/compositor/intern/COM_WorkScheduler.h index 7f07978a9c72..a08b3856a8b6 100644 --- a/source/blender/compositor/intern/COM_WorkScheduler.h +++ b/source/blender/compositor/intern/COM_WorkScheduler.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_WorkScheduler_h_ -#define _COM_WorkScheduler_h_ +#ifndef __COM_WORKSCHEDULER_H__ +#define __COM_WORKSCHEDULER_H__ #include "COM_ExecutionGroup.h" extern "C" { @@ -53,7 +53,7 @@ class WorkScheduler { * inside this loop new work is queried and being executed */ static void *thread_execute_gpu(void *data); -#endif +#endif public: /** * @brief schedule a chunk of a group to be calculated. @@ -120,4 +120,4 @@ class WorkScheduler { #endif }; -#endif /* _COM_WorkScheduler_h_ */ +#endif /* __COM_WORKSCHEDULER_H__ */ diff --git a/source/blender/compositor/intern/COM_compositor.cpp b/source/blender/compositor/intern/COM_compositor.cpp index 467286084f97..ae9defa786e5 100644 --- a/source/blender/compositor/intern/COM_compositor.cpp +++ b/source/blender/compositor/intern/COM_compositor.cpp @@ -88,13 +88,13 @@ void COM_execute(RenderData *rd, Scene *scene, bNodeTree *editingtree, int rende editingtree->progress(editingtree->prh, 0.0); editingtree->stats_draw(editingtree->sdh, IFACE_("Compositing")); - bool twopass = (editingtree->flag & NTREE_TWO_PASS) > 0 && !rendering; + bool twopass = (editingtree->flag & NTREE_TWO_PASS) && !rendering; /* initialize execution system */ if (twopass) { ExecutionSystem *system = new ExecutionSystem(rd, scene, editingtree, rendering, twopass, viewSettings, displaySettings, viewName); system->execute(); delete system; - + if (editingtree->test_break(editingtree->tbh)) { // during editing multiple calls to this method can be triggered. // make sure one the last one will be doing the work. diff --git a/source/blender/compositor/nodes/COM_AlphaOverNode.cpp b/source/blender/compositor/nodes/COM_AlphaOverNode.cpp index 0c35f079a8bd..3481fd1adddf 100644 --- a/source/blender/compositor/nodes/COM_AlphaOverNode.cpp +++ b/source/blender/compositor/nodes/COM_AlphaOverNode.cpp @@ -35,14 +35,14 @@ void AlphaOverNode::convertToOperations(NodeConverter &converter, const Composit NodeInput *color1Socket = this->getInputSocket(1); NodeInput *color2Socket = this->getInputSocket(2); bNode *editorNode = this->getbNode(); - + MixBaseOperation *convertProg; NodeTwoFloats *ntf = (NodeTwoFloats *)editorNode->storage; if (ntf->x != 0.0f) { AlphaOverMixedOperation *mixOperation = new AlphaOverMixedOperation(); mixOperation->setX(ntf->x); convertProg = mixOperation; - + } else if (editorNode->custom1) { convertProg = new AlphaOverKeyOperation(); @@ -50,7 +50,7 @@ void AlphaOverNode::convertToOperations(NodeConverter &converter, const Composit else { convertProg = new AlphaOverPremultiplyOperation(); } - + convertProg->setUseValueAlphaMultiply(false); if (color1Socket->isLinked()) { convertProg->setResolutionInputSocketIndex(1); @@ -61,7 +61,7 @@ void AlphaOverNode::convertToOperations(NodeConverter &converter, const Composit else { convertProg->setResolutionInputSocketIndex(0); } - + converter.addOperation(convertProg); converter.mapInputSocket(getInputSocket(0), convertProg->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), convertProg->getInputSocket(1)); diff --git a/source/blender/compositor/nodes/COM_AlphaOverNode.h b/source/blender/compositor/nodes/COM_AlphaOverNode.h index b1fe85cf800c..0af2ea3310dd 100644 --- a/source/blender/compositor/nodes/COM_AlphaOverNode.h +++ b/source/blender/compositor/nodes/COM_AlphaOverNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_AlphaOverNode_h_ -#define _COM_AlphaOverNode_h_ +#ifndef __COM_ALPHAOVERNODE_H__ +#define __COM_ALPHAOVERNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BilateralBlurNode.cpp b/source/blender/compositor/nodes/COM_BilateralBlurNode.cpp index fe6b447b23b7..dba1a0094170 100644 --- a/source/blender/compositor/nodes/COM_BilateralBlurNode.cpp +++ b/source/blender/compositor/nodes/COM_BilateralBlurNode.cpp @@ -36,7 +36,7 @@ void BilateralBlurNode::convertToOperations(NodeConverter &converter, const Comp BilateralBlurOperation *operation = new BilateralBlurOperation(); operation->setQuality(context.getQuality()); operation->setData(data); - + converter.addOperation(operation); converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); diff --git a/source/blender/compositor/nodes/COM_BilateralBlurNode.h b/source/blender/compositor/nodes/COM_BilateralBlurNode.h index 6d13cd5b96a4..babb558e0d18 100644 --- a/source/blender/compositor/nodes/COM_BilateralBlurNode.h +++ b/source/blender/compositor/nodes/COM_BilateralBlurNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BilateralBlurNode_h_ -#define _COM_BilateralBlurNode_h_ +#ifndef __COM_BILATERALBLURNODE_H__ +#define __COM_BILATERALBLURNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BlurNode.cpp b/source/blender/compositor/nodes/COM_BlurNode.cpp index 66ccbaa4de82..ed1c15d15a20 100644 --- a/source/blender/compositor/nodes/COM_BlurNode.cpp +++ b/source/blender/compositor/nodes/COM_BlurNode.cpp @@ -56,9 +56,9 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon operationfgb->setData(data); operationfgb->setExtendBounds(extend_bounds); converter.addOperation(operationfgb); - + converter.mapInputSocket(getInputSocket(1), operationfgb->getInputSocket(1)); - + input_operation = operationfgb; output_operation = operationfgb; } @@ -67,12 +67,12 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon SetValueOperation *zero = new SetValueOperation(); zero->setValue(0.0f); clamp->setUseClamp(true); - + converter.addOperation(clamp); converter.addOperation(zero); converter.mapInputSocket(getInputSocket(1), clamp->getInputSocket(0)); converter.addLink(zero->getOutputSocket(), clamp->getInputSocket(1)); - + GaussianAlphaXBlurOperation *operationx = new GaussianAlphaXBlurOperation(); operationx->setData(data); operationx->setQuality(quality); @@ -80,10 +80,10 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon operationx->setFalloff(PROP_SMOOTH); operationx->setSubtract(false); operationx->setExtendBounds(extend_bounds); - + converter.addOperation(operationx); converter.addLink(clamp->getOutputSocket(), operationx->getInputSocket(0)); - + GaussianAlphaYBlurOperation *operationy = new GaussianAlphaYBlurOperation(); operationy->setData(data); operationy->setQuality(quality); @@ -94,7 +94,7 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon converter.addOperation(operationy); converter.addLink(operationx->getOutputSocket(), operationy->getInputSocket(0)); - + GaussianBlurReferenceOperation *operation = new GaussianBlurReferenceOperation(); operation->setData(data); operation->setQuality(quality); @@ -102,7 +102,7 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon converter.addOperation(operation); converter.addLink(operationy->getOutputSocket(), operation->getInputSocket(1)); - + output_operation = operation; input_operation = operation; } @@ -115,7 +115,7 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon converter.addOperation(operationx); converter.mapInputSocket(getInputSocket(1), operationx->getInputSocket(1)); - + GaussianYBlurOperation *operationy = new GaussianYBlurOperation(); operationy->setData(data); operationy->setQuality(quality); @@ -156,18 +156,18 @@ void BlurNode::convertToOperations(NodeConverter &converter, const CompositorCon GammaUncorrectOperation *inverse = new GammaUncorrectOperation(); converter.addOperation(correct); converter.addOperation(inverse); - + converter.mapInputSocket(getInputSocket(0), correct->getInputSocket(0)); converter.addLink(correct->getOutputSocket(), input_operation->getInputSocket(0)); converter.addLink(output_operation->getOutputSocket(), inverse->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(), inverse->getOutputSocket()); - + converter.addPreview(inverse->getOutputSocket()); } else { converter.mapInputSocket(getInputSocket(0), input_operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(), output_operation->getOutputSocket()); - + converter.addPreview(output_operation->getOutputSocket()); } } diff --git a/source/blender/compositor/nodes/COM_BlurNode.h b/source/blender/compositor/nodes/COM_BlurNode.h index fecba9c0eef6..9a5f5ea1efdd 100644 --- a/source/blender/compositor/nodes/COM_BlurNode.h +++ b/source/blender/compositor/nodes/COM_BlurNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BlurNode_h_ -#define _COM_BlurNode_h_ +#ifndef __COM_BLURNODE_H__ +#define __COM_BLURNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BokehBlurNode.cpp b/source/blender/compositor/nodes/COM_BokehBlurNode.cpp index b71f2f5fa077..b36e8cc4c530 100644 --- a/source/blender/compositor/nodes/COM_BokehBlurNode.cpp +++ b/source/blender/compositor/nodes/COM_BokehBlurNode.cpp @@ -49,7 +49,7 @@ void BokehBlurNode::convertToOperations(NodeConverter &converter, const Composit operation->setThreshold(0.0f); operation->setMaxBlur(b_node->custom4); operation->setDoScaleSize(true); - + converter.addOperation(operation); converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); @@ -60,7 +60,7 @@ void BokehBlurNode::convertToOperations(NodeConverter &converter, const Composit BokehBlurOperation *operation = new BokehBlurOperation(); operation->setQuality(context.getQuality()); operation->setExtendBounds(extend_bounds); - + converter.addOperation(operation); converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); diff --git a/source/blender/compositor/nodes/COM_BokehBlurNode.h b/source/blender/compositor/nodes/COM_BokehBlurNode.h index 2c8d52ad2777..48cd661a7bf7 100644 --- a/source/blender/compositor/nodes/COM_BokehBlurNode.h +++ b/source/blender/compositor/nodes/COM_BokehBlurNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BokehBlurNode_h_ -#define _COM_BokehBlurNode_h_ +#ifndef __COM_BOKEHBLURNODE_H__ +#define __COM_BOKEHBLURNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BokehImageNode.cpp b/source/blender/compositor/nodes/COM_BokehImageNode.cpp index 7f25a19ee375..7a388f80def4 100644 --- a/source/blender/compositor/nodes/COM_BokehImageNode.cpp +++ b/source/blender/compositor/nodes/COM_BokehImageNode.cpp @@ -33,9 +33,9 @@ void BokehImageNode::convertToOperations(NodeConverter &converter, const Composi { BokehImageOperation *operation = new BokehImageOperation(); operation->setData((NodeBokehImage *)this->getbNode()->storage); - + converter.addOperation(operation); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); - + converter.addPreview(operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_BokehImageNode.h b/source/blender/compositor/nodes/COM_BokehImageNode.h index 36ee13006614..70f363b8cf6d 100644 --- a/source/blender/compositor/nodes/COM_BokehImageNode.h +++ b/source/blender/compositor/nodes/COM_BokehImageNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BokehImageNode_h_ -#define _COM_BokehImageNode_h_ +#ifndef __COM_BOKEHIMAGENODE_H__ +#define __COM_BOKEHIMAGENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BoxMaskNode.cpp b/source/blender/compositor/nodes/COM_BoxMaskNode.cpp index b3cffb90459c..f798c95b1b10 100644 --- a/source/blender/compositor/nodes/COM_BoxMaskNode.cpp +++ b/source/blender/compositor/nodes/COM_BoxMaskNode.cpp @@ -36,13 +36,13 @@ void BoxMaskNode::convertToOperations(NodeConverter &converter, const Compositor { NodeInput *inputSocket = this->getInputSocket(0); NodeOutput *outputSocket = this->getOutputSocket(0); - + BoxMaskOperation *operation; operation = new BoxMaskOperation(); operation->setData((NodeBoxMask *)this->getbNode()->storage); operation->setMaskType(this->getbNode()->custom1); converter.addOperation(operation); - + if (inputSocket->isLinked()) { converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_BoxMaskNode.h b/source/blender/compositor/nodes/COM_BoxMaskNode.h index 8229aa58ac1d..01557229be92 100644 --- a/source/blender/compositor/nodes/COM_BoxMaskNode.h +++ b/source/blender/compositor/nodes/COM_BoxMaskNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BoxMaskNode_h_ -#define _COM_BoxMaskNode_h_ +#ifndef __COM_BOXMASKNODE_H__ +#define __COM_BOXMASKNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_BrightnessNode.cpp b/source/blender/compositor/nodes/COM_BrightnessNode.cpp index fc7294eb6b1e..b2422a230cd7 100644 --- a/source/blender/compositor/nodes/COM_BrightnessNode.cpp +++ b/source/blender/compositor/nodes/COM_BrightnessNode.cpp @@ -35,7 +35,7 @@ void BrightnessNode::convertToOperations(NodeConverter &converter, const Composi BrightnessOperation *operation = new BrightnessOperation(); operation->setUsePremultiply((bnode->custom1 & 1) != 0); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_BrightnessNode.h b/source/blender/compositor/nodes/COM_BrightnessNode.h index bacd35105174..27155e277740 100644 --- a/source/blender/compositor/nodes/COM_BrightnessNode.h +++ b/source/blender/compositor/nodes/COM_BrightnessNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BrightnessNode_h_ -#define _COM_BrightnessNode_h_ +#ifndef __COM_BRIGHTNESSNODE_H__ +#define __COM_BRIGHTNESSNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ChannelMatteNode.h b/source/blender/compositor/nodes/COM_ChannelMatteNode.h index f528578e6dd0..c5f062cb2158 100644 --- a/source/blender/compositor/nodes/COM_ChannelMatteNode.h +++ b/source/blender/compositor/nodes/COM_ChannelMatteNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ChannelMatteNode_h_ -#define _COM_ChannelMatteNode_h_ +#ifndef __COM_CHANNELMATTENODE_H__ +#define __COM_CHANNELMATTENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ChromaMatteNode.cpp b/source/blender/compositor/nodes/COM_ChromaMatteNode.cpp index 2c985cd5bd10..d725ad135a55 100644 --- a/source/blender/compositor/nodes/COM_ChromaMatteNode.cpp +++ b/source/blender/compositor/nodes/COM_ChromaMatteNode.cpp @@ -33,35 +33,35 @@ ChromaMatteNode::ChromaMatteNode(bNode *editorNode) : Node(editorNode) void ChromaMatteNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bNode *editorsnode = getbNode(); - + NodeInput *inputSocketImage = this->getInputSocket(0); NodeInput *inputSocketKey = this->getInputSocket(1); NodeOutput *outputSocketImage = this->getOutputSocket(0); NodeOutput *outputSocketMatte = this->getOutputSocket(1); - + ConvertRGBToYCCOperation *operationRGBToYCC_Image = new ConvertRGBToYCCOperation(); ConvertRGBToYCCOperation *operationRGBToYCC_Key = new ConvertRGBToYCCOperation(); operationRGBToYCC_Image->setMode(BLI_YCC_ITU_BT709); operationRGBToYCC_Key->setMode(BLI_YCC_ITU_BT709); converter.addOperation(operationRGBToYCC_Image); converter.addOperation(operationRGBToYCC_Key); - + ChromaMatteOperation *operation = new ChromaMatteOperation(); operation->setSettings((NodeChroma *)editorsnode->storage); converter.addOperation(operation); - + SetAlphaOperation *operationAlpha = new SetAlphaOperation(); converter.addOperation(operationAlpha); - + converter.mapInputSocket(inputSocketImage, operationRGBToYCC_Image->getInputSocket(0)); converter.mapInputSocket(inputSocketKey, operationRGBToYCC_Key->getInputSocket(0)); converter.addLink(operationRGBToYCC_Image->getOutputSocket(), operation->getInputSocket(0)); converter.addLink(operationRGBToYCC_Key->getOutputSocket(), operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketMatte, operation->getOutputSocket()); - + converter.mapInputSocket(inputSocketImage, operationAlpha->getInputSocket(0)); converter.addLink(operation->getOutputSocket(), operationAlpha->getInputSocket(1)); converter.mapOutputSocket(outputSocketImage, operationAlpha->getOutputSocket()); - + converter.addPreview(operationAlpha->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ChromaMatteNode.h b/source/blender/compositor/nodes/COM_ChromaMatteNode.h index d1eb3a907ef8..7d0b34ecf5dc 100644 --- a/source/blender/compositor/nodes/COM_ChromaMatteNode.h +++ b/source/blender/compositor/nodes/COM_ChromaMatteNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ChromaMatteNode_h_ -#define _COM_ChromaMatteNode_h_ +#ifndef __COM_CHROMAMATTENODE_H__ +#define __COM_CHROMAMATTENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorBalanceNode.cpp b/source/blender/compositor/nodes/COM_ColorBalanceNode.cpp index 98d2e0488075..28966beb4f46 100644 --- a/source/blender/compositor/nodes/COM_ColorBalanceNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorBalanceNode.cpp @@ -36,11 +36,11 @@ void ColorBalanceNode::convertToOperations(NodeConverter &converter, const Compo { bNode *node = this->getbNode(); NodeColorBalance *n = (NodeColorBalance *)node->storage; - + NodeInput *inputSocket = this->getInputSocket(0); NodeInput *inputImageSocket = this->getInputSocket(1); NodeOutput *outputSocket = this->getOutputSocket(0); - + NodeOperation *operation; if (node->custom1 == 0) { ColorBalanceLGGOperation *operationLGG = new ColorBalanceLGGOperation(); @@ -69,7 +69,7 @@ void ColorBalanceNode::convertToOperations(NodeConverter &converter, const Compo operation = operationCDL; } converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapInputSocket(inputImageSocket, operation->getInputSocket(1)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_ColorBalanceNode.h b/source/blender/compositor/nodes/COM_ColorBalanceNode.h index 1244dbbb7c54..d203fef20f44 100644 --- a/source/blender/compositor/nodes/COM_ColorBalanceNode.h +++ b/source/blender/compositor/nodes/COM_ColorBalanceNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorBalanceNode_h_ -#define _COM_ColorBalanceNode_h_ +#ifndef __COM_COLORBALANCENODE_H__ +#define __COM_COLORBALANCENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorCorrectionNode.cpp b/source/blender/compositor/nodes/COM_ColorCorrectionNode.cpp index c4eefe038a52..72943f6b53f6 100644 --- a/source/blender/compositor/nodes/COM_ColorCorrectionNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorCorrectionNode.cpp @@ -32,14 +32,14 @@ ColorCorrectionNode::ColorCorrectionNode(bNode *editorNode) : Node(editorNode) void ColorCorrectionNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bNode *editorNode = getbNode(); - + ColorCorrectionOperation *operation = new ColorCorrectionOperation(); operation->setData((NodeColorCorrection *)editorNode->storage); operation->setRedChannelEnabled((editorNode->custom1 & 1) > 0); operation->setGreenChannelEnabled((editorNode->custom1 & 2) > 0); operation->setBlueChannelEnabled((editorNode->custom1 & 4) > 0); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_ColorCorrectionNode.h b/source/blender/compositor/nodes/COM_ColorCorrectionNode.h index d943136ceb89..fcbd7631cb48 100644 --- a/source/blender/compositor/nodes/COM_ColorCorrectionNode.h +++ b/source/blender/compositor/nodes/COM_ColorCorrectionNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorCorrectionNode_h_ -#define _COM_ColorCorrectionNode_h_ +#ifndef __COM_COLORCORRECTIONNODE_H__ +#define __COM_COLORCORRECTIONNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorCurveNode.cpp b/source/blender/compositor/nodes/COM_ColorCurveNode.cpp index 41052ef536da..fb8587adabbb 100644 --- a/source/blender/compositor/nodes/COM_ColorCurveNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorCurveNode.cpp @@ -35,12 +35,12 @@ void ColorCurveNode::convertToOperations(NodeConverter &converter, const Composi ColorCurveOperation *operation = new ColorCurveOperation(); operation->setCurveMapping((CurveMapping *)this->getbNode()->storage); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(2)); converter.mapInputSocket(getInputSocket(3), operation->getInputSocket(3)); - + converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); } else { @@ -52,7 +52,7 @@ void ColorCurveNode::convertToOperations(NodeConverter &converter, const Composi operation->setWhiteLevel(col); operation->setCurveMapping((CurveMapping *)this->getbNode()->storage); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_ColorCurveNode.h b/source/blender/compositor/nodes/COM_ColorCurveNode.h index 0f99625e31a7..ad51611d1cf0 100644 --- a/source/blender/compositor/nodes/COM_ColorCurveNode.h +++ b/source/blender/compositor/nodes/COM_ColorCurveNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorCurveNode_h_ -#define _COM_ColorCurveNode_h_ +#ifndef __COM_COLORCURVENODE_H__ +#define __COM_COLORCURVENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorMatteNode.cpp b/source/blender/compositor/nodes/COM_ColorMatteNode.cpp index f7c20894087d..477fdddff8a8 100644 --- a/source/blender/compositor/nodes/COM_ColorMatteNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorMatteNode.cpp @@ -33,33 +33,33 @@ ColorMatteNode::ColorMatteNode(bNode *editorNode) : Node(editorNode) void ColorMatteNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bNode *editorsnode = getbNode(); - + NodeInput *inputSocketImage = this->getInputSocket(0); NodeInput *inputSocketKey = this->getInputSocket(1); NodeOutput *outputSocketImage = this->getOutputSocket(0); NodeOutput *outputSocketMatte = this->getOutputSocket(1); - + ConvertRGBToHSVOperation *operationRGBToHSV_Image = new ConvertRGBToHSVOperation(); ConvertRGBToHSVOperation *operationRGBToHSV_Key = new ConvertRGBToHSVOperation(); converter.addOperation(operationRGBToHSV_Image); converter.addOperation(operationRGBToHSV_Key); - + ColorMatteOperation *operation = new ColorMatteOperation(); operation->setSettings((NodeChroma *)editorsnode->storage); converter.addOperation(operation); - + SetAlphaOperation *operationAlpha = new SetAlphaOperation(); converter.addOperation(operationAlpha); - + converter.mapInputSocket(inputSocketImage, operationRGBToHSV_Image->getInputSocket(0)); converter.mapInputSocket(inputSocketKey, operationRGBToHSV_Key->getInputSocket(0)); converter.addLink(operationRGBToHSV_Image->getOutputSocket(), operation->getInputSocket(0)); converter.addLink(operationRGBToHSV_Key->getOutputSocket(), operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketMatte, operation->getOutputSocket(0)); - + converter.mapInputSocket(inputSocketImage, operationAlpha->getInputSocket(0)); converter.addLink(operation->getOutputSocket(), operationAlpha->getInputSocket(1)); converter.mapOutputSocket(outputSocketImage, operationAlpha->getOutputSocket()); - + converter.addPreview(operationAlpha->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ColorMatteNode.h b/source/blender/compositor/nodes/COM_ColorMatteNode.h index c17d3eb6c4e5..f2c3c08beead 100644 --- a/source/blender/compositor/nodes/COM_ColorMatteNode.h +++ b/source/blender/compositor/nodes/COM_ColorMatteNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ColorMatteNode_h_ -#define _COM_ColorMatteNode_h_ +#ifndef __COM_COLORMATTENODE_H__ +#define __COM_COLORMATTENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorNode.cpp b/source/blender/compositor/nodes/COM_ColorNode.cpp index 2c37a927e462..c9254b30e8e4 100644 --- a/source/blender/compositor/nodes/COM_ColorNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorNode.cpp @@ -37,6 +37,6 @@ void ColorNode::convertToOperations(NodeConverter &converter, const CompositorCo output->getEditorValueColor(col); operation->setChannels(col); converter.addOperation(operation); - + converter.mapOutputSocket(output, operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ColorNode.h b/source/blender/compositor/nodes/COM_ColorNode.h index d03c910bfd26..205f4d071353 100644 --- a/source/blender/compositor/nodes/COM_ColorNode.h +++ b/source/blender/compositor/nodes/COM_ColorNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorNode_h_ -#define _COM_ColorNode_h_ +#ifndef __COM_COLORNODE_H__ +#define __COM_COLORNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorRampNode.cpp b/source/blender/compositor/nodes/COM_ColorRampNode.cpp index 175267a3a4fd..3e5128fa0fad 100644 --- a/source/blender/compositor/nodes/COM_ColorRampNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorRampNode.cpp @@ -42,14 +42,14 @@ void ColorRampNode::convertToOperations(NodeConverter &converter, const Composit ColorRampOperation *operation = new ColorRampOperation(); operation->setColorBand((ColorBand *)editorNode->storage); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); - + SeparateChannelOperation *operation2 = new SeparateChannelOperation(); operation2->setChannel(3); converter.addOperation(operation2); - + converter.addLink(operation->getOutputSocket(), operation2->getInputSocket(0)); converter.mapOutputSocket(outputSocketAlpha, operation2->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ColorRampNode.h b/source/blender/compositor/nodes/COM_ColorRampNode.h index c5e6b2f6154c..4332d831e31a 100644 --- a/source/blender/compositor/nodes/COM_ColorRampNode.h +++ b/source/blender/compositor/nodes/COM_ColorRampNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorRampNode_h_ -#define _COM_ColorRampNode_h_ +#ifndef __COM_COLORRAMPNODE_H__ +#define __COM_COLORRAMPNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorSpillNode.cpp b/source/blender/compositor/nodes/COM_ColorSpillNode.cpp index f33f28583974..bef518bb186b 100644 --- a/source/blender/compositor/nodes/COM_ColorSpillNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorSpillNode.cpp @@ -32,18 +32,18 @@ ColorSpillNode::ColorSpillNode(bNode *editorNode) : Node(editorNode) void ColorSpillNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bNode *editorsnode = getbNode(); - + NodeInput *inputSocketImage = this->getInputSocket(0); NodeInput *inputSocketFac = this->getInputSocket(1); NodeOutput *outputSocketImage = this->getOutputSocket(0); - + ColorSpillOperation *operation; operation = new ColorSpillOperation(); operation->setSettings((NodeColorspill *)editorsnode->storage); operation->setSpillChannel(editorsnode->custom1 - 1); // Channel for spilling operation->setSpillMethod(editorsnode->custom2); // Channel method converter.addOperation(operation); - + converter.mapInputSocket(inputSocketImage, operation->getInputSocket(0)); converter.mapInputSocket(inputSocketFac, operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketImage, operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_ColorSpillNode.h b/source/blender/compositor/nodes/COM_ColorSpillNode.h index 7442d2b02616..cb2cd8a2ea31 100644 --- a/source/blender/compositor/nodes/COM_ColorSpillNode.h +++ b/source/blender/compositor/nodes/COM_ColorSpillNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorSpillNode_h_ -#define _COM_ColorSpillNode_h_ +#ifndef __COM_COLORSPILLNODE_H__ +#define __COM_COLORSPILLNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ColorToBWNode.cpp b/source/blender/compositor/nodes/COM_ColorToBWNode.cpp index 2ce4dd5d3a80..1b26354117af 100644 --- a/source/blender/compositor/nodes/COM_ColorToBWNode.cpp +++ b/source/blender/compositor/nodes/COM_ColorToBWNode.cpp @@ -34,10 +34,10 @@ void ColorToBWNode::convertToOperations(NodeConverter &converter, const Composit { NodeInput *colorSocket = this->getInputSocket(0); NodeOutput *valueSocket = this->getOutputSocket(0); - + ConvertColorToBWOperation *convertProg = new ConvertColorToBWOperation(); converter.addOperation(convertProg); - + converter.mapInputSocket(colorSocket, convertProg->getInputSocket(0)); converter.mapOutputSocket(valueSocket, convertProg->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_ColorToBWNode.h b/source/blender/compositor/nodes/COM_ColorToBWNode.h index 350ab88513d6..05f937eb555c 100644 --- a/source/blender/compositor/nodes/COM_ColorToBWNode.h +++ b/source/blender/compositor/nodes/COM_ColorToBWNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorToBWNode_h_ -#define _COM_ColorToBWNode_h_ +#ifndef __COM_COLORTOBWNODE_H__ +#define __COM_COLORTOBWNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_CombineColorNode.cpp b/source/blender/compositor/nodes/COM_CombineColorNode.cpp index b7b84b9986c9..ad410038c659 100644 --- a/source/blender/compositor/nodes/COM_CombineColorNode.cpp +++ b/source/blender/compositor/nodes/COM_CombineColorNode.cpp @@ -38,7 +38,7 @@ void CombineColorNode::convertToOperations(NodeConverter &converter, const Compo NodeInput *inputBSocket = this->getInputSocket(2); NodeInput *inputASocket = this->getInputSocket(3); NodeOutput *outputSocket = this->getOutputSocket(0); - + CombineChannelsOperation *operation = new CombineChannelsOperation(); if (inputRSocket->isLinked()) { operation->setResolutionInputSocketIndex(0); @@ -53,16 +53,16 @@ void CombineColorNode::convertToOperations(NodeConverter &converter, const Compo operation->setResolutionInputSocketIndex(3); } converter.addOperation(operation); - + converter.mapInputSocket(inputRSocket, operation->getInputSocket(0)); converter.mapInputSocket(inputGSocket, operation->getInputSocket(1)); converter.mapInputSocket(inputBSocket, operation->getInputSocket(2)); converter.mapInputSocket(inputASocket, operation->getInputSocket(3)); - + NodeOperation *color_conv = getColorConverter(context); if (color_conv) { converter.addOperation(color_conv); - + converter.addLink(operation->getOutputSocket(), color_conv->getInputSocket(0)); converter.mapOutputSocket(outputSocket, color_conv->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_CombineColorNode.h b/source/blender/compositor/nodes/COM_CombineColorNode.h index 4cb626ea3845..030224e16f96 100644 --- a/source/blender/compositor/nodes/COM_CombineColorNode.h +++ b/source/blender/compositor/nodes/COM_CombineColorNode.h @@ -21,8 +21,8 @@ * Lukas Toenne */ -#ifndef _COM_CombineColorNode_h_ -#define _COM_CombineColorNode_h_ +#ifndef __COM_COMBINECOLORNODE_H__ +#define __COM_COMBINECOLORNODE_H__ #include "COM_Node.h" @@ -30,7 +30,7 @@ class CombineColorNode : public Node { public: CombineColorNode(bNode *editorNode); void convertToOperations(NodeConverter &converter, const CompositorContext &context) const; - + protected: virtual NodeOperation *getColorConverter(const CompositorContext &context) const = 0; }; @@ -40,7 +40,7 @@ class CombineRGBANode : public CombineColorNode { CombineRGBANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -49,7 +49,7 @@ class CombineHSVANode : public CombineColorNode { CombineHSVANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -58,7 +58,7 @@ class CombineYCCANode : public CombineColorNode { CombineYCCANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -67,7 +67,7 @@ class CombineYUVANode : public CombineColorNode { CombineYUVANode(bNode *editorNode) : CombineColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; diff --git a/source/blender/compositor/nodes/COM_CompositorNode.cpp b/source/blender/compositor/nodes/COM_CompositorNode.cpp index b2a1df7ee9e4..002f28f31351 100644 --- a/source/blender/compositor/nodes/COM_CompositorNode.cpp +++ b/source/blender/compositor/nodes/COM_CompositorNode.cpp @@ -49,7 +49,7 @@ void CompositorNode::convertToOperations(NodeConverter &converter, const Composi /* alpha socket gives either 1 or a custom alpha value if "use alpha" is enabled */ compositorOperation->setUseAlphaInput(ignore_alpha || alphaSocket->isLinked()); compositorOperation->setActive(is_active); - + converter.addOperation(compositorOperation); converter.mapInputSocket(imageSocket, compositorOperation->getInputSocket(0)); /* only use alpha link if "use alpha" is enabled */ @@ -58,6 +58,6 @@ void CompositorNode::convertToOperations(NodeConverter &converter, const Composi else converter.mapInputSocket(alphaSocket, compositorOperation->getInputSocket(1)); converter.mapInputSocket(depthSocket, compositorOperation->getInputSocket(2)); - + converter.addNodeInputPreview(imageSocket); } diff --git a/source/blender/compositor/nodes/COM_CompositorNode.h b/source/blender/compositor/nodes/COM_CompositorNode.h index 4e96eb637760..a21013f2ce2c 100644 --- a/source/blender/compositor/nodes/COM_CompositorNode.h +++ b/source/blender/compositor/nodes/COM_CompositorNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CompositorNode_h_ -#define _COM_CompositorNode_h_ +#ifndef __COM_COMPOSITORNODE_H__ +#define __COM_COMPOSITORNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp b/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp index fbf5dbb62530..75f72669e1e1 100644 --- a/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp +++ b/source/blender/compositor/nodes/COM_ConvertAlphaNode.cpp @@ -35,9 +35,9 @@ void ConvertAlphaNode::convertToOperations(NodeConverter &converter, const Compo else { operation = new ConvertStraightToPremulOperation(); } - + converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ConvertAlphaNode.h b/source/blender/compositor/nodes/COM_ConvertAlphaNode.h index 5bc5169b6d9e..37482d66269f 100644 --- a/source/blender/compositor/nodes/COM_ConvertAlphaNode.h +++ b/source/blender/compositor/nodes/COM_ConvertAlphaNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ConvertAlphaNode_h_ -#define _COM_ConvertAlphaNode_h_ +#ifndef __COM_CONVERTALPHANODE_H__ +#define __COM_CONVERTALPHANODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_CornerPinNode.cpp b/source/blender/compositor/nodes/COM_CornerPinNode.cpp index 5e4e463595a2..b03a3e64f832 100644 --- a/source/blender/compositor/nodes/COM_CornerPinNode.cpp +++ b/source/blender/compositor/nodes/COM_CornerPinNode.cpp @@ -46,7 +46,7 @@ void CornerPinNode::convertToOperations(NodeConverter &converter, const Composit converter.addOperation(warp_image_operation); PlaneCornerPinMaskOperation *plane_mask_operation = new PlaneCornerPinMaskOperation(); converter.addOperation(plane_mask_operation); - + converter.mapInputSocket(input_image, warp_image_operation->getInputSocket(0)); for (int i = 0; i < 4; ++i) { NodeInput *corner_input = getInputSocket(node_corner_index[i]); diff --git a/source/blender/compositor/nodes/COM_CornerPinNode.h b/source/blender/compositor/nodes/COM_CornerPinNode.h index 70e48e41d6be..63428fa653b2 100644 --- a/source/blender/compositor/nodes/COM_CornerPinNode.h +++ b/source/blender/compositor/nodes/COM_CornerPinNode.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_CornerPinNode_h -#define _COM_CornerPinNode_h +#ifndef __COM_CORNERPINNODE_H__ +#define __COM_CORNERPINNODE_H__ #include "COM_Node.h" @@ -38,4 +38,4 @@ class CornerPinNode : public Node { void convertToOperations(NodeConverter &converter, const CompositorContext &context) const; }; -#endif /* _COM_CornerPinNode_h */ +#endif /* __COM_CORNERPINNODE_H__ */ diff --git a/source/blender/compositor/nodes/COM_CropNode.cpp b/source/blender/compositor/nodes/COM_CropNode.cpp index 12eb5268be47..4f80b868f3a4 100644 --- a/source/blender/compositor/nodes/COM_CropNode.cpp +++ b/source/blender/compositor/nodes/COM_CropNode.cpp @@ -45,7 +45,7 @@ void CropNode::convertToOperations(NodeConverter &converter, const CompositorCon operation->setCropSettings(cropSettings); operation->setRelative(relative); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(), operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_CropNode.h b/source/blender/compositor/nodes/COM_CropNode.h index cdec70a4a5ce..a7d529c426fb 100644 --- a/source/blender/compositor/nodes/COM_CropNode.h +++ b/source/blender/compositor/nodes/COM_CropNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CropNode_h_ -#define _COM_CropNode_h_ +#ifndef __COM_CROPNODE_H__ +#define __COM_CROPNODE_H__ #include "COM_Node.h" @@ -36,5 +36,3 @@ class CropNode : public Node { }; #endif - - diff --git a/source/blender/compositor/nodes/COM_CryptomatteNode.cpp b/source/blender/compositor/nodes/COM_CryptomatteNode.cpp new file mode 100644 index 000000000000..648ea4556ade --- /dev/null +++ b/source/blender/compositor/nodes/COM_CryptomatteNode.cpp @@ -0,0 +1,121 @@ +/* + * Copyright 2018, Blender Foundation. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contributor: + * Lukas Stockner + * Stefan Werner + */ + +#include "COM_CryptomatteNode.h" +#include "COM_CryptomatteOperation.h" +#include "COM_SetAlphaOperation.h" +#include "COM_ConvertOperation.h" +#include "BLI_string.h" +#include "BLI_hash_mm3.h" +#include "BLI_assert.h" +#include + +CryptomatteNode::CryptomatteNode(bNode *editorNode) : Node(editorNode) +{ + /* pass */ +} + +/* This is taken from the Cryptomatte specification 1.0. */ +static inline float hash_to_float(uint32_t hash) +{ + uint32_t mantissa = hash & (( 1 << 23) - 1); + uint32_t exponent = (hash >> 23) & ((1 << 8) - 1); + exponent = max(exponent, (uint32_t) 1); + exponent = min(exponent, (uint32_t) 254); + exponent = exponent << 23; + uint32_t sign = (hash >> 31); + sign = sign << 31; + uint32_t float_bits = sign | exponent | mantissa; + float f; + /* Bit casting relies on equal size for both types. */ + BLI_STATIC_ASSERT(sizeof(float) == sizeof(uint32_t), "float and uint32_t are not the same size") + ::memcpy(&f, &float_bits, sizeof(float)); + return f; +} + +void CryptomatteNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const +{ + NodeInput *inputSocketImage = this->getInputSocket(0); + NodeOutput *outputSocketImage = this->getOutputSocket(0); + NodeOutput *outputSocketMatte = this->getOutputSocket(1); + NodeOutput *outputSocketPick = this->getOutputSocket(2); + + bNode *node = this->getbNode(); + NodeCryptomatte *cryptoMatteSettings = (NodeCryptomatte *)node->storage; + + CryptomatteOperation *operation = new CryptomatteOperation(getNumberOfInputSockets() - 1); + if (cryptoMatteSettings) { + if (cryptoMatteSettings->matte_id) { + /* Split the string by commas, ignoring white space. */ + std::string input = cryptoMatteSettings->matte_id; + std::istringstream ss(input); + while (ss.good()) { + std::string token; + getline(ss, token, ','); + /* Ignore empty tokens. */ + if (token.length() > 0) { + size_t first = token.find_first_not_of(' '); + size_t last = token.find_last_not_of(' '); + if (first == std::string::npos || last == std::string::npos) { + break; + } + token = token.substr(first, (last - first + 1)); + if (*token.begin() == '<' && *(--token.end()) == '>') { + operation->addObjectIndex(atof(token.substr(1, token.length() - 2).c_str())); + } + else { + uint32_t hash = BLI_hash_mm3((const unsigned char *)token.c_str(), token.length(), 0); + operation->addObjectIndex(hash_to_float(hash)); + } + } + } + } + } + + converter.addOperation(operation); + + for (int i = 0; i < getNumberOfInputSockets() - 1; ++i) { + converter.mapInputSocket(this->getInputSocket(i + 1), operation->getInputSocket(i)); + } + + SeparateChannelOperation *separateOperation = new SeparateChannelOperation; + separateOperation->setChannel(3); + converter.addOperation(separateOperation); + + SetAlphaOperation *operationAlpha = new SetAlphaOperation(); + converter.addOperation(operationAlpha); + + converter.addLink(operation->getOutputSocket(0), separateOperation->getInputSocket(0)); + converter.addLink(separateOperation->getOutputSocket(0), operationAlpha->getInputSocket(1)); + + SetAlphaOperation *clearAlphaOperation = new SetAlphaOperation(); + converter.addOperation(clearAlphaOperation); + converter.addInputValue(clearAlphaOperation->getInputSocket(1), 1.0f); + + converter.addLink(operation->getOutputSocket(0), clearAlphaOperation->getInputSocket(0)); + + converter.mapInputSocket(inputSocketImage, operationAlpha->getInputSocket(0)); + converter.mapOutputSocket(outputSocketMatte, separateOperation->getOutputSocket(0)); + converter.mapOutputSocket(outputSocketImage, operationAlpha->getOutputSocket(0)); + converter.mapOutputSocket(outputSocketPick, clearAlphaOperation->getOutputSocket(0)); + +} diff --git a/source/blender/compositor/nodes/COM_CryptomatteNode.h b/source/blender/compositor/nodes/COM_CryptomatteNode.h new file mode 100644 index 000000000000..2e1784dedb9f --- /dev/null +++ b/source/blender/compositor/nodes/COM_CryptomatteNode.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018, Blender Foundation. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contributor: + * Lukas Stockner + */ + +#ifndef __COM_CRYPTOMATTENODE_H__ +#define __COM_CRYPTOMATTENODE_H__ + +#include "COM_Node.h" + +/** + * @brief CryptomatteNode + * @ingroup Node + */ +class CryptomatteNode : public Node { +public: + CryptomatteNode(bNode *editorNode); + void convertToOperations(NodeConverter &converter, const CompositorContext &context) const; +}; + +#endif diff --git a/source/blender/compositor/nodes/COM_DefocusNode.cpp b/source/blender/compositor/nodes/COM_DefocusNode.cpp index 5df246db1d27..19bb42327f57 100644 --- a/source/blender/compositor/nodes/COM_DefocusNode.cpp +++ b/source/blender/compositor/nodes/COM_DefocusNode.cpp @@ -54,17 +54,17 @@ void DefocusNode::convertToOperations(NodeConverter &converter, const Compositor SetValueOperation *maxRadius = new SetValueOperation(); maxRadius->setValue(data->maxblur); MathMinimumOperation *minimize = new MathMinimumOperation(); - + converter.addOperation(multiply); converter.addOperation(multiplier); converter.addOperation(maxRadius); converter.addOperation(minimize); - + converter.mapInputSocket(getInputSocket(1), multiply->getInputSocket(0)); converter.addLink(multiplier->getOutputSocket(), multiply->getInputSocket(1)); converter.addLink(multiply->getOutputSocket(), minimize->getInputSocket(0)); converter.addLink(maxRadius->getOutputSocket(), minimize->getInputSocket(1)); - + radiusOperation = minimize; } else { @@ -73,20 +73,20 @@ void DefocusNode::convertToOperations(NodeConverter &converter, const Compositor radius_op->setfStop(data->fstop); radius_op->setMaxRadius(data->maxblur); converter.addOperation(radius_op); - + converter.mapInputSocket(getInputSocket(1), radius_op->getInputSocket(0)); - + FastGaussianBlurValueOperation *blur = new FastGaussianBlurValueOperation(); /* maintain close pixels so far Z values don't bleed into the foreground */ blur->setOverlay(FAST_GAUSS_OVERLAY_MIN); converter.addOperation(blur); - + converter.addLink(radius_op->getOutputSocket(0), blur->getInputSocket(0)); radius_op->setPostBlur(blur); - + radiusOperation = blur; } - + NodeBokehImage *bokehdata = new NodeBokehImage(); bokehdata->angle = data->rotation; bokehdata->rounding = 0.0f; @@ -97,20 +97,20 @@ void DefocusNode::convertToOperations(NodeConverter &converter, const Compositor } bokehdata->catadioptric = 0.0f; bokehdata->lensshift = 0.0f; - + BokehImageOperation *bokeh = new BokehImageOperation(); bokeh->setData(bokehdata); bokeh->deleteDataOnFinish(); converter.addOperation(bokeh); - + #ifdef COM_DEFOCUS_SEARCH InverseSearchRadiusOperation *search = new InverseSearchRadiusOperation(); search->setMaxBlur(data->maxblur); converter.addOperation(search); - + converter.addLink(radiusOperation->getOutputSocket(0), search->getInputSocket(0)); #endif - + VariableSizeBokehBlurOperation *operation = new VariableSizeBokehBlurOperation(); if (data->preview) operation->setQuality(COM_QUALITY_LOW); @@ -119,19 +119,19 @@ void DefocusNode::convertToOperations(NodeConverter &converter, const Compositor operation->setMaxBlur(data->maxblur); operation->setThreshold(data->bthresh); converter.addOperation(operation); - + converter.addLink(bokeh->getOutputSocket(), operation->getInputSocket(1)); converter.addLink(radiusOperation->getOutputSocket(), operation->getInputSocket(2)); #ifdef COM_DEFOCUS_SEARCH converter.addLink(search->getOutputSocket(), operation->getInputSocket(3)); #endif - + if (data->gamco) { GammaCorrectOperation *correct = new GammaCorrectOperation(); converter.addOperation(correct); GammaUncorrectOperation *inverse = new GammaUncorrectOperation(); converter.addOperation(inverse); - + converter.mapInputSocket(getInputSocket(0), correct->getInputSocket(0)); converter.addLink(correct->getOutputSocket(), operation->getInputSocket(0)); converter.addLink(operation->getOutputSocket(), inverse->getInputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_DefocusNode.h b/source/blender/compositor/nodes/COM_DefocusNode.h index 917499ee93ab..99efdd15b370 100644 --- a/source/blender/compositor/nodes/COM_DefocusNode.h +++ b/source/blender/compositor/nodes/COM_DefocusNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DefocusNode_h_ -#define _COM_DefocusNode_h_ +#ifndef __COM_DEFOCUSNODE_H__ +#define __COM_DEFOCUSNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DespeckleNode.cpp b/source/blender/compositor/nodes/COM_DespeckleNode.cpp index a21885bf42df..d211050389e1 100644 --- a/source/blender/compositor/nodes/COM_DespeckleNode.cpp +++ b/source/blender/compositor/nodes/COM_DespeckleNode.cpp @@ -35,15 +35,15 @@ void DespeckleNode::convertToOperations(NodeConverter &converter, const Composit NodeInput *inputSocket = this->getInputSocket(0); NodeInput *inputImageSocket = this->getInputSocket(1); NodeOutput *outputSocket = this->getOutputSocket(0); - + DespeckleOperation *operation = new DespeckleOperation(); operation->setThreshold(editorNode->custom3); operation->setThresholdNeighbor(editorNode->custom4); converter.addOperation(operation); - + converter.mapInputSocket(inputImageSocket, operation->getInputSocket(0)); converter.mapInputSocket(inputSocket, operation->getInputSocket(1)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket()); - + converter.addPreview(operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_DespeckleNode.h b/source/blender/compositor/nodes/COM_DespeckleNode.h index 64d99db7ded4..e8097be35dd6 100644 --- a/source/blender/compositor/nodes/COM_DespeckleNode.h +++ b/source/blender/compositor/nodes/COM_DespeckleNode.h @@ -18,8 +18,8 @@ * Contributor: Campbell Barton */ -#ifndef _COM_DespeckleNode_h_ -#define _COM_DespeckleNode_h_ +#ifndef __COM_DESPECKLENODE_H__ +#define __COM_DESPECKLENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DifferenceMatteNode.cpp b/source/blender/compositor/nodes/COM_DifferenceMatteNode.cpp index f19cfd443a8c..3867a5430636 100644 --- a/source/blender/compositor/nodes/COM_DifferenceMatteNode.cpp +++ b/source/blender/compositor/nodes/COM_DifferenceMatteNode.cpp @@ -41,17 +41,17 @@ void DifferenceMatteNode::convertToOperations(NodeConverter &converter, const Co DifferenceMatteOperation *operationSet = new DifferenceMatteOperation(); operationSet->setSettings((NodeChroma *)editorNode->storage); converter.addOperation(operationSet); - + converter.mapInputSocket(inputSocket, operationSet->getInputSocket(0)); converter.mapInputSocket(inputSocket2, operationSet->getInputSocket(1)); converter.mapOutputSocket(outputSocketMatte, operationSet->getOutputSocket(0)); SetAlphaOperation *operation = new SetAlphaOperation(); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.addLink(operationSet->getOutputSocket(), operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketImage, operation->getOutputSocket()); - + converter.addPreview(operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_DifferenceMatteNode.h b/source/blender/compositor/nodes/COM_DifferenceMatteNode.h index 98fb917e1523..ea3da8d2fca2 100644 --- a/source/blender/compositor/nodes/COM_DifferenceMatteNode.h +++ b/source/blender/compositor/nodes/COM_DifferenceMatteNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DifferenceMatteNode_h_ -#define _COM_DifferenceMatteNode_h_ +#ifndef __COM_DIFFERENCEMATTENODE_H__ +#define __COM_DIFFERENCEMATTENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DilateErodeNode.cpp b/source/blender/compositor/nodes/COM_DilateErodeNode.cpp index 6e78fcb38f1f..102dba3b9570 100644 --- a/source/blender/compositor/nodes/COM_DilateErodeNode.cpp +++ b/source/blender/compositor/nodes/COM_DilateErodeNode.cpp @@ -45,20 +45,20 @@ DilateErodeNode::DilateErodeNode(bNode *editorNode) : Node(editorNode) void DilateErodeNode::convertToOperations(NodeConverter &converter, const CompositorContext &context) const { - + bNode *editorNode = this->getbNode(); if (editorNode->custom1 == CMP_NODE_DILATEERODE_DISTANCE_THRESH) { DilateErodeThresholdOperation *operation = new DilateErodeThresholdOperation(); operation->setDistance(editorNode->custom2); operation->setInset(editorNode->custom3); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); - + if (editorNode->custom3 < 2.0f) { AntiAliasOperation *antiAlias = new AntiAliasOperation(); converter.addOperation(antiAlias); - + converter.addLink(operation->getOutputSocket(), antiAlias->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), antiAlias->getOutputSocket(0)); } @@ -71,7 +71,7 @@ void DilateErodeNode::convertToOperations(NodeConverter &converter, const Compos DilateDistanceOperation *operation = new DilateDistanceOperation(); operation->setDistance(editorNode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } @@ -79,7 +79,7 @@ void DilateErodeNode::convertToOperations(NodeConverter &converter, const Compos ErodeDistanceOperation *operation = new ErodeDistanceOperation(); operation->setDistance(-editorNode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } @@ -93,20 +93,20 @@ void DilateErodeNode::convertToOperations(NodeConverter &converter, const Compos operationx->setQuality(quality); operationx->setFalloff(PROP_SMOOTH); converter.addOperation(operationx); - + converter.mapInputSocket(getInputSocket(0), operationx->getInputSocket(0)); // converter.mapInputSocket(getInputSocket(1), operationx->getInputSocket(1)); // no size input yet - + GaussianAlphaYBlurOperation *operationy = new GaussianAlphaYBlurOperation(); operationy->setData(&m_alpha_blur); operationy->setQuality(quality); operationy->setFalloff(PROP_SMOOTH); converter.addOperation(operationy); - + converter.addLink(operationx->getOutputSocket(), operationy->getInputSocket(0)); // converter.mapInputSocket(getInputSocket(1), operationy->getInputSocket(1)); // no size input yet converter.mapOutputSocket(getOutputSocket(0), operationy->getOutputSocket()); - + converter.addPreview(operationy->getOutputSocket()); /* TODO? */ @@ -134,7 +134,7 @@ void DilateErodeNode::convertToOperations(NodeConverter &converter, const Compos DilateStepOperation *operation = new DilateStepOperation(); operation->setIterations(editorNode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } @@ -142,7 +142,7 @@ void DilateErodeNode::convertToOperations(NodeConverter &converter, const Compos ErodeStepOperation *operation = new ErodeStepOperation(); operation->setIterations(-editorNode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_DilateErodeNode.h b/source/blender/compositor/nodes/COM_DilateErodeNode.h index 560087da30ad..aff3ecbb4b0b 100644 --- a/source/blender/compositor/nodes/COM_DilateErodeNode.h +++ b/source/blender/compositor/nodes/COM_DilateErodeNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DilateErodeNode_h_ -#define _COM_DilateErodeNode_h_ +#ifndef __COM_DILATEERODENODE_H__ +#define __COM_DILATEERODENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DirectionalBlurNode.cpp b/source/blender/compositor/nodes/COM_DirectionalBlurNode.cpp index 9a4ced2bf966..9f846c67b1df 100644 --- a/source/blender/compositor/nodes/COM_DirectionalBlurNode.cpp +++ b/source/blender/compositor/nodes/COM_DirectionalBlurNode.cpp @@ -37,7 +37,7 @@ void DirectionalBlurNode::convertToOperations(NodeConverter &converter, const Co operation->setQuality(context.getQuality()); operation->setData(data); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_DirectionalBlurNode.h b/source/blender/compositor/nodes/COM_DirectionalBlurNode.h index 720ac32005e1..eef51e140bc7 100644 --- a/source/blender/compositor/nodes/COM_DirectionalBlurNode.h +++ b/source/blender/compositor/nodes/COM_DirectionalBlurNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DirectionalBlurNode_h_ -#define _COM_DirectionalBlurNode_h_ +#ifndef __COM_DIRECTIONALBLURNODE_H__ +#define __COM_DIRECTIONALBLURNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DisplaceNode.h b/source/blender/compositor/nodes/COM_DisplaceNode.h index 6eb894077fcc..28105fd59637 100644 --- a/source/blender/compositor/nodes/COM_DisplaceNode.h +++ b/source/blender/compositor/nodes/COM_DisplaceNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DisplaceNode_h_ -#define _COM_DisplaceNode_h_ +#ifndef __COM_DISPLACENODE_H__ +#define __COM_DISPLACENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DistanceMatteNode.cpp b/source/blender/compositor/nodes/COM_DistanceMatteNode.cpp index 52c764f22232..fc05e0564bc2 100644 --- a/source/blender/compositor/nodes/COM_DistanceMatteNode.cpp +++ b/source/blender/compositor/nodes/COM_DistanceMatteNode.cpp @@ -35,27 +35,27 @@ void DistanceMatteNode::convertToOperations(NodeConverter &converter, const Comp { bNode *editorsnode = getbNode(); NodeChroma *storage = (NodeChroma *)editorsnode->storage; - + NodeInput *inputSocketImage = this->getInputSocket(0); NodeInput *inputSocketKey = this->getInputSocket(1); NodeOutput *outputSocketImage = this->getOutputSocket(0); NodeOutput *outputSocketMatte = this->getOutputSocket(1); - + SetAlphaOperation *operationAlpha = new SetAlphaOperation(); converter.addOperation(operationAlpha); - + /* work in RGB color space */ NodeOperation *operation; if (storage->channel == 1) { DistanceRGBMatteOperation *matte = new DistanceRGBMatteOperation(); matte->setSettings(storage); converter.addOperation(matte); - + converter.mapInputSocket(inputSocketImage, matte->getInputSocket(0)); converter.mapInputSocket(inputSocketImage, operationAlpha->getInputSocket(0)); - + converter.mapInputSocket(inputSocketKey, matte->getInputSocket(1)); - + operation = matte; } /* work in YCbCr color space */ @@ -63,27 +63,27 @@ void DistanceMatteNode::convertToOperations(NodeConverter &converter, const Comp DistanceYCCMatteOperation *matte = new DistanceYCCMatteOperation(); matte->setSettings(storage); converter.addOperation(matte); - + ConvertRGBToYCCOperation *operationYCCImage = new ConvertRGBToYCCOperation(); ConvertRGBToYCCOperation *operationYCCMatte = new ConvertRGBToYCCOperation(); operationYCCImage->setMode(BLI_YCC_ITU_BT709); operationYCCMatte->setMode(BLI_YCC_ITU_BT709); converter.addOperation(operationYCCImage); converter.addOperation(operationYCCMatte); - + converter.mapInputSocket(inputSocketImage, operationYCCImage->getInputSocket(0)); converter.addLink(operationYCCImage->getOutputSocket(), matte->getInputSocket(0)); converter.addLink(operationYCCImage->getOutputSocket(), operationAlpha->getInputSocket(0)); - + converter.mapInputSocket(inputSocketKey, operationYCCMatte->getInputSocket(0)); converter.addLink(operationYCCMatte->getOutputSocket(), matte->getInputSocket(1)); - + operation = matte; } - + converter.mapOutputSocket(outputSocketMatte, operation->getOutputSocket(0)); converter.addLink(operation->getOutputSocket(), operationAlpha->getInputSocket(1)); - + if (storage->channel != 1) { ConvertYCCToRGBOperation *inv_convert = new ConvertYCCToRGBOperation(); inv_convert->setMode(BLI_YCC_ITU_BT709); diff --git a/source/blender/compositor/nodes/COM_DistanceMatteNode.h b/source/blender/compositor/nodes/COM_DistanceMatteNode.h index e7a514b79c46..e7bd3c57dfa7 100644 --- a/source/blender/compositor/nodes/COM_DistanceMatteNode.h +++ b/source/blender/compositor/nodes/COM_DistanceMatteNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DistanceMatteNode_h_ -#define _COM_DistanceMatteNode_h_ +#ifndef __COM_DISTANCEMATTENODE_H__ +#define __COM_DISTANCEMATTENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.cpp b/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.cpp index 913d97a6395e..1a10b912b238 100644 --- a/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.cpp +++ b/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.cpp @@ -33,12 +33,12 @@ void DoubleEdgeMaskNode::convertToOperations(NodeConverter &converter, const Com { DoubleEdgeMaskOperation *operation; bNode *bnode = this->getbNode(); - + operation = new DoubleEdgeMaskOperation(); operation->setAdjecentOnly(bnode->custom1); operation->setKeepInside(bnode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.h b/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.h index 4ee58e18c9b4..91a230051289 100644 --- a/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.h +++ b/source/blender/compositor/nodes/COM_DoubleEdgeMaskNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DoubleEdgeMaskNode_h_ -#define _COM_DoubleEdgeMaskNode_h_ +#ifndef __COM_DOUBLEEDGEMASKNODE_H__ +#define __COM_DOUBLEEDGEMASKNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_EllipseMaskNode.cpp b/source/blender/compositor/nodes/COM_EllipseMaskNode.cpp index c0c99a2efe89..60dc377518bc 100644 --- a/source/blender/compositor/nodes/COM_EllipseMaskNode.cpp +++ b/source/blender/compositor/nodes/COM_EllipseMaskNode.cpp @@ -36,13 +36,13 @@ void EllipseMaskNode::convertToOperations(NodeConverter &converter, const Compos { NodeInput *inputSocket = this->getInputSocket(0); NodeOutput *outputSocket = this->getOutputSocket(0); - + EllipseMaskOperation *operation; operation = new EllipseMaskOperation(); operation->setData((NodeEllipseMask *)this->getbNode()->storage); operation->setMaskType(this->getbNode()->custom1); converter.addOperation(operation); - + if (inputSocket->isLinked()) { converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket()); @@ -68,6 +68,6 @@ void EllipseMaskNode::convertToOperations(NodeConverter &converter, const Compos converter.addLink(scaleOperation->getOutputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); } - + converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); } diff --git a/source/blender/compositor/nodes/COM_EllipseMaskNode.h b/source/blender/compositor/nodes/COM_EllipseMaskNode.h index 50c578c2d7b6..e5e9861b2d93 100644 --- a/source/blender/compositor/nodes/COM_EllipseMaskNode.h +++ b/source/blender/compositor/nodes/COM_EllipseMaskNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_EllipseMaskNode_h_ -#define _COM_EllipseMaskNode_h_ +#ifndef __COM_ELLIPSEMASKNODE_H__ +#define __COM_ELLIPSEMASKNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_FilterNode.cpp b/source/blender/compositor/nodes/COM_FilterNode.cpp index 627f2a30f6e3..ad25894929e3 100644 --- a/source/blender/compositor/nodes/COM_FilterNode.cpp +++ b/source/blender/compositor/nodes/COM_FilterNode.cpp @@ -38,7 +38,7 @@ void FilterNode::convertToOperations(NodeConverter &converter, const CompositorC NodeInput *inputImageSocket = this->getInputSocket(1); NodeOutput *outputSocket = this->getOutputSocket(0); ConvolutionFilterOperation *operation = NULL; - + switch (this->getbNode()->custom1) { case CMP_FILT_SOFT: operation = new ConvolutionFilterOperation(); @@ -74,10 +74,10 @@ void FilterNode::convertToOperations(NodeConverter &converter, const CompositorC break; } converter.addOperation(operation); - + converter.mapInputSocket(inputImageSocket, operation->getInputSocket(0)); converter.mapInputSocket(inputSocket, operation->getInputSocket(1)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket()); - + converter.addPreview(operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_FlipNode.cpp b/source/blender/compositor/nodes/COM_FlipNode.cpp index 4cbae9bab66b..2d1b60b784e5 100644 --- a/source/blender/compositor/nodes/COM_FlipNode.cpp +++ b/source/blender/compositor/nodes/COM_FlipNode.cpp @@ -49,7 +49,7 @@ void FlipNode::convertToOperations(NodeConverter &converter, const CompositorCon operation->setFlipY(true); break; } - + converter.addOperation(operation); converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_FlipNode.h b/source/blender/compositor/nodes/COM_FlipNode.h index 033f893ab76b..8c9a78df85d3 100644 --- a/source/blender/compositor/nodes/COM_FlipNode.h +++ b/source/blender/compositor/nodes/COM_FlipNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_FlipNode_h_ -#define _COM_FlipNode_h_ +#ifndef __COM_FLIPNODE_H__ +#define __COM_FLIPNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_GammaNode.cpp b/source/blender/compositor/nodes/COM_GammaNode.cpp index 383231ff3264..fdee02b2d027 100644 --- a/source/blender/compositor/nodes/COM_GammaNode.cpp +++ b/source/blender/compositor/nodes/COM_GammaNode.cpp @@ -33,7 +33,7 @@ void GammaNode::convertToOperations(NodeConverter &converter, const CompositorCo { GammaOperation *operation = new GammaOperation(); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_GammaNode.h b/source/blender/compositor/nodes/COM_GammaNode.h index 3b8a530edd9a..8b6434b9c6a5 100644 --- a/source/blender/compositor/nodes/COM_GammaNode.h +++ b/source/blender/compositor/nodes/COM_GammaNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GammaNode_h_ -#define _COM_GammaNode_h_ +#ifndef __COM_GAMMANODE_H__ +#define __COM_GAMMANODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_GlareNode.cpp b/source/blender/compositor/nodes/COM_GlareNode.cpp index b52ef9ebb33a..2e012b097b3c 100644 --- a/source/blender/compositor/nodes/COM_GlareNode.cpp +++ b/source/blender/compositor/nodes/COM_GlareNode.cpp @@ -40,7 +40,7 @@ void GlareNode::convertToOperations(NodeConverter &converter, const CompositorCo { bNode *node = this->getbNode(); NodeGlare *glare = (NodeGlare *)node->storage; - + GlareBaseOperation *glareoperation = NULL; switch (glare->type) { default: @@ -59,17 +59,17 @@ void GlareNode::convertToOperations(NodeConverter &converter, const CompositorCo } BLI_assert(glareoperation); glareoperation->setGlareSettings(glare); - + GlareThresholdOperation *thresholdOperation = new GlareThresholdOperation(); thresholdOperation->setGlareSettings(glare); - + SetValueOperation *mixvalueoperation = new SetValueOperation(); mixvalueoperation->setValue(0.5f + glare->mix * 0.5f); - + MixGlareOperation *mixoperation = new MixGlareOperation(); mixoperation->setResolutionInputSocketIndex(1); mixoperation->getInputSocket(2)->setResizeMode(COM_SC_FIT); - + converter.addOperation(glareoperation); converter.addOperation(thresholdOperation); converter.addOperation(mixvalueoperation); @@ -77,7 +77,7 @@ void GlareNode::convertToOperations(NodeConverter &converter, const CompositorCo converter.mapInputSocket(getInputSocket(0), thresholdOperation->getInputSocket(0)); converter.addLink(thresholdOperation->getOutputSocket(), glareoperation->getInputSocket(0)); - + converter.addLink(mixvalueoperation->getOutputSocket(), mixoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(0), mixoperation->getInputSocket(1)); converter.addLink(glareoperation->getOutputSocket(), mixoperation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_GlareNode.h b/source/blender/compositor/nodes/COM_GlareNode.h index afc9ad3e6f34..93f923138351 100644 --- a/source/blender/compositor/nodes/COM_GlareNode.h +++ b/source/blender/compositor/nodes/COM_GlareNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareNode_h_ -#define _COM_GlareNode_h_ +#ifndef __COM_GLARENODE_H__ +#define __COM_GLARENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.cpp b/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.cpp index 0c572c1ddc7e..3542bc7f36ee 100644 --- a/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.cpp +++ b/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.cpp @@ -42,17 +42,17 @@ void HueSaturationValueCorrectNode::convertToOperations(NodeConverter &converter NodeOutput *outputSocket = this->getOutputSocket(0); bNode *editorsnode = getbNode(); CurveMapping *storage = (CurveMapping *)editorsnode->storage; - + ConvertRGBToHSVOperation *rgbToHSV = new ConvertRGBToHSVOperation(); converter.addOperation(rgbToHSV); - + ConvertHSVToRGBOperation *hsvToRGB = new ConvertHSVToRGBOperation(); converter.addOperation(hsvToRGB); - + HueSaturationValueCorrectOperation *changeHSV = new HueSaturationValueCorrectOperation(); changeHSV->setCurveMapping(storage); converter.addOperation(changeHSV); - + MixBlendOperation *blend = new MixBlendOperation(); blend->setResolutionInputSocketIndex(1); converter.addOperation(blend); diff --git a/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.h b/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.h index cc4256266082..f940a20e0dab 100644 --- a/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.h +++ b/source/blender/compositor/nodes/COM_HueSaturationValueCorrectNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_HueSaturationValueCorrectNode_h_ -#define _COM_HueSaturationValueCorrectNode_h_ +#ifndef __COM_HUESATURATIONVALUECORRECTNODE_H__ +#define __COM_HUESATURATIONVALUECORRECTNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp b/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp index b31fe7ac0305..7da8c5b3d3da 100644 --- a/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp +++ b/source/blender/compositor/nodes/COM_HueSaturationValueNode.cpp @@ -46,16 +46,16 @@ void HueSaturationValueNode::convertToOperations(NodeConverter &converter, const ConvertRGBToHSVOperation *rgbToHSV = new ConvertRGBToHSVOperation(); converter.addOperation(rgbToHSV); - + ConvertHSVToRGBOperation *hsvToRGB = new ConvertHSVToRGBOperation(); converter.addOperation(hsvToRGB); - + ChangeHSVOperation *changeHSV = new ChangeHSVOperation(); converter.mapInputSocket(hueSocket, changeHSV->getInputSocket(1)); converter.mapInputSocket(saturationSocket, changeHSV->getInputSocket(2)); converter.mapInputSocket(valueSocket, changeHSV->getInputSocket(3)); converter.addOperation(changeHSV); - + MixBlendOperation *blend = new MixBlendOperation(); blend->setResolutionInputSocketIndex(1); converter.addOperation(blend); diff --git a/source/blender/compositor/nodes/COM_HueSaturationValueNode.h b/source/blender/compositor/nodes/COM_HueSaturationValueNode.h index 669cb6d2cff5..f09164de34fe 100644 --- a/source/blender/compositor/nodes/COM_HueSaturationValueNode.h +++ b/source/blender/compositor/nodes/COM_HueSaturationValueNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_HueSaturationValueNode_h_ -#define _COM_HueSaturationValueNode_h_ +#ifndef __COM_HUESATURATIONVALUENODE_H__ +#define __COM_HUESATURATIONVALUENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_IDMaskNode.cpp b/source/blender/compositor/nodes/COM_IDMaskNode.cpp index 471373522262..ab5931ea5668 100644 --- a/source/blender/compositor/nodes/COM_IDMaskNode.cpp +++ b/source/blender/compositor/nodes/COM_IDMaskNode.cpp @@ -32,12 +32,12 @@ IDMaskNode::IDMaskNode(bNode *editorNode) : Node(editorNode) void IDMaskNode::convertToOperations(NodeConverter &converter, const CompositorContext &context) const { bNode *bnode = this->getbNode(); - + IDMaskOperation *operation; operation = new IDMaskOperation(); operation->setObjectIndex(bnode->custom1); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); if (bnode->custom2 == 0 || context.getRenderData()->scemode & R_FULL_SAMPLE) { converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); @@ -45,7 +45,7 @@ void IDMaskNode::convertToOperations(NodeConverter &converter, const CompositorC else { AntiAliasOperation *antiAliasOperation = new AntiAliasOperation(); converter.addOperation(antiAliasOperation); - + converter.addLink(operation->getOutputSocket(), antiAliasOperation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), antiAliasOperation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_IDMaskNode.h b/source/blender/compositor/nodes/COM_IDMaskNode.h index 120d173e5c38..8a6e55a946e4 100644 --- a/source/blender/compositor/nodes/COM_IDMaskNode.h +++ b/source/blender/compositor/nodes/COM_IDMaskNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_IDMaskNode_h_ -#define _COM_IDMaskNode_h_ +#ifndef __COM_IDMASKNODE_H__ +#define __COM_IDMASKNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ImageNode.cpp b/source/blender/compositor/nodes/COM_ImageNode.cpp index 337169ba748b..b82de5962e92 100644 --- a/source/blender/compositor/nodes/COM_ImageNode.cpp +++ b/source/blender/compositor/nodes/COM_ImageNode.cpp @@ -61,10 +61,10 @@ NodeOperation *ImageNode::doMultilayerCheck(NodeConverter &converter, RenderLaye operation->setRenderLayer(rl); operation->setImageUser(user); operation->setFramenumber(framenumber); - + converter.addOperation(operation); converter.mapOutputSocket(outputSocket, operation->getOutputSocket()); - + return operation; } @@ -189,10 +189,10 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo operation->setRenderData(context.getRenderData()); operation->setViewName(context.getViewName()); converter.addOperation(operation); - + if (outputStraightAlpha) { NodeOperation *alphaConvertOperation = new ConvertPremulToStraightOperation(); - + converter.addOperation(alphaConvertOperation); converter.mapOutputSocket(outputImage, alphaConvertOperation->getOutputSocket()); converter.addLink(operation->getOutputSocket(0), alphaConvertOperation->getInputSocket(0)); @@ -200,10 +200,10 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo else { converter.mapOutputSocket(outputImage, operation->getOutputSocket()); } - + converter.addPreview(operation->getOutputSocket()); } - + if (numberOfOutputs > 1) { NodeOutput *alphaImage = this->getOutputSocket(1); ImageAlphaOperation *alphaOperation = new ImageAlphaOperation(); @@ -213,7 +213,7 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo alphaOperation->setRenderData(context.getRenderData()); alphaOperation->setViewName(context.getViewName()); converter.addOperation(alphaOperation); - + converter.mapOutputSocket(alphaImage, alphaOperation->getOutputSocket()); } if (numberOfOutputs > 2) { @@ -225,7 +225,7 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo depthOperation->setRenderData(context.getRenderData()); depthOperation->setViewName(context.getViewName()); converter.addOperation(depthOperation); - + converter.mapOutputSocket(depthImage, depthOperation->getOutputSocket()); } if (numberOfOutputs > 3) { @@ -271,4 +271,3 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo } } } - diff --git a/source/blender/compositor/nodes/COM_InpaintNode.cpp b/source/blender/compositor/nodes/COM_InpaintNode.cpp index 17cc2fa653ea..41cc65e2fee7 100644 --- a/source/blender/compositor/nodes/COM_InpaintNode.cpp +++ b/source/blender/compositor/nodes/COM_InpaintNode.cpp @@ -33,7 +33,7 @@ InpaintNode::InpaintNode(bNode *editorNode) : Node(editorNode) void InpaintNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { - + bNode *editorNode = this->getbNode(); /* if (editorNode->custom1 == CMP_NODE_INPAINT_SIMPLE) { */ @@ -41,7 +41,7 @@ void InpaintNode::convertToOperations(NodeConverter &converter, const Compositor InpaintSimpleOperation *operation = new InpaintSimpleOperation(); operation->setIterations(editorNode->custom2); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_InpaintNode.h b/source/blender/compositor/nodes/COM_InpaintNode.h index 6c167ed90ffd..dcc563234bef 100644 --- a/source/blender/compositor/nodes/COM_InpaintNode.h +++ b/source/blender/compositor/nodes/COM_InpaintNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_InpaintNode_h_ -#define _COM_InpaintNode_h_ +#ifndef __COM_INPAINTNODE_H__ +#define __COM_INPAINTNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_InvertNode.cpp b/source/blender/compositor/nodes/COM_InvertNode.cpp index ebdb2cdb7c58..c83db3fe78fe 100644 --- a/source/blender/compositor/nodes/COM_InvertNode.cpp +++ b/source/blender/compositor/nodes/COM_InvertNode.cpp @@ -37,7 +37,7 @@ void InvertNode::convertToOperations(NodeConverter &converter, const CompositorC operation->setColor(node->custom1 & CMP_CHAN_RGB); operation->setAlpha(node->custom1 & CMP_CHAN_A); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_InvertNode.h b/source/blender/compositor/nodes/COM_InvertNode.h index a946799ce67c..9ca774e76004 100644 --- a/source/blender/compositor/nodes/COM_InvertNode.h +++ b/source/blender/compositor/nodes/COM_InvertNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_InvertNode_h_ -#define _COM_InvertNode_h_ +#ifndef __COM_INVERTNODE_H__ +#define __COM_INVERTNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_KeyingNode.cpp b/source/blender/compositor/nodes/COM_KeyingNode.cpp index ddfba07d9f75..261bdb93adbf 100644 --- a/source/blender/compositor/nodes/COM_KeyingNode.cpp +++ b/source/blender/compositor/nodes/COM_KeyingNode.cpp @@ -52,9 +52,9 @@ NodeOperationOutput *KeyingNode::setupPreBlur(NodeConverter &converter, NodeInpu ConvertRGBToYCCOperation *convertRGBToYCCOperation = new ConvertRGBToYCCOperation(); convertRGBToYCCOperation->setMode(BLI_YCC_ITU_BT709); converter.addOperation(convertRGBToYCCOperation); - + converter.mapInputSocket(inputImage, convertRGBToYCCOperation->getInputSocket(0)); - + CombineChannelsOperation *combineOperation = new CombineChannelsOperation(); converter.addOperation(combineOperation); @@ -62,9 +62,9 @@ NodeOperationOutput *KeyingNode::setupPreBlur(NodeConverter &converter, NodeInpu SeparateChannelOperation *separateOperation = new SeparateChannelOperation(); separateOperation->setChannel(channel); converter.addOperation(separateOperation); - + converter.addLink(convertRGBToYCCOperation->getOutputSocket(0), separateOperation->getInputSocket(0)); - + if (channel == 0 || channel == 3) { converter.addLink(separateOperation->getOutputSocket(0), combineOperation->getInputSocket(channel)); } @@ -73,24 +73,24 @@ NodeOperationOutput *KeyingNode::setupPreBlur(NodeConverter &converter, NodeInpu blurXOperation->setSize(size); blurXOperation->setAxis(KeyingBlurOperation::BLUR_AXIS_X); converter.addOperation(blurXOperation); - + KeyingBlurOperation *blurYOperation = new KeyingBlurOperation(); blurYOperation->setSize(size); blurYOperation->setAxis(KeyingBlurOperation::BLUR_AXIS_Y); converter.addOperation(blurYOperation); - + converter.addLink(separateOperation->getOutputSocket(), blurXOperation->getInputSocket(0)); converter.addLink(blurXOperation->getOutputSocket(), blurYOperation->getInputSocket(0)); converter.addLink(blurYOperation->getOutputSocket(0), combineOperation->getInputSocket(channel)); } } - + ConvertYCCToRGBOperation *convertYCCToRGBOperation = new ConvertYCCToRGBOperation(); convertYCCToRGBOperation->setMode(BLI_YCC_ITU_BT709); converter.addOperation(convertYCCToRGBOperation); - + converter.addLink(combineOperation->getOutputSocket(0), convertYCCToRGBOperation->getInputSocket(0)); - + return convertYCCToRGBOperation->getOutputSocket(0); } @@ -100,15 +100,15 @@ NodeOperationOutput *KeyingNode::setupPostBlur(NodeConverter &converter, NodeOpe blurXOperation->setSize(size); blurXOperation->setAxis(KeyingBlurOperation::BLUR_AXIS_X); converter.addOperation(blurXOperation); - + KeyingBlurOperation *blurYOperation = new KeyingBlurOperation(); blurYOperation->setSize(size); blurYOperation->setAxis(KeyingBlurOperation::BLUR_AXIS_Y); converter.addOperation(blurYOperation); - + converter.addLink(postBlurInput, blurXOperation->getInputSocket(0)); converter.addLink(blurXOperation->getOutputSocket(), blurYOperation->getInputSocket(0)); - + return blurYOperation->getOutputSocket(); } @@ -124,9 +124,9 @@ NodeOperationOutput *KeyingNode::setupDilateErode(NodeConverter &converter, Node dilateErodeOperation->setDistance(-distance); } converter.addOperation(dilateErodeOperation); - + converter.addLink(dilateErodeInput, dilateErodeOperation->getInputSocket(0)); - + return dilateErodeOperation->getOutputSocket(0); } @@ -154,7 +154,7 @@ NodeOperationOutput *KeyingNode::setupFeather(NodeConverter &converter, const Co operationx->setSubtract(distance < 0); operationx->setFalloff(falloff); converter.addOperation(operationx); - + GaussianAlphaYBlurOperation *operationy = new GaussianAlphaYBlurOperation(); operationy->setData(&data); operationy->setQuality(quality); @@ -176,10 +176,10 @@ NodeOperationOutput *KeyingNode::setupDespill(NodeConverter &converter, NodeOper despillOperation->setDespillFactor(factor); despillOperation->setColorBalance(colorBalance); converter.addOperation(despillOperation); - + converter.addLink(despillInput, despillOperation->getInputSocket(0)); converter.mapInputSocket(inputScreen, despillOperation->getInputSocket(1)); - + return despillOperation->getOutputSocket(0); } @@ -193,9 +193,9 @@ NodeOperationOutput *KeyingNode::setupClip(NodeConverter &converter, NodeOperati clipOperation->setClipWhite(clipWhite); clipOperation->setIsEdgeMatte(edgeMatte); converter.addOperation(clipOperation); - + converter.addLink(clipInput, clipOperation->getInputSocket(0)); - + return clipOperation->getOutputSocket(0); } @@ -203,7 +203,7 @@ void KeyingNode::convertToOperations(NodeConverter &converter, const CompositorC { bNode *editorNode = this->getbNode(); NodeKeyingData *keying_data = (NodeKeyingData *) editorNode->storage; - + NodeInput *inputImage = this->getInputSocket(0); NodeInput *inputScreen = this->getInputSocket(1); NodeInput *inputGarbageMatte = this->getInputSocket(2); @@ -212,14 +212,14 @@ void KeyingNode::convertToOperations(NodeConverter &converter, const CompositorC NodeOutput *outputMatte = this->getOutputSocket(1); NodeOutput *outputEdges = this->getOutputSocket(2); NodeOperationOutput *postprocessedMatte = NULL, *postprocessedImage = NULL, *edgesMatte = NULL; - + /* keying operation */ KeyingOperation *keyingOperation = new KeyingOperation(); keyingOperation->setScreenBalance(keying_data->screen_balance); converter.addOperation(keyingOperation); - + converter.mapInputSocket(inputScreen, keyingOperation->getInputSocket(1)); - + if (keying_data->blur_pre) { /* chroma preblur operation for input of keying operation */ NodeOperationOutput *preBluredImage = setupPreBlur(converter, inputImage, keying_data->blur_pre); @@ -228,53 +228,53 @@ void KeyingNode::convertToOperations(NodeConverter &converter, const CompositorC else { converter.mapInputSocket(inputImage, keyingOperation->getInputSocket(0)); } - + postprocessedMatte = keyingOperation->getOutputSocket(); - + /* black / white clipping */ if (keying_data->clip_black > 0.0f || keying_data->clip_white < 1.0f) { postprocessedMatte = setupClip(converter, postprocessedMatte, keying_data->edge_kernel_radius, keying_data->edge_kernel_tolerance, keying_data->clip_black, keying_data->clip_white, false); } - + /* output edge matte */ edgesMatte = setupClip(converter, postprocessedMatte, keying_data->edge_kernel_radius, keying_data->edge_kernel_tolerance, keying_data->clip_black, keying_data->clip_white, true); - + /* apply garbage matte */ if (inputGarbageMatte->isLinked()) { SetValueOperation *valueOperation = new SetValueOperation(); valueOperation->setValue(1.0f); converter.addOperation(valueOperation); - + MathSubtractOperation *subtractOperation = new MathSubtractOperation(); converter.addOperation(subtractOperation); - + MathMinimumOperation *minOperation = new MathMinimumOperation(); converter.addOperation(minOperation); - + converter.addLink(valueOperation->getOutputSocket(), subtractOperation->getInputSocket(0)); converter.mapInputSocket(inputGarbageMatte, subtractOperation->getInputSocket(1)); - + converter.addLink(subtractOperation->getOutputSocket(), minOperation->getInputSocket(0)); converter.addLink(postprocessedMatte, minOperation->getInputSocket(1)); - + postprocessedMatte = minOperation->getOutputSocket(); } - + /* apply core matte */ if (inputCoreMatte->isLinked()) { MathMaximumOperation *maxOperation = new MathMaximumOperation(); converter.addOperation(maxOperation); - + converter.mapInputSocket(inputCoreMatte, maxOperation->getInputSocket(0)); converter.addLink(postprocessedMatte, maxOperation->getInputSocket(1)); - + postprocessedMatte = maxOperation->getOutputSocket(); } - + /* apply blur on matte if needed */ if (keying_data->blur_post) postprocessedMatte = setupPostBlur(converter, postprocessedMatte, keying_data->blur_post); @@ -293,7 +293,7 @@ void KeyingNode::convertToOperations(NodeConverter &converter, const CompositorC /* set alpha channel to output image */ SetAlphaOperation *alphaOperation = new SetAlphaOperation(); converter.addOperation(alphaOperation); - + converter.mapInputSocket(inputImage, alphaOperation->getInputSocket(0)); converter.addLink(postprocessedMatte, alphaOperation->getInputSocket(1)); diff --git a/source/blender/compositor/nodes/COM_KeyingScreenNode.cpp b/source/blender/compositor/nodes/COM_KeyingScreenNode.cpp index 70b3b696e37b..df9668883e87 100644 --- a/source/blender/compositor/nodes/COM_KeyingScreenNode.cpp +++ b/source/blender/compositor/nodes/COM_KeyingScreenNode.cpp @@ -39,15 +39,15 @@ void KeyingScreenNode::convertToOperations(NodeConverter &converter, const Compo bNode *editorNode = this->getbNode(); MovieClip *clip = (MovieClip *) editorNode->id; NodeKeyingScreenData *keyingscreen_data = (NodeKeyingScreenData *) editorNode->storage; - + NodeOutput *outputScreen = this->getOutputSocket(0); - + // always connect the output image KeyingScreenOperation *operation = new KeyingScreenOperation(); operation->setMovieClip(clip); operation->setTrackingObject(keyingscreen_data->tracking_object); operation->setFramenumber(context.getFramenumber()); converter.addOperation(operation); - + converter.mapOutputSocket(outputScreen, operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_LensDistortionNode.cpp b/source/blender/compositor/nodes/COM_LensDistortionNode.cpp index b6cc2acb9a62..2bad80839e15 100644 --- a/source/blender/compositor/nodes/COM_LensDistortionNode.cpp +++ b/source/blender/compositor/nodes/COM_LensDistortionNode.cpp @@ -37,7 +37,7 @@ void LensDistortionNode::convertToOperations(NodeConverter &converter, const Com if (data->proj) { ProjectorLensDistortionOperation *operation = new ProjectorLensDistortionOperation(); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); @@ -51,9 +51,9 @@ void LensDistortionNode::convertToOperations(NodeConverter &converter, const Com operation->setDistortion(getInputSocket(1)->getEditorValueFloat()); if (!getInputSocket(2)->isLinked()) operation->setDispersion(getInputSocket(2)->getEditorValueFloat()); - + converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_LensDistortionNode.h b/source/blender/compositor/nodes/COM_LensDistortionNode.h index 231de6a51754..ee0f9f1bc067 100644 --- a/source/blender/compositor/nodes/COM_LensDistortionNode.h +++ b/source/blender/compositor/nodes/COM_LensDistortionNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_LensDistortionNode_h_ -#define _COM_LensDistortionNode_h_ +#ifndef __COM_LENSDISTORTIONNODE_H__ +#define __COM_LENSDISTORTIONNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp b/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp index de6ad3df0303..12f3b1bc4103 100644 --- a/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp +++ b/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp @@ -46,10 +46,10 @@ void LuminanceMatteNode::convertToOperations(NodeConverter &converter, const Com SetAlphaOperation *operation = new SetAlphaOperation(); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.addLink(operationSet->getOutputSocket(), operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketImage, operation->getOutputSocket()); - + converter.addPreview(operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_MapRangeNode.cpp b/source/blender/compositor/nodes/COM_MapRangeNode.cpp index 81ee4f0d7a93..6590cf043068 100644 --- a/source/blender/compositor/nodes/COM_MapRangeNode.cpp +++ b/source/blender/compositor/nodes/COM_MapRangeNode.cpp @@ -38,11 +38,11 @@ void MapRangeNode::convertToOperations(NodeConverter &converter, const Composito NodeInput *destMinSocket = this->getInputSocket(3); NodeInput *destMaxSocket = this->getInputSocket(4); NodeOutput *outputSocket = this->getOutputSocket(0); - + MapRangeOperation *operation = new MapRangeOperation(); operation->setUseClamp(this->getbNode()->custom1); converter.addOperation(operation); - + converter.mapInputSocket(valueSocket, operation->getInputSocket(0)); converter.mapInputSocket(sourceMinSocket, operation->getInputSocket(1)); converter.mapInputSocket(sourceMaxSocket, operation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_MapUVNode.cpp b/source/blender/compositor/nodes/COM_MapUVNode.cpp index c593805c9405..dc477ad9da02 100644 --- a/source/blender/compositor/nodes/COM_MapUVNode.cpp +++ b/source/blender/compositor/nodes/COM_MapUVNode.cpp @@ -31,7 +31,7 @@ MapUVNode::MapUVNode(bNode *editorNode) : Node(editorNode) void MapUVNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bNode *node = this->getbNode(); - + MapUVOperation *operation = new MapUVOperation(); operation->setAlpha((float)node->custom1); operation->setResolutionInputSocketIndex(1); diff --git a/source/blender/compositor/nodes/COM_MapUVNode.h b/source/blender/compositor/nodes/COM_MapUVNode.h index 286ec4205f19..245a31ce83cc 100644 --- a/source/blender/compositor/nodes/COM_MapUVNode.h +++ b/source/blender/compositor/nodes/COM_MapUVNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_MapUVNode_h_ -#define _COM_MapUVNode_h_ +#ifndef __COM_MAPUVNODE_H__ +#define __COM_MAPUVNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_MapValueNode.cpp b/source/blender/compositor/nodes/COM_MapValueNode.cpp index 9a4c4880b621..6276548c7a7b 100644 --- a/source/blender/compositor/nodes/COM_MapValueNode.cpp +++ b/source/blender/compositor/nodes/COM_MapValueNode.cpp @@ -33,14 +33,14 @@ MapValueNode::MapValueNode(bNode *editorNode) : Node(editorNode) void MapValueNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { TexMapping *storage = (TexMapping *)this->getbNode()->storage; - + NodeInput *colorSocket = this->getInputSocket(0); NodeOutput *valueSocket = this->getOutputSocket(0); - + MapValueOperation *convertProg = new MapValueOperation(); convertProg->setSettings(storage); converter.addOperation(convertProg); - + converter.mapInputSocket(colorSocket, convertProg->getInputSocket(0)); converter.mapOutputSocket(valueSocket, convertProg->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_MathNode.cpp b/source/blender/compositor/nodes/COM_MathNode.cpp index e9bed136a371..25c617a34878 100644 --- a/source/blender/compositor/nodes/COM_MathNode.cpp +++ b/source/blender/compositor/nodes/COM_MathNode.cpp @@ -27,7 +27,7 @@ void MathNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { MathBaseOperation *operation = NULL; - + switch (this->getbNode()->custom1) { case NODE_MATH_ADD: operation = new MathAddOperation(); @@ -89,13 +89,25 @@ void MathNode::convertToOperations(NodeConverter &converter, const CompositorCon case NODE_MATH_ATAN2: operation = new MathArcTan2Operation(); break; + case NODE_MATH_FLOOR: + operation = new MathFloorOperation(); + break; + case NODE_MATH_CEIL: + operation = new MathCeilOperation(); + break; + case NODE_MATH_FRACT: + operation = new MathFractOperation(); + break; + case NODE_MATH_SQRT: + operation = new MathSqrtOperation(); + break; } - + if (operation) { bool useClamp = getbNode()->custom2; operation->setUseClamp(useClamp); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_MathNode.h b/source/blender/compositor/nodes/COM_MathNode.h index 4c84dc2a3313..cf92765f6da9 100644 --- a/source/blender/compositor/nodes/COM_MathNode.h +++ b/source/blender/compositor/nodes/COM_MathNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MathNode_h_ -#define _COM_MathNode_h_ +#ifndef __COM_MATHNODE_H__ +#define __COM_MATHNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_MixNode.cpp b/source/blender/compositor/nodes/COM_MixNode.cpp index e807365d9db4..e0af0106513d 100644 --- a/source/blender/compositor/nodes/COM_MixNode.cpp +++ b/source/blender/compositor/nodes/COM_MixNode.cpp @@ -43,7 +43,7 @@ void MixNode::convertToOperations(NodeConverter &converter, const CompositorCont bNode *editorNode = this->getbNode(); bool useAlphaPremultiply = (this->getbNode()->custom2 & 1) != 0; bool useClamp = (this->getbNode()->custom2 & 2) != 0; - + MixBaseOperation *convertProg; switch (editorNode->custom1) { case MA_RAMP_ADD: @@ -106,11 +106,11 @@ void MixNode::convertToOperations(NodeConverter &converter, const CompositorCont convertProg->setUseValueAlphaMultiply(useAlphaPremultiply); convertProg->setUseClamp(useClamp); converter.addOperation(convertProg); - + converter.mapInputSocket(valueSocket, convertProg->getInputSocket(0)); converter.mapInputSocket(color1Socket, convertProg->getInputSocket(1)); converter.mapInputSocket(color2Socket, convertProg->getInputSocket(2)); converter.mapOutputSocket(outputSocket, convertProg->getOutputSocket(0)); - + converter.addPreview(convertProg->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_MixNode.h b/source/blender/compositor/nodes/COM_MixNode.h index e5424c2f4e59..10954080a51b 100644 --- a/source/blender/compositor/nodes/COM_MixNode.h +++ b/source/blender/compositor/nodes/COM_MixNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MixNode_h_ -#define _COM_MixNode_h_ +#ifndef __COM_MIXNODE_H__ +#define __COM_MIXNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_MovieClipNode.cpp b/source/blender/compositor/nodes/COM_MovieClipNode.cpp index 269d7f2cafee..18e6f811fff9 100644 --- a/source/blender/compositor/nodes/COM_MovieClipNode.cpp +++ b/source/blender/compositor/nodes/COM_MovieClipNode.cpp @@ -46,7 +46,7 @@ void MovieClipNode::convertToOperations(NodeConverter &converter, const Composit NodeOutput *offsetYMovieClip = this->getOutputSocket(3); NodeOutput *scaleMovieClip = this->getOutputSocket(4); NodeOutput *angleMovieClip = this->getOutputSocket(5); - + bNode *editorNode = this->getbNode(); MovieClip *movieClip = (MovieClip *)editorNode->id; MovieClipUser *movieClipUser = (MovieClipUser *)editorNode->storage; @@ -59,7 +59,7 @@ void MovieClipNode::convertToOperations(NodeConverter &converter, const Composit else ibuf = BKE_movieclip_get_ibuf_flag(movieClip, movieClipUser, movieClip->flag, MOVIECLIP_CACHE_SKIP); } - + // always connect the output image MovieClipOperation *operation = new MovieClipOperation(); operation->setMovieClip(movieClip); @@ -76,7 +76,7 @@ void MovieClipNode::convertToOperations(NodeConverter &converter, const Composit alphaOperation->setMovieClipUser(movieClipUser); alphaOperation->setFramenumber(context.getFramenumber()); alphaOperation->setCacheFrame(cacheFrame); - + converter.addOperation(alphaOperation); converter.mapOutputSocket(alphaMovieClip, alphaOperation->getOutputSocket()); @@ -99,7 +99,7 @@ void MovieClipNode::convertToOperations(NodeConverter &converter, const Composit converter.addOutputValue(offsetYMovieClip, loc[1]); converter.addOutputValue(scaleMovieClip, scale); converter.addOutputValue(angleMovieClip, angle); - + if (ibuf) { IMB_freeImBuf(ibuf); } diff --git a/source/blender/compositor/nodes/COM_MovieDistortionNode.cpp b/source/blender/compositor/nodes/COM_MovieDistortionNode.cpp index c4277354b430..e3009e068aba 100644 --- a/source/blender/compositor/nodes/COM_MovieDistortionNode.cpp +++ b/source/blender/compositor/nodes/COM_MovieDistortionNode.cpp @@ -35,10 +35,10 @@ void MovieDistortionNode::convertToOperations(NodeConverter &converter, const Co { bNode *bnode = this->getbNode(); MovieClip *clip = (MovieClip *)bnode->id; - + NodeInput *inputSocket = this->getInputSocket(0); NodeOutput *outputSocket = this->getOutputSocket(0); - + MovieDistortionOperation *operation = new MovieDistortionOperation(bnode->custom1 == 1); operation->setMovieClip(clip); operation->setFramenumber(context.getFramenumber()); diff --git a/source/blender/compositor/nodes/COM_MovieDistortionNode.h b/source/blender/compositor/nodes/COM_MovieDistortionNode.h index 5ef0115bbaaa..97cfaec57c8d 100644 --- a/source/blender/compositor/nodes/COM_MovieDistortionNode.h +++ b/source/blender/compositor/nodes/COM_MovieDistortionNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MovieDistortionNode_h_ -#define _COM_MovieDistortionNode_h_ +#ifndef __COM_MOVIEDISTORTIONNODE_H__ +#define __COM_MOVIEDISTORTIONNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_NormalNode.cpp b/source/blender/compositor/nodes/COM_NormalNode.cpp index bde5a126325b..64231d116fad 100644 --- a/source/blender/compositor/nodes/COM_NormalNode.cpp +++ b/source/blender/compositor/nodes/COM_NormalNode.cpp @@ -36,7 +36,7 @@ void NormalNode::convertToOperations(NodeConverter &converter, const CompositorC NodeInput *inputSocket = this->getInputSocket(0); NodeOutput *outputSocket = this->getOutputSocket(0); NodeOutput *outputSocketDotproduct = this->getOutputSocket(1); - + SetVectorOperation *operationSet = new SetVectorOperation(); float normal[3]; outputSocket->getEditorValueVector(normal); @@ -47,12 +47,12 @@ void NormalNode::convertToOperations(NodeConverter &converter, const CompositorC operationSet->setZ(normal[2]); operationSet->setW(0.0f); converter.addOperation(operationSet); - + converter.mapOutputSocket(outputSocket, operationSet->getOutputSocket(0)); - + DotproductOperation *operation = new DotproductOperation(); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.addLink(operationSet->getOutputSocket(0), operation->getInputSocket(1)); converter.mapOutputSocket(outputSocketDotproduct, operation->getOutputSocket(0)); diff --git a/source/blender/compositor/nodes/COM_NormalNode.h b/source/blender/compositor/nodes/COM_NormalNode.h index c9b37580ecae..4e1dbe553603 100644 --- a/source/blender/compositor/nodes/COM_NormalNode.h +++ b/source/blender/compositor/nodes/COM_NormalNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_NormalNode_h_ -#define _COM_NormalNode_h_ +#ifndef __COM_NORMALNODE_H__ +#define __COM_NORMALNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_NormalizeNode.h b/source/blender/compositor/nodes/COM_NormalizeNode.h index a0eb7c9f5a96..02f413c6ae42 100644 --- a/source/blender/compositor/nodes/COM_NormalizeNode.h +++ b/source/blender/compositor/nodes/COM_NormalizeNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_NormalizeNode_h_ -#define _COM_NormalizeNode_h_ +#ifndef __COM_NORMALIZENODE_H__ +#define __COM_NORMALIZENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_OutputFileNode.cpp b/source/blender/compositor/nodes/COM_OutputFileNode.cpp index 46e7f7fe790d..5a7e5e2c6234 100644 --- a/source/blender/compositor/nodes/COM_OutputFileNode.cpp +++ b/source/blender/compositor/nodes/COM_OutputFileNode.cpp @@ -39,7 +39,7 @@ void OutputFileNode::convertToOperations(NodeConverter &converter, const Composi { NodeImageMultiFile *storage = (NodeImageMultiFile *)this->getbNode()->storage; const bool is_multiview = (context.getRenderData()->scemode & R_MULTIVIEW) != 0; - + if (!context.isRendering()) { /* only output files when rendering a sequence - * otherwise, it overwrites the output files just @@ -70,12 +70,12 @@ void OutputFileNode::convertToOperations(NodeConverter &converter, const Composi for (int i = 0; i < num_inputs; ++i) { NodeInput *input = getInputSocket(i); NodeImageMultiFileSocket *sockdata = (NodeImageMultiFileSocket *)input->getbNodeSocket()->storage; - + /* note: layer becomes an empty placeholder if the input is not linked */ outputOperation->add_layer(sockdata->layer, input->getDataType(), input->isLinked()); - + converter.mapInputSocket(input, outputOperation->getInputSocket(i)); - + if (!previewAdded) { converter.addNodeInputPreview(input); previewAdded = true; diff --git a/source/blender/compositor/nodes/COM_OutputFileNode.h b/source/blender/compositor/nodes/COM_OutputFileNode.h index b321572d6380..b246dd2a5411 100644 --- a/source/blender/compositor/nodes/COM_OutputFileNode.h +++ b/source/blender/compositor/nodes/COM_OutputFileNode.h @@ -21,8 +21,8 @@ * Lukas Tönne */ -#ifndef _COM_OutputFileNode_h_ -#define _COM_OutputFileNode_h_ +#ifndef __COM_OUTPUTFILENODE_H__ +#define __COM_OUTPUTFILENODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_PixelateNode.cpp b/source/blender/compositor/nodes/COM_PixelateNode.cpp index fe806dbf3071..2b7ab0ea4e8f 100644 --- a/source/blender/compositor/nodes/COM_PixelateNode.cpp +++ b/source/blender/compositor/nodes/COM_PixelateNode.cpp @@ -35,7 +35,7 @@ void PixelateNode::convertToOperations(NodeConverter &converter, const Composito NodeInput *inputSocket = this->getInputSocket(0); NodeOutput *outputSocket = this->getOutputSocket(0); DataType datatype = inputSocket->getDataType(); - + if (inputSocket->isLinked()) { NodeOutput *link = inputSocket->getLink(); datatype = link->getDataType(); @@ -43,7 +43,7 @@ void PixelateNode::convertToOperations(NodeConverter &converter, const Composito PixelateOperation *operation = new PixelateOperation(datatype); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_PixelateNode.h b/source/blender/compositor/nodes/COM_PixelateNode.h index 06ac886c843c..b43c15b01dac 100644 --- a/source/blender/compositor/nodes/COM_PixelateNode.h +++ b/source/blender/compositor/nodes/COM_PixelateNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_PixelateNode_h_ -#define _COM_PixelateNode_h_ +#ifndef __COM_PIXELATENODE_H__ +#define __COM_PIXELATENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_PlaneTrackDeformNode.cpp b/source/blender/compositor/nodes/COM_PlaneTrackDeformNode.cpp index 379b9f193e82..d8e4655b84e6 100644 --- a/source/blender/compositor/nodes/COM_PlaneTrackDeformNode.cpp +++ b/source/blender/compositor/nodes/COM_PlaneTrackDeformNode.cpp @@ -42,13 +42,13 @@ void PlaneTrackDeformNode::convertToOperations(NodeConverter &converter, const C bNode *editorNode = this->getbNode(); MovieClip *clip = (MovieClip *) editorNode->id; NodePlaneTrackDeformData *data = (NodePlaneTrackDeformData *) editorNode->storage; - + int frame_number = context.getFramenumber(); - + NodeInput *input_image = this->getInputSocket(0); NodeOutput *output_warped_image = this->getOutputSocket(0); NodeOutput *output_plane = this->getOutputSocket(1); - + PlaneTrackWarpImageOperation *warp_image_operation = new PlaneTrackWarpImageOperation(); warp_image_operation->setMovieClip(clip); warp_image_operation->setTrackingObject(data->tracking_object); @@ -59,10 +59,10 @@ void PlaneTrackDeformNode::convertToOperations(NodeConverter &converter, const C warp_image_operation->setMotionBlurShutter(data->motion_blur_shutter); } converter.addOperation(warp_image_operation); - + converter.mapInputSocket(input_image, warp_image_operation->getInputSocket(0)); converter.mapOutputSocket(output_warped_image, warp_image_operation->getOutputSocket()); - + PlaneTrackMaskOperation *plane_mask_operation = new PlaneTrackMaskOperation(); plane_mask_operation->setMovieClip(clip); plane_mask_operation->setTrackingObject(data->tracking_object); @@ -73,6 +73,6 @@ void PlaneTrackDeformNode::convertToOperations(NodeConverter &converter, const C plane_mask_operation->setMotionBlurShutter(data->motion_blur_shutter); } converter.addOperation(plane_mask_operation); - + converter.mapOutputSocket(output_plane, plane_mask_operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_RotateNode.cpp b/source/blender/compositor/nodes/COM_RotateNode.cpp index 77638d669872..fe85d5db2557 100644 --- a/source/blender/compositor/nodes/COM_RotateNode.cpp +++ b/source/blender/compositor/nodes/COM_RotateNode.cpp @@ -39,10 +39,10 @@ void RotateNode::convertToOperations(NodeConverter &converter, const CompositorC RotateOperation *operation = new RotateOperation(); SetSamplerOperation *sampler = new SetSamplerOperation(); sampler->setSampler((PixelSampler)this->getbNode()->custom1); - + converter.addOperation(sampler); converter.addOperation(operation); - + converter.addLink(sampler->getOutputSocket(), operation->getInputSocket(0)); converter.mapInputSocket(inputSocket, sampler->getInputSocket(0)); converter.mapInputSocket(inputDegreeSocket, operation->getInputSocket(1)); diff --git a/source/blender/compositor/nodes/COM_RotateNode.h b/source/blender/compositor/nodes/COM_RotateNode.h index e897c9a49df5..e3c9710891be 100644 --- a/source/blender/compositor/nodes/COM_RotateNode.h +++ b/source/blender/compositor/nodes/COM_RotateNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_RotateNode_h_ -#define _COM_RotateNode_h_ +#ifndef __COM_ROTATENODE_H__ +#define __COM_ROTATENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ScaleNode.cpp b/source/blender/compositor/nodes/COM_ScaleNode.cpp index ef4128a78b4e..dc512684ce61 100644 --- a/source/blender/compositor/nodes/COM_ScaleNode.cpp +++ b/source/blender/compositor/nodes/COM_ScaleNode.cpp @@ -36,7 +36,7 @@ ScaleNode::ScaleNode(bNode *editorNode) : Node(editorNode) void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorContext &context) const { bNode *bnode = this->getbNode(); - + NodeInput *inputSocket = this->getInputSocket(0); NodeInput *inputXSocket = this->getInputSocket(1); NodeInput *inputYSocket = this->getInputSocket(2); @@ -47,7 +47,7 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo { ScaleOperation *operation = new ScaleOperation(); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.mapInputSocket(inputXSocket, operation->getInputSocket(1)); converter.mapInputSocket(inputYSocket, operation->getInputSocket(2)); @@ -62,10 +62,10 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo SetValueOperation *scaleFactorOperation = new SetValueOperation(); scaleFactorOperation->setValue(context.getRenderData()->size / 100.0f); converter.addOperation(scaleFactorOperation); - + ScaleOperation *operation = new ScaleOperation(); converter.addOperation(operation); - + converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); converter.addLink(scaleFactorOperation->getOutputSocket(), operation->getInputSocket(1)); converter.addLink(scaleFactorOperation->getOutputSocket(), operation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_ScaleNode.h b/source/blender/compositor/nodes/COM_ScaleNode.h index 614866d2318e..b1695aab9661 100644 --- a/source/blender/compositor/nodes/COM_ScaleNode.h +++ b/source/blender/compositor/nodes/COM_ScaleNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ScaleNode_h_ -#define _COM_ScaleNode_h_ +#ifndef __COM_SCALENODE_H__ +#define __COM_SCALENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_SeparateColorNode.cpp b/source/blender/compositor/nodes/COM_SeparateColorNode.cpp index 68fdaf01f5c5..b3f9ab46f358 100644 --- a/source/blender/compositor/nodes/COM_SeparateColorNode.cpp +++ b/source/blender/compositor/nodes/COM_SeparateColorNode.cpp @@ -38,55 +38,55 @@ void SeparateColorNode::convertToOperations(NodeConverter &converter, const Comp NodeOutput *outputGSocket = this->getOutputSocket(1); NodeOutput *outputBSocket = this->getOutputSocket(2); NodeOutput *outputASocket = this->getOutputSocket(3); - + NodeOperation *color_conv = getColorConverter(context); if (color_conv) { converter.addOperation(color_conv); - + converter.mapInputSocket(imageSocket, color_conv->getInputSocket(0)); } - + { SeparateChannelOperation *operation = new SeparateChannelOperation(); operation->setChannel(0); converter.addOperation(operation); - + if (color_conv) converter.addLink(color_conv->getOutputSocket(), operation->getInputSocket(0)); else converter.mapInputSocket(imageSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputRSocket, operation->getOutputSocket(0)); } - + { SeparateChannelOperation *operation = new SeparateChannelOperation(); operation->setChannel(1); converter.addOperation(operation); - + if (color_conv) converter.addLink(color_conv->getOutputSocket(), operation->getInputSocket(0)); else converter.mapInputSocket(imageSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputGSocket, operation->getOutputSocket(0)); } - + { SeparateChannelOperation *operation = new SeparateChannelOperation(); operation->setChannel(2); converter.addOperation(operation); - + if (color_conv) converter.addLink(color_conv->getOutputSocket(), operation->getInputSocket(0)); else converter.mapInputSocket(imageSocket, operation->getInputSocket(0)); converter.mapOutputSocket(outputBSocket, operation->getOutputSocket(0)); } - + { SeparateChannelOperation *operation = new SeparateChannelOperation(); operation->setChannel(3); converter.addOperation(operation); - + if (color_conv) converter.addLink(color_conv->getOutputSocket(), operation->getInputSocket(0)); else diff --git a/source/blender/compositor/nodes/COM_SeparateColorNode.h b/source/blender/compositor/nodes/COM_SeparateColorNode.h index d378a311e737..a1ec23b71c74 100644 --- a/source/blender/compositor/nodes/COM_SeparateColorNode.h +++ b/source/blender/compositor/nodes/COM_SeparateColorNode.h @@ -21,8 +21,8 @@ * Lukas Toenne */ -#ifndef _COM_SeparateColorNode_h_ -#define _COM_SeparateColorNode_h_ +#ifndef __COM_SEPARATECOLORNODE_H__ +#define __COM_SEPARATECOLORNODE_H__ #include "COM_Node.h" @@ -30,7 +30,7 @@ class SeparateColorNode : public Node { public: SeparateColorNode(bNode *editorNode); void convertToOperations(NodeConverter &converter, const CompositorContext &context) const; - + protected: virtual NodeOperation *getColorConverter(const CompositorContext &context) const = 0; }; @@ -40,7 +40,7 @@ class SeparateRGBANode : public SeparateColorNode { SeparateRGBANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -49,7 +49,7 @@ class SeparateHSVANode : public SeparateColorNode { SeparateHSVANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -58,7 +58,7 @@ class SeparateYCCANode : public SeparateColorNode { SeparateYCCANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; @@ -67,7 +67,7 @@ class SeparateYUVANode : public SeparateColorNode { SeparateYUVANode(bNode *editorNode) : SeparateColorNode(editorNode) {} - + NodeOperation *getColorConverter(const CompositorContext &context) const; }; diff --git a/source/blender/compositor/nodes/COM_SetAlphaNode.cpp b/source/blender/compositor/nodes/COM_SetAlphaNode.cpp index 4c55a4bdc0a8..b5d5bf9d9d9f 100644 --- a/source/blender/compositor/nodes/COM_SetAlphaNode.cpp +++ b/source/blender/compositor/nodes/COM_SetAlphaNode.cpp @@ -27,13 +27,13 @@ void SetAlphaNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { SetAlphaOperation *operation = new SetAlphaOperation(); - + if (!this->getInputSocket(0)->isLinked() && this->getInputSocket(1)->isLinked()) { operation->setResolutionInputSocketIndex(1); } - + converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_SetAlphaNode.h b/source/blender/compositor/nodes/COM_SetAlphaNode.h index efc8ccf1f277..f71d743c1d47 100644 --- a/source/blender/compositor/nodes/COM_SetAlphaNode.h +++ b/source/blender/compositor/nodes/COM_SetAlphaNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetAlphaNode_h_ -#define _COM_SetAlphaNode_h_ +#ifndef __COM_SETALPHANODE_H__ +#define __COM_SETALPHANODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_SocketProxyNode.cpp b/source/blender/compositor/nodes/COM_SocketProxyNode.cpp index c76b057577cb..230c27dd9a0d 100644 --- a/source/blender/compositor/nodes/COM_SocketProxyNode.cpp +++ b/source/blender/compositor/nodes/COM_SocketProxyNode.cpp @@ -72,14 +72,14 @@ void SocketBufferNode::convertToOperations(NodeConverter &converter, const Compo { NodeOutput *output = this->getOutputSocket(0); NodeInput *input = this->getInputSocket(0); - + DataType datatype = output->getDataType(); WriteBufferOperation *writeOperation = new WriteBufferOperation(datatype); ReadBufferOperation *readOperation = new ReadBufferOperation(datatype); readOperation->setMemoryProxy(writeOperation->getMemoryProxy()); converter.addOperation(writeOperation); converter.addOperation(readOperation); - + converter.mapInputSocket(input, writeOperation->getInputSocket(0)); converter.mapOutputSocket(output, readOperation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_SocketProxyNode.h b/source/blender/compositor/nodes/COM_SocketProxyNode.h index 410cbf94842b..ce19a9abd7da 100644 --- a/source/blender/compositor/nodes/COM_SocketProxyNode.h +++ b/source/blender/compositor/nodes/COM_SocketProxyNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SocketProxyNode_h_ -#define _COM_SocketProxyNode_h_ +#ifndef __COM_SOCKETPROXYNODE_H__ +#define __COM_SOCKETPROXYNODE_H__ #include "COM_Node.h" @@ -33,10 +33,10 @@ class SocketProxyNode : public Node { public: SocketProxyNode(bNode *editorNode, bNodeSocket *editorInput, bNodeSocket *editorOutput, bool use_conversion); void convertToOperations(NodeConverter &converter, const CompositorContext &context) const; - + bool getUseConversion() const { return m_use_conversion; } void setUseConversion(bool use_conversion) { m_use_conversion = use_conversion; } - + private: /** If true, the proxy will convert input and output data to/from the proxy socket types. */ bool m_use_conversion; diff --git a/source/blender/compositor/nodes/COM_SplitViewerNode.h b/source/blender/compositor/nodes/COM_SplitViewerNode.h index 674067696eab..c073713f21f2 100644 --- a/source/blender/compositor/nodes/COM_SplitViewerNode.h +++ b/source/blender/compositor/nodes/COM_SplitViewerNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SplitViewerNode_h_ -#define _COM_SplitViewerNode_h_ +#ifndef __COM_SPLITVIEWERNODE_H__ +#define __COM_SPLITVIEWERNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_Stabilize2dNode.cpp b/source/blender/compositor/nodes/COM_Stabilize2dNode.cpp index a575cf65b990..38b8a4663691 100644 --- a/source/blender/compositor/nodes/COM_Stabilize2dNode.cpp +++ b/source/blender/compositor/nodes/COM_Stabilize2dNode.cpp @@ -44,7 +44,7 @@ void Stabilize2dNode::convertToOperations(NodeConverter &converter, const Compos NodeInput *imageInput = this->getInputSocket(0); MovieClip *clip = (MovieClip *)editorNode->id; bool invert = (editorNode->custom2 & CMP_NODEFLAG_STABILIZE_INVERSE) != 0; - + ScaleOperation *scaleOperation = new ScaleOperation(); scaleOperation->setSampler((PixelSampler)editorNode->custom1); RotateOperation *rotateOperation = new RotateOperation(); @@ -85,18 +85,18 @@ void Stabilize2dNode::convertToOperations(NodeConverter &converter, const Compos converter.addOperation(translateOperation); converter.addOperation(rotateOperation); converter.addOperation(psoperation); - + converter.mapInputSocket(imageInput, scaleOperation->getInputSocket(0)); converter.addLink(scaleAttribute->getOutputSocket(), scaleOperation->getInputSocket(1)); converter.addLink(scaleAttribute->getOutputSocket(), scaleOperation->getInputSocket(2)); - + converter.addLink(scaleOperation->getOutputSocket(), rotateOperation->getInputSocket(0)); converter.addLink(angleAttribute->getOutputSocket(), rotateOperation->getInputSocket(1)); converter.addLink(rotateOperation->getOutputSocket(), translateOperation->getInputSocket(0)); converter.addLink(xAttribute->getOutputSocket(), translateOperation->getInputSocket(1)); converter.addLink(yAttribute->getOutputSocket(), translateOperation->getInputSocket(2)); - + converter.addLink(translateOperation->getOutputSocket(), psoperation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(), psoperation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_Stabilize2dNode.h b/source/blender/compositor/nodes/COM_Stabilize2dNode.h index d0b5f6e96f67..2859432fac7e 100644 --- a/source/blender/compositor/nodes/COM_Stabilize2dNode.h +++ b/source/blender/compositor/nodes/COM_Stabilize2dNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_Stabilize2dNode_h_ -#define _COM_Stabilize2dNode_h_ +#ifndef __COM_STABILIZE2DNODE_H__ +#define __COM_STABILIZE2DNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_SunBeamsNode.h b/source/blender/compositor/nodes/COM_SunBeamsNode.h index 4024eb276bcc..425b97061ca8 100644 --- a/source/blender/compositor/nodes/COM_SunBeamsNode.h +++ b/source/blender/compositor/nodes/COM_SunBeamsNode.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_SunBeamsNode_h_ -#define _COM_SunBeamsNode_h_ +#ifndef __COM_SUNBEAMSNODE_H__ +#define __COM_SUNBEAMSNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_SwitchNode.cpp b/source/blender/compositor/nodes/COM_SwitchNode.cpp index e0c12e4dbea7..7e1eaabc8863 100644 --- a/source/blender/compositor/nodes/COM_SwitchNode.cpp +++ b/source/blender/compositor/nodes/COM_SwitchNode.cpp @@ -30,12 +30,12 @@ SwitchNode::SwitchNode(bNode *editorNode) : Node(editorNode) void SwitchNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { bool condition = this->getbNode()->custom1; - + NodeOperationOutput *result; if (!condition) result = converter.addInputProxy(getInputSocket(0), false); else result = converter.addInputProxy(getInputSocket(1), false); - + converter.mapOutputSocket(getOutputSocket(0), result); } diff --git a/source/blender/compositor/nodes/COM_SwitchNode.h b/source/blender/compositor/nodes/COM_SwitchNode.h index 37ba73528f37..5967bbd5dd05 100644 --- a/source/blender/compositor/nodes/COM_SwitchNode.h +++ b/source/blender/compositor/nodes/COM_SwitchNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SwitchNode_h_ -#define _COM_SwitchNode_h_ +#ifndef __COM_SWITCHNODE_H__ +#define __COM_SWITCHNODE_H__ #include "COM_Node.h" #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/nodes/COM_SwitchViewNode.h b/source/blender/compositor/nodes/COM_SwitchViewNode.h index 6ab5145bed52..f41719408807 100644 --- a/source/blender/compositor/nodes/COM_SwitchViewNode.h +++ b/source/blender/compositor/nodes/COM_SwitchViewNode.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_SwitchViewNode_h_ -#define _COM_SwitchViewNode_h_ +#ifndef __COM_SWITCHVIEWNODE_H__ +#define __COM_SWITCHVIEWNODE_H__ #include "COM_Node.h" #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/nodes/COM_TextureNode.cpp b/source/blender/compositor/nodes/COM_TextureNode.cpp index 411dea2925f0..47b32f6e04d8 100644 --- a/source/blender/compositor/nodes/COM_TextureNode.cpp +++ b/source/blender/compositor/nodes/COM_TextureNode.cpp @@ -40,11 +40,11 @@ void TextureNode::convertToOperations(NodeConverter &converter, const Compositor operation->setRenderData(context.getRenderData()); operation->setSceneColorManage(sceneColorManage); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(1), operation->getOutputSocket()); - + converter.addPreview(operation->getOutputSocket()); TextureAlphaOperation *alphaOperation = new TextureAlphaOperation(); @@ -52,7 +52,7 @@ void TextureNode::convertToOperations(NodeConverter &converter, const Compositor alphaOperation->setRenderData(context.getRenderData()); alphaOperation->setSceneColorManage(sceneColorManage); converter.addOperation(alphaOperation); - + converter.mapInputSocket(getInputSocket(0), alphaOperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), alphaOperation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(0), alphaOperation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_TimeNode.cpp b/source/blender/compositor/nodes/COM_TimeNode.cpp index 8450b5212672..883ff72229dc 100644 --- a/source/blender/compositor/nodes/COM_TimeNode.cpp +++ b/source/blender/compositor/nodes/COM_TimeNode.cpp @@ -54,8 +54,8 @@ void TimeNode::convertToOperations(NodeConverter &converter, const CompositorCon curvemapping_initialize((CurveMapping *)node->storage); fac = curvemapping_evaluateF((CurveMapping *)node->storage, 0, fac); - operation->setValue(CLAMPIS(fac, 0.0f, 1.0f)); + operation->setValue(clamp_f(fac, 0.0f, 1.0f)); converter.addOperation(operation); - + converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_TimeNode.h b/source/blender/compositor/nodes/COM_TimeNode.h index 065c55f27809..7ebc6f2cc67f 100644 --- a/source/blender/compositor/nodes/COM_TimeNode.h +++ b/source/blender/compositor/nodes/COM_TimeNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_TimeNode_h_ -#define _COM_TimeNode_h_ +#ifndef __COM_TIMENODE_H__ +#define __COM_TIMENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_TonemapNode.cpp b/source/blender/compositor/nodes/COM_TonemapNode.cpp index 1ecc42a0a275..a01be6acb7b0 100644 --- a/source/blender/compositor/nodes/COM_TonemapNode.cpp +++ b/source/blender/compositor/nodes/COM_TonemapNode.cpp @@ -32,11 +32,11 @@ TonemapNode::TonemapNode(bNode *editorNode) : Node(editorNode) void TonemapNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const { NodeTonemap *data = (NodeTonemap *)this->getbNode()->storage; - + TonemapOperation *operation = data->type == 1 ? new PhotoreceptorTonemapOperation() : new TonemapOperation(); operation->setData(data); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket(0)); } diff --git a/source/blender/compositor/nodes/COM_TonemapNode.h b/source/blender/compositor/nodes/COM_TonemapNode.h index e504db4c0149..13e51acf3fe0 100644 --- a/source/blender/compositor/nodes/COM_TonemapNode.h +++ b/source/blender/compositor/nodes/COM_TonemapNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_TonemapNode_h_ -#define _COM_TonemapNode_h_ +#ifndef __COM_TONEMAPNODE_H__ +#define __COM_TONEMAPNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_TrackPositionNode.cpp b/source/blender/compositor/nodes/COM_TrackPositionNode.cpp index 490f72b4aa1f..cddb35574980 100644 --- a/source/blender/compositor/nodes/COM_TrackPositionNode.cpp +++ b/source/blender/compositor/nodes/COM_TrackPositionNode.cpp @@ -63,7 +63,7 @@ void TrackPositionNode::convertToOperations(NodeConverter &converter, const Comp bNode *editorNode = this->getbNode(); MovieClip *clip = (MovieClip *) editorNode->id; NodeTrackPosData *trackpos_data = (NodeTrackPosData *) editorNode->storage; - + NodeOutput *outputX = this->getOutputSocket(0); NodeOutput *outputY = this->getOutputSocket(1); NodeOutput *outputSpeed = this->getOutputSocket(2); diff --git a/source/blender/compositor/nodes/COM_TransformNode.cpp b/source/blender/compositor/nodes/COM_TransformNode.cpp index 5b772d1ce561..288f394a10f5 100644 --- a/source/blender/compositor/nodes/COM_TransformNode.cpp +++ b/source/blender/compositor/nodes/COM_TransformNode.cpp @@ -40,32 +40,32 @@ void TransformNode::convertToOperations(NodeConverter &converter, const Composit NodeInput *yInput = this->getInputSocket(2); NodeInput *angleInput = this->getInputSocket(3); NodeInput *scaleInput = this->getInputSocket(4); - + ScaleOperation *scaleOperation = new ScaleOperation(); converter.addOperation(scaleOperation); - + RotateOperation *rotateOperation = new RotateOperation(); rotateOperation->setDoDegree2RadConversion(false); converter.addOperation(rotateOperation); - + TranslateOperation *translateOperation = new TranslateOperation(); converter.addOperation(translateOperation); - + SetSamplerOperation *sampler = new SetSamplerOperation(); sampler->setSampler((PixelSampler)this->getbNode()->custom1); converter.addOperation(sampler); - + converter.mapInputSocket(imageInput, sampler->getInputSocket(0)); converter.addLink(sampler->getOutputSocket(), scaleOperation->getInputSocket(0)); converter.mapInputSocket(scaleInput, scaleOperation->getInputSocket(1)); converter.mapInputSocket(scaleInput, scaleOperation->getInputSocket(2)); // xscale = yscale - + converter.addLink(scaleOperation->getOutputSocket(), rotateOperation->getInputSocket(0)); converter.mapInputSocket(angleInput, rotateOperation->getInputSocket(1)); - + converter.addLink(rotateOperation->getOutputSocket(), translateOperation->getInputSocket(0)); converter.mapInputSocket(xInput, translateOperation->getInputSocket(1)); converter.mapInputSocket(yInput, translateOperation->getInputSocket(2)); - + converter.mapOutputSocket(getOutputSocket(), translateOperation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_TranslateNode.cpp b/source/blender/compositor/nodes/COM_TranslateNode.cpp index 0e658e099311..78d1bfc3b28a 100644 --- a/source/blender/compositor/nodes/COM_TranslateNode.cpp +++ b/source/blender/compositor/nodes/COM_TranslateNode.cpp @@ -36,32 +36,32 @@ void TranslateNode::convertToOperations(NodeConverter &converter, const Composit { bNode *bnode = this->getbNode(); NodeTranslateData *data = (NodeTranslateData *)bnode->storage; - + NodeInput *inputSocket = this->getInputSocket(0); NodeInput *inputXSocket = this->getInputSocket(1); NodeInput *inputYSocket = this->getInputSocket(2); NodeOutput *outputSocket = this->getOutputSocket(0); - + TranslateOperation *operation = new TranslateOperation(); if (data->relative) { const RenderData *rd = context.getRenderData(); float fx = rd->xsch * rd->size / 100.0f; float fy = rd->ysch * rd->size / 100.0f; - + operation->setFactorXY(fx, fy); } - + converter.addOperation(operation); converter.mapInputSocket(inputXSocket, operation->getInputSocket(1)); converter.mapInputSocket(inputYSocket, operation->getInputSocket(2)); converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0)); - + if (data->wrap_axis) { WriteBufferOperation *writeOperation = new WriteBufferOperation(COM_DT_COLOR); WrapOperation *wrapOperation = new WrapOperation(COM_DT_COLOR); wrapOperation->setMemoryProxy(writeOperation->getMemoryProxy()); wrapOperation->setWrapping(data->wrap_axis); - + converter.addOperation(writeOperation); converter.addOperation(wrapOperation); converter.mapInputSocket(inputSocket, writeOperation->getInputSocket(0)); @@ -71,4 +71,3 @@ void TranslateNode::convertToOperations(NodeConverter &converter, const Composit converter.mapInputSocket(inputSocket, operation->getInputSocket(0)); } } - diff --git a/source/blender/compositor/nodes/COM_TranslateNode.h b/source/blender/compositor/nodes/COM_TranslateNode.h index 484f28b1089f..51d969dbb046 100644 --- a/source/blender/compositor/nodes/COM_TranslateNode.h +++ b/source/blender/compositor/nodes/COM_TranslateNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_TranslateNode_h_ -#define _COM_TranslateNode_h_ +#ifndef __COM_TRANSLATENODE_H__ +#define __COM_TRANSLATENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ValueNode.cpp b/source/blender/compositor/nodes/COM_ValueNode.cpp index f2eef1888618..b7484eb4ed64 100644 --- a/source/blender/compositor/nodes/COM_ValueNode.cpp +++ b/source/blender/compositor/nodes/COM_ValueNode.cpp @@ -35,6 +35,6 @@ void ValueNode::convertToOperations(NodeConverter &converter, const CompositorCo NodeOutput *output = this->getOutputSocket(0); operation->setValue(output->getEditorValueFloat()); converter.addOperation(operation); - + converter.mapOutputSocket(output, operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_ValueNode.h b/source/blender/compositor/nodes/COM_ValueNode.h index b88c502be7f9..e1b13c2d8aa0 100644 --- a/source/blender/compositor/nodes/COM_ValueNode.h +++ b/source/blender/compositor/nodes/COM_ValueNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ValueNode_h_ -#define _COM_ValueNode_h_ +#ifndef __COM_VALUENODE_H__ +#define __COM_VALUENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_VectorBlurNode.cpp b/source/blender/compositor/nodes/COM_VectorBlurNode.cpp index 5cfd83360c73..5a6b49c9bd1b 100644 --- a/source/blender/compositor/nodes/COM_VectorBlurNode.cpp +++ b/source/blender/compositor/nodes/COM_VectorBlurNode.cpp @@ -33,12 +33,12 @@ void VectorBlurNode::convertToOperations(NodeConverter &converter, const Composi { bNode *node = this->getbNode(); NodeBlurData *vectorBlurSettings = (NodeBlurData *)node->storage; - + VectorBlurOperation *operation = new VectorBlurOperation(); operation->setVectorBlurSettings(vectorBlurSettings); operation->setQuality(context.getQuality()); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(2)); diff --git a/source/blender/compositor/nodes/COM_VectorBlurNode.h b/source/blender/compositor/nodes/COM_VectorBlurNode.h index 0e7ad015cc5a..5f741ff0852e 100644 --- a/source/blender/compositor/nodes/COM_VectorBlurNode.h +++ b/source/blender/compositor/nodes/COM_VectorBlurNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_VectorBlurNode_h_ -#define _COM_VectorBlurNode_h_ +#ifndef __COM_VECTORBLURNODE_H__ +#define __COM_VECTORBLURNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_VectorCurveNode.cpp b/source/blender/compositor/nodes/COM_VectorCurveNode.cpp index db7e1597bf3c..dc4b2f66a0a4 100644 --- a/source/blender/compositor/nodes/COM_VectorCurveNode.cpp +++ b/source/blender/compositor/nodes/COM_VectorCurveNode.cpp @@ -34,7 +34,7 @@ void VectorCurveNode::convertToOperations(NodeConverter &converter, const Compos VectorCurveOperation *operation = new VectorCurveOperation(); operation->setCurveMapping((CurveMapping *)this->getbNode()->storage); converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); } diff --git a/source/blender/compositor/nodes/COM_VectorCurveNode.h b/source/blender/compositor/nodes/COM_VectorCurveNode.h index 8cf76cff206e..d8a2121a7c61 100644 --- a/source/blender/compositor/nodes/COM_VectorCurveNode.h +++ b/source/blender/compositor/nodes/COM_VectorCurveNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_VectorCurveNode_h_ -#define _COM_VectorCurveNode_h_ +#ifndef __COM_VECTORCURVENODE_H__ +#define __COM_VECTORCURVENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp b/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp index b7e4c9e8a1df..134ab5628ec1 100644 --- a/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp +++ b/source/blender/compositor/nodes/COM_ViewLevelsNode.cpp @@ -36,12 +36,12 @@ void ViewLevelsNode::convertToOperations(NodeConverter &converter, const Composi NodeInput *input = this->getInputSocket(0); if (input->isLinked()) { // add preview to inputSocket; - + /* calculate mean operation */ { CalculateMeanOperation *operation = new CalculateMeanOperation(); operation->setSetting(this->getbNode()->custom1); - + converter.addOperation(operation); converter.mapInputSocket(input, operation->getInputSocket(0)); converter.mapOutputSocket(this->getOutputSocket(0), operation->getOutputSocket()); @@ -51,7 +51,7 @@ void ViewLevelsNode::convertToOperations(NodeConverter &converter, const Composi { CalculateStandardDeviationOperation *operation = new CalculateStandardDeviationOperation(); operation->setSetting(this->getbNode()->custom1); - + converter.addOperation(operation); converter.mapInputSocket(input, operation->getInputSocket(0)); converter.mapOutputSocket(this->getOutputSocket(1), operation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_ViewLevelsNode.h b/source/blender/compositor/nodes/COM_ViewLevelsNode.h index c56c6b0cef1e..7fca060389a4 100644 --- a/source/blender/compositor/nodes/COM_ViewLevelsNode.h +++ b/source/blender/compositor/nodes/COM_ViewLevelsNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ViewLevelsNode_h_ -#define _COM_ViewLevelsNode_h_ +#ifndef __COM_VIEWLEVELSNODE_H__ +#define __COM_VIEWLEVELSNODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/nodes/COM_ViewerNode.h b/source/blender/compositor/nodes/COM_ViewerNode.h index 1f2cb02dcd69..67d6387a17c3 100644 --- a/source/blender/compositor/nodes/COM_ViewerNode.h +++ b/source/blender/compositor/nodes/COM_ViewerNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ViewerNode_h_ -#define _COM_ViewerNode_h_ +#ifndef __COM_VIEWERNODE_H__ +#define __COM_VIEWERNODE_H__ #include "COM_Node.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/nodes/COM_ZCombineNode.cpp b/source/blender/compositor/nodes/COM_ZCombineNode.cpp index c77bd0318242..a5d42bb0333d 100644 --- a/source/blender/compositor/nodes/COM_ZCombineNode.cpp +++ b/source/blender/compositor/nodes/COM_ZCombineNode.cpp @@ -43,16 +43,16 @@ void ZCombineNode::convertToOperations(NodeConverter &converter, const Composito operation = new ZCombineOperation(); } converter.addOperation(operation); - + converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(1), operation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), operation->getInputSocket(2)); converter.mapInputSocket(getInputSocket(3), operation->getInputSocket(3)); converter.mapOutputSocket(getOutputSocket(0), operation->getOutputSocket()); - + MathMinimumOperation *zoperation = new MathMinimumOperation(); converter.addOperation(zoperation); - + converter.mapInputSocket(getInputSocket(1), zoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(3), zoperation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(1), zoperation->getOutputSocket()); @@ -65,14 +65,14 @@ void ZCombineNode::convertToOperations(NodeConverter &converter, const Composito if (this->getbNode()->custom1) { maskoperation = new MathGreaterThanOperation(); converter.addOperation(maskoperation); - + converter.mapInputSocket(getInputSocket(1), maskoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(3), maskoperation->getInputSocket(1)); } else { maskoperation = new MathLessThanOperation(); converter.addOperation(maskoperation); - + converter.mapInputSocket(getInputSocket(1), maskoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(3), maskoperation->getInputSocket(1)); } @@ -80,13 +80,13 @@ void ZCombineNode::convertToOperations(NodeConverter &converter, const Composito // step 2 anti alias mask bit of an expensive operation, but does the trick AntiAliasOperation *antialiasoperation = new AntiAliasOperation(); converter.addOperation(antialiasoperation); - + converter.addLink(maskoperation->getOutputSocket(), antialiasoperation->getInputSocket(0)); // use mask to blend between the input colors. ZCombineMaskOperation *zcombineoperation = this->getbNode()->custom1 ? new ZCombineMaskAlphaOperation() : new ZCombineMaskOperation(); converter.addOperation(zcombineoperation); - + converter.addLink(antialiasoperation->getOutputSocket(), zcombineoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(0), zcombineoperation->getInputSocket(1)); converter.mapInputSocket(getInputSocket(2), zcombineoperation->getInputSocket(2)); @@ -94,7 +94,7 @@ void ZCombineNode::convertToOperations(NodeConverter &converter, const Composito MathMinimumOperation *zoperation = new MathMinimumOperation(); converter.addOperation(zoperation); - + converter.mapInputSocket(getInputSocket(1), zoperation->getInputSocket(0)); converter.mapInputSocket(getInputSocket(3), zoperation->getInputSocket(1)); converter.mapOutputSocket(getOutputSocket(1), zoperation->getOutputSocket()); diff --git a/source/blender/compositor/nodes/COM_ZCombineNode.h b/source/blender/compositor/nodes/COM_ZCombineNode.h index 9a438d6dde30..8e166ddf1682 100644 --- a/source/blender/compositor/nodes/COM_ZCombineNode.h +++ b/source/blender/compositor/nodes/COM_ZCombineNode.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ZCombineNode_h_ -#define _COM_ZCombineNode_h_ +#ifndef __COM_ZCOMBINENODE_H__ +#define __COM_ZCOMBINENODE_H__ #include "COM_Node.h" diff --git a/source/blender/compositor/operations/COM_AlphaOverKeyOperation.cpp b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.cpp index 928525f25949..e6ae9b5fc8ba 100644 --- a/source/blender/compositor/operations/COM_AlphaOverKeyOperation.cpp +++ b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.cpp @@ -32,11 +32,11 @@ void AlphaOverKeyOperation::executePixelSampled(float output[4], float x, float float inputColor1[4]; float inputOverColor[4]; float value[4]; - + this->m_inputValueOperation->readSampled(value, x, y, sampler); this->m_inputColor1Operation->readSampled(inputColor1, x, y, sampler); this->m_inputColor2Operation->readSampled(inputOverColor, x, y, sampler); - + if (inputOverColor[3] <= 0.0f) { copy_v4_v4(output, inputColor1); } @@ -46,7 +46,7 @@ void AlphaOverKeyOperation::executePixelSampled(float output[4], float x, float else { float premul = value[0] * inputOverColor[3]; float mul = 1.0f - premul; - + output[0] = (mul * inputColor1[0]) + premul * inputOverColor[0]; output[1] = (mul * inputColor1[1]) + premul * inputOverColor[1]; output[2] = (mul * inputColor1[2]) + premul * inputOverColor[2]; diff --git a/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h index 8e4a0c932028..569c18888d83 100644 --- a/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverKeyOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_AlphaOverKeyOperation_h -#define _COM_AlphaOverKeyOperation_h +#ifndef __COM_ALPHAOVERKEYOPERATION_H__ +#define __COM_ALPHAOVERKEYOPERATION_H__ #include "COM_MixOperation.h" @@ -35,7 +35,7 @@ class AlphaOverKeyOperation : public MixBaseOperation { * Default constructor */ AlphaOverKeyOperation(); - + /** * the inner loop of this program */ diff --git a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.cpp b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.cpp index 990ec5f5370d..119ff3f98e9b 100644 --- a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.cpp +++ b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.cpp @@ -32,11 +32,11 @@ void AlphaOverMixedOperation::executePixelSampled(float output[4], float x, floa float inputColor1[4]; float inputOverColor[4]; float value[4]; - + this->m_inputValueOperation->readSampled(value, x, y, sampler); this->m_inputColor1Operation->readSampled(inputColor1, x, y, sampler); this->m_inputColor2Operation->readSampled(inputOverColor, x, y, sampler); - + if (inputOverColor[3] <= 0.0f) { copy_v4_v4(output, inputColor1); } @@ -54,4 +54,3 @@ void AlphaOverMixedOperation::executePixelSampled(float output[4], float x, floa output[3] = (mul * inputColor1[3]) + value[0] * inputOverColor[3]; } } - diff --git a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h index 8c97b0657926..a5174f0839a3 100644 --- a/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverMixedOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_AlphaOverMixedOperation_h_ -#define _COM_AlphaOverMixedOperation_h_ +#ifndef __COM_ALPHAOVERMIXEDOPERATION_H__ +#define __COM_ALPHAOVERMIXEDOPERATION_H__ #include "COM_MixOperation.h" @@ -37,12 +37,12 @@ class AlphaOverMixedOperation : public MixBaseOperation { * Default constructor */ AlphaOverMixedOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void setX(float x) { this->m_x = x; } }; #endif diff --git a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.cpp b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.cpp index 1f397e8a126b..22a92c8e65b0 100644 --- a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.cpp +++ b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.cpp @@ -32,11 +32,11 @@ void AlphaOverPremultiplyOperation::executePixelSampled(float output[4], float x float inputColor1[4]; float inputOverColor[4]; float value[4]; - + this->m_inputValueOperation->readSampled(value, x, y, sampler); this->m_inputColor1Operation->readSampled(inputColor1, x, y, sampler); this->m_inputColor2Operation->readSampled(inputOverColor, x, y, sampler); - + /* Zero alpha values should still permit an add of RGB data */ if (inputOverColor[3] < 0.0f) { copy_v4_v4(output, inputColor1); @@ -46,11 +46,10 @@ void AlphaOverPremultiplyOperation::executePixelSampled(float output[4], float x } else { float mul = 1.0f - value[0] * inputOverColor[3]; - + output[0] = (mul * inputColor1[0]) + value[0] * inputOverColor[0]; output[1] = (mul * inputColor1[1]) + value[0] * inputOverColor[1]; output[2] = (mul * inputColor1[2]) + value[0] * inputOverColor[2]; output[3] = (mul * inputColor1[3]) + value[0] * inputOverColor[3]; } } - diff --git a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h index 1dad453ca4e6..e52971222ab0 100644 --- a/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h +++ b/source/blender/compositor/operations/COM_AlphaOverPremultiplyOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_AlphaOverPremultiplyOperation_h -#define _COM_AlphaOverPremultiplyOperation_h +#ifndef __COM_ALPHAOVERPREMULTIPLYOPERATION_H__ +#define __COM_ALPHAOVERPREMULTIPLYOPERATION_H__ #include "COM_MixOperation.h" @@ -35,7 +35,7 @@ class AlphaOverPremultiplyOperation : public MixBaseOperation { * Default constructor */ AlphaOverPremultiplyOperation(); - + /** * the inner loop of this program */ diff --git a/source/blender/compositor/operations/COM_AntiAliasOperation.h b/source/blender/compositor/operations/COM_AntiAliasOperation.h index 13632a810842..34243cd34b61 100644 --- a/source/blender/compositor/operations/COM_AntiAliasOperation.h +++ b/source/blender/compositor/operations/COM_AntiAliasOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_AntiAliasOperation_h -#define _COM_AntiAliasOperation_h +#ifndef __COM_ANTIALIASOPERATION_H__ +#define __COM_ANTIALIASOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" @@ -38,19 +38,19 @@ class AntiAliasOperation : public NodeOperation { SocketReader *m_valueReader; public: AntiAliasOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_BilateralBlurOperation.cpp b/source/blender/compositor/operations/COM_BilateralBlurOperation.cpp index 4a6da3092a2a..506c2181ee94 100644 --- a/source/blender/compositor/operations/COM_BilateralBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_BilateralBlurOperation.cpp @@ -84,7 +84,7 @@ void BilateralBlurOperation::executePixel(float output[4], int x, int y, void *d } } } - + if (blurDivider > 0.0f) { mul_v4_v4fl(output, blurColor, 1.0f / blurDivider); } diff --git a/source/blender/compositor/operations/COM_BilateralBlurOperation.h b/source/blender/compositor/operations/COM_BilateralBlurOperation.h index b013e357b9c6..70f291d5e1c8 100644 --- a/source/blender/compositor/operations/COM_BilateralBlurOperation.h +++ b/source/blender/compositor/operations/COM_BilateralBlurOperation.h @@ -39,19 +39,19 @@ class BilateralBlurOperation : public NodeOperation, public QualityStepHelper { * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); - + void setData(NodeBilateralBlurData *data) { this->m_data = data; } }; #endif diff --git a/source/blender/compositor/operations/COM_BlurBaseOperation.h b/source/blender/compositor/operations/COM_BlurBaseOperation.h index 9fd7c0177152..8b3cfcafcef9 100644 --- a/source/blender/compositor/operations/COM_BlurBaseOperation.h +++ b/source/blender/compositor/operations/COM_BlurBaseOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BlurBaseOperation_h -#define _COM_BlurBaseOperation_h +#ifndef __COM_BLURBASEOPERATION_H__ +#define __COM_BLURBASEOPERATION_H__ #include "COM_NodeOperation.h" #include "COM_QualityStepHelper.h" @@ -62,12 +62,12 @@ class BlurBaseOperation : public NodeOperation, public QualityStepHelper { * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setData(const NodeBlurData *data); void setSize(float size) { this->m_size = size; this->m_sizeavailable = true; } diff --git a/source/blender/compositor/operations/COM_BokehBlurOperation.cpp b/source/blender/compositor/operations/COM_BokehBlurOperation.cpp index c413f45cbaa4..2476ab3b5919 100644 --- a/source/blender/compositor/operations/COM_BokehBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_BokehBlurOperation.cpp @@ -194,8 +194,8 @@ bool BokehBlurOperation::determineDependingAreaOfInterest(rcti *input, ReadBuffe } void BokehBlurOperation::executeOpenCL(OpenCLDevice *device, - MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, - MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list * /*clKernelsToCleanUp*/) { cl_kernel kernel = device->COM_clCreateKernel("bokehBlurKernel", NULL); @@ -205,7 +205,7 @@ void BokehBlurOperation::executeOpenCL(OpenCLDevice *device, const float max_dim = max(this->getWidth(), this->getHeight()); cl_int radius = this->m_size * max_dim / 100.0f; cl_int step = this->getStep(); - + device->COM_clAttachMemoryBufferToKernelParameter(kernel, 0, -1, clMemToCleanUp, inputMemoryBuffers, this->m_inputBoundingBoxReader); device->COM_clAttachMemoryBufferToKernelParameter(kernel, 1, 4, clMemToCleanUp, inputMemoryBuffers, this->m_inputProgram); device->COM_clAttachMemoryBufferToKernelParameter(kernel, 2, -1, clMemToCleanUp, inputMemoryBuffers, this->m_inputBokehProgram); @@ -214,7 +214,7 @@ void BokehBlurOperation::executeOpenCL(OpenCLDevice *device, clSetKernelArg(kernel, 6, sizeof(cl_int), &radius); clSetKernelArg(kernel, 7, sizeof(cl_int), &step); device->COM_clAttachSizeToKernelParameter(kernel, 8, this); - + device->COM_clEnqueueRange(kernel, outputMemoryBuffer, 9, this); } diff --git a/source/blender/compositor/operations/COM_BokehBlurOperation.h b/source/blender/compositor/operations/COM_BokehBlurOperation.h index 3bfaae6617e8..f1540835eafc 100644 --- a/source/blender/compositor/operations/COM_BokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_BokehBlurOperation.h @@ -46,21 +46,21 @@ class BokehBlurOperation : public NodeOperation, public QualityStepHelper { * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void setSize(float size) { this->m_size = size; this->m_sizeavailable = true; } - + void executeOpenCL(OpenCLDevice *device, MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, diff --git a/source/blender/compositor/operations/COM_BokehImageOperation.h b/source/blender/compositor/operations/COM_BokehImageOperation.h index a2dd3b6ddb70..c6ca7054352b 100644 --- a/source/blender/compositor/operations/COM_BokehImageOperation.h +++ b/source/blender/compositor/operations/COM_BokehImageOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BokehImageOperation_h -#define _COM_BokehImageOperation_h +#ifndef __COM_BOKEHIMAGEOPERATION_H__ +#define __COM_BOKEHIMAGEOPERATION_H__ #include "COM_NodeOperation.h" /** @@ -61,27 +61,27 @@ class BokehImageOperation : public NodeOperation { * @brief precalced center of the image */ float m_center[2]; - + /** * @brief 1.0-rounding */ float m_inverseRounding; - + /** * @brief distance of a full circle lens */ float m_circularDistance; - + /** * @brief radius when the first flap starts */ float m_flapRad; - + /** * @brief radians of a single flap */ float m_flapRadAdd; - + /** * @brief should the m_data field by deleted when this operation is finished */ @@ -95,7 +95,7 @@ class BokehImageOperation : public NodeOperation { * @param distance the lens distance is used to simulate lens shifts */ void detemineStartPointOfFlap(float r[2], int flapNumber, float distance); - + /** * @brief Determine if a coordinate is inside the bokeh image * @@ -112,17 +112,17 @@ class BokehImageOperation : public NodeOperation { * @brief the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * @brief Initialize the execution */ void initExecution(); - + /** * @brief Deinitialize the execution */ void deinitExecution(); - + /** * @brief determine the resolution of this operation. currently fixed at [COM_BLUR_BOKEH_PIXELS, COM_BLUR_BOKEH_PIXELS] * @param resolution @@ -135,7 +135,7 @@ class BokehImageOperation : public NodeOperation { * @param data */ void setData(NodeBokehImage *data) { this->m_data = data; } - + /** * @brief deleteDataOnFinish * diff --git a/source/blender/compositor/operations/COM_BoxMaskOperation.cpp b/source/blender/compositor/operations/COM_BoxMaskOperation.cpp index e19e5bf031c0..d4fe976cf26d 100644 --- a/source/blender/compositor/operations/COM_BoxMaskOperation.cpp +++ b/source/blender/compositor/operations/COM_BoxMaskOperation.cpp @@ -48,25 +48,25 @@ void BoxMaskOperation::executePixelSampled(float output[4], float x, float y, Pi { float inputMask[4]; float inputValue[4]; - + float rx = x / this->getWidth(); float ry = y / this->getHeight(); - + const float dy = (ry - this->m_data->y) / this->m_aspectRatio; const float dx = rx - this->m_data->x; rx = this->m_data->x + (this->m_cosine * dx + this->m_sine * dy); ry = this->m_data->y + (-this->m_sine * dx + this->m_cosine * dy); - + this->m_inputMask->readSampled(inputMask, x, y, sampler); this->m_inputValue->readSampled(inputValue, x, y, sampler); - + float halfHeight = this->m_data->height / 2.0f; float halfWidth = this->m_data->width / 2.0f; bool inside = (rx > this->m_data->x - halfWidth && rx < this->m_data->x + halfWidth && ry > this->m_data->y - halfHeight && ry < this->m_data->y + halfHeight); - + switch (this->m_maskType) { case CMP_NODE_MASKTYPE_ADD: if (inside) { diff --git a/source/blender/compositor/operations/COM_BoxMaskOperation.h b/source/blender/compositor/operations/COM_BoxMaskOperation.h index c8b2ba144671..399b7dd393bb 100644 --- a/source/blender/compositor/operations/COM_BoxMaskOperation.h +++ b/source/blender/compositor/operations/COM_BoxMaskOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BoxMaskOperation_h -#define _COM_BoxMaskOperation_h +#ifndef __COM_BOXMASKOPERATION_H__ +#define __COM_BOXMASKOPERATION_H__ #include "COM_NodeOperation.h" @@ -32,31 +32,31 @@ class BoxMaskOperation : public NodeOperation { */ SocketReader *m_inputMask; SocketReader *m_inputValue; - + float m_sine; float m_cosine; float m_aspectRatio; int m_maskType; - + NodeBoxMask *m_data; public: BoxMaskOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setData(NodeBoxMask *data) { this->m_data = data; } void setMaskType(int maskType) { this->m_maskType = maskType; } diff --git a/source/blender/compositor/operations/COM_BrightnessOperation.cpp b/source/blender/compositor/operations/COM_BrightnessOperation.cpp index 099113dbf479..a959bd0a5aa6 100644 --- a/source/blender/compositor/operations/COM_BrightnessOperation.cpp +++ b/source/blender/compositor/operations/COM_BrightnessOperation.cpp @@ -89,4 +89,3 @@ void BrightnessOperation::deinitExecution() this->m_inputBrightnessProgram = NULL; this->m_inputContrastProgram = NULL; } - diff --git a/source/blender/compositor/operations/COM_BrightnessOperation.h b/source/blender/compositor/operations/COM_BrightnessOperation.h index 0b7656c53640..1ebccf761a7a 100644 --- a/source/blender/compositor/operations/COM_BrightnessOperation.h +++ b/source/blender/compositor/operations/COM_BrightnessOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_BrightnessOperation_h -#define _COM_BrightnessOperation_h +#ifndef __COM_BRIGHTNESSOPERATION_H__ +#define __COM_BRIGHTNESSOPERATION_H__ #include "COM_NodeOperation.h" @@ -38,17 +38,17 @@ class BrightnessOperation : public NodeOperation { public: BrightnessOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp b/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp index 0fa8b5fa5d2f..be6d2b40d7e6 100644 --- a/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp +++ b/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp @@ -96,7 +96,7 @@ void CalculateMeanOperation::calculateMean(MemoryBuffer *tile) for (int i = 0, offset = 0; i < size; i++, offset += 4) { if (buffer[offset + 3] > 0) { pixels++; - + switch (this->m_setting) { case 1: { diff --git a/source/blender/compositor/operations/COM_CalculateMeanOperation.h b/source/blender/compositor/operations/COM_CalculateMeanOperation.h index 4fa89290c825..1872cb738b20 100644 --- a/source/blender/compositor/operations/COM_CalculateMeanOperation.h +++ b/source/blender/compositor/operations/COM_CalculateMeanOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CalculateMeanOperation_h -#define _COM_CalculateMeanOperation_h +#ifndef __COM_CALCULATEMEANOPERATION_H__ +#define __COM_CALCULATEMEANOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" @@ -35,34 +35,34 @@ class CalculateMeanOperation : public NodeOperation { * @brief Cached reference to the reader */ SocketReader *m_imageReader; - + bool m_iscalculated; float m_result; int m_setting; public: CalculateMeanOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void setSetting(int setting) { this->m_setting = setting; } - + protected: void calculateMean(MemoryBuffer *tile); }; diff --git a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp index ff4857b7b0f7..28012cdfabf0 100644 --- a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp +++ b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp @@ -55,7 +55,7 @@ void *CalculateStandardDeviationOperation::initializeTileData(rcti *rect) for (int i = 0, offset = 0; i < size; i++, offset += 4) { if (buffer[offset + 3] > 0) { pixels++; - + switch (this->m_setting) { case 1: /* rgb combined */ { diff --git a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.h b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.h index dfeaa7297a80..7089e40b210b 100644 --- a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.h +++ b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CalculateStandardDeviationOperation_h -#define _COM_CalculateStandardDeviationOperation_h +#ifndef __COM_CALCULATESTANDARDDEVIATIONOPERATION_H__ +#define __COM_CALCULATESTANDARDDEVIATIONOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_CalculateMeanOperation.h" diff --git a/source/blender/compositor/operations/COM_ChangeHSVOperation.cpp b/source/blender/compositor/operations/COM_ChangeHSVOperation.cpp index a02c1b030060..cbd871132761 100644 --- a/source/blender/compositor/operations/COM_ChangeHSVOperation.cpp +++ b/source/blender/compositor/operations/COM_ChangeHSVOperation.cpp @@ -52,12 +52,12 @@ void ChangeHSVOperation::executePixelSampled(float output[4], float x, float y, { float inputColor1[4]; float hue[4], saturation[4], value[4]; - + this->m_inputOperation->readSampled(inputColor1, x, y, sampler); this->m_hueOperation->readSampled(hue, x, y, sampler); this->m_saturationOperation->readSampled(saturation, x, y, sampler); this->m_valueOperation->readSampled(value, x, y, sampler); - + output[0] = inputColor1[0] + (hue[0] - 0.5f); if (output[0] > 1.0f) output[0] -= 1.0f; else if (output[0] < 0.0f) output[0] += 1.0f; @@ -65,4 +65,3 @@ void ChangeHSVOperation::executePixelSampled(float output[4], float x, float y, output[2] = inputColor1[2] * value[0]; output[3] = inputColor1[3]; } - diff --git a/source/blender/compositor/operations/COM_ChangeHSVOperation.h b/source/blender/compositor/operations/COM_ChangeHSVOperation.h index e6f45c5ad36d..16c4a0cca07a 100644 --- a/source/blender/compositor/operations/COM_ChangeHSVOperation.h +++ b/source/blender/compositor/operations/COM_ChangeHSVOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ChangeHSVOperation_h -#define _COM_ChangeHSVOperation_h +#ifndef __COM_CHANGEHSVOPERATION_H__ +#define __COM_CHANGEHSVOPERATION_H__ #include "COM_MixOperation.h" @@ -41,10 +41,10 @@ class ChangeHSVOperation : public NodeOperation { * Default constructor */ ChangeHSVOperation(); - + void initExecution(); void deinitExecution(); - + /** * the inner loop of this program */ diff --git a/source/blender/compositor/operations/COM_ChannelMatteOperation.cpp b/source/blender/compositor/operations/COM_ChannelMatteOperation.cpp index 3faffc1e3ff9..ec59a27e724a 100644 --- a/source/blender/compositor/operations/COM_ChannelMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_ChannelMatteOperation.cpp @@ -101,10 +101,10 @@ void ChannelMatteOperation::executePixelSampled(float output[4], float x, float /* matte operation */ alpha = inColor[this->m_ids[0]] - max(inColor[this->m_ids[1]], inColor[this->m_ids[2]]); - + /* flip because 0.0 is transparent, not 1.0 */ alpha = 1.0f - alpha; - + /* test range */ if (alpha > limit_max) { alpha = inColor[3]; /*whatever it was prior */ @@ -119,8 +119,7 @@ void ChannelMatteOperation::executePixelSampled(float output[4], float x, float /* store matte(alpha) value in [0] to go with * COM_SetAlphaOperation and the Value output */ - + /* don't make something that was more transparent less transparent */ output[0] = min(alpha, inColor[3]); } - diff --git a/source/blender/compositor/operations/COM_ChannelMatteOperation.h b/source/blender/compositor/operations/COM_ChannelMatteOperation.h index 58b467e78928..46ef78094928 100644 --- a/source/blender/compositor/operations/COM_ChannelMatteOperation.h +++ b/source/blender/compositor/operations/COM_ChannelMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ChannelMatteOperation_h -#define _COM_ChannelMatteOperation_h +#ifndef __COM_CHANNELMATTEOPERATION_H__ +#define __COM_CHANNELMATTEOPERATION_H__ #include "COM_MixOperation.h" diff --git a/source/blender/compositor/operations/COM_ChromaMatteOperation.cpp b/source/blender/compositor/operations/COM_ChromaMatteOperation.cpp index bc6389c5bbd6..6696a6add6d8 100644 --- a/source/blender/compositor/operations/COM_ChromaMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_ChromaMatteOperation.cpp @@ -108,4 +108,3 @@ void ChromaMatteOperation::executePixelSampled(float output[4], float x, float y output[0] = inImage[3]; /* make pixel just as transparent as it was before */ } } - diff --git a/source/blender/compositor/operations/COM_ChromaMatteOperation.h b/source/blender/compositor/operations/COM_ChromaMatteOperation.h index a68790838c03..ba7f207b1c63 100644 --- a/source/blender/compositor/operations/COM_ChromaMatteOperation.h +++ b/source/blender/compositor/operations/COM_ChromaMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ChromaMatteOperation_h -#define _COM_ChromaMatteOperation_h +#ifndef __COM_CHROMAMATTEOPERATION_H__ +#define __COM_CHROMAMATTEOPERATION_H__ #include "COM_MixOperation.h" diff --git a/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.cpp b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.cpp index 23390bd337d0..806772417a4b 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.cpp @@ -53,14 +53,14 @@ void ColorBalanceASCCDLOperation::executePixelSampled(float output[4], float x, { float inputColor[4]; float value[4]; - + this->m_inputValueOperation->readSampled(value, x, y, sampler); this->m_inputColorOperation->readSampled(inputColor, x, y, sampler); - + float fac = value[0]; fac = min(1.0f, fac); const float mfac = 1.0f - fac; - + output[0] = mfac * inputColor[0] + fac * colorbalance_cdl(inputColor[0], this->m_offset[0], this->m_power[0], this->m_slope[0]); output[1] = mfac * inputColor[1] + fac * colorbalance_cdl(inputColor[1], this->m_offset[1], this->m_power[1], this->m_slope[1]); output[2] = mfac * inputColor[2] + fac * colorbalance_cdl(inputColor[2], this->m_offset[2], this->m_power[2], this->m_slope[2]); diff --git a/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h index cc6bd894748b..77a5dd55cd92 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h +++ b/source/blender/compositor/operations/COM_ColorBalanceASCCDLOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorBalanceASCCDLOperation_h -#define _COM_ColorBalanceASCCDLOperation_h +#ifndef __COM_COLORBALANCEASCCDLOPERATION_H__ +#define __COM_COLORBALANCEASCCDLOPERATION_H__ #include "COM_NodeOperation.h" /** @@ -35,7 +35,7 @@ class ColorBalanceASCCDLOperation : public NodeOperation { */ SocketReader *m_inputValueOperation; SocketReader *m_inputColorOperation; - + float m_offset[3]; float m_power[3]; float m_slope[3]; @@ -45,22 +45,22 @@ class ColorBalanceASCCDLOperation : public NodeOperation { * Default constructor */ ColorBalanceASCCDLOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setOffset(float offset[3]) { copy_v3_v3(this->m_offset, offset); } void setPower(float power[3]) { copy_v3_v3(this->m_power, power); } void setSlope(float slope[3]) { copy_v3_v3(this->m_slope, slope); } diff --git a/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.cpp b/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.cpp index e13fd26aed2d..e264c065f477 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.cpp @@ -58,14 +58,14 @@ void ColorBalanceLGGOperation::executePixelSampled(float output[4], float x, flo { float inputColor[4]; float value[4]; - + this->m_inputValueOperation->readSampled(value, x, y, sampler); this->m_inputColorOperation->readSampled(inputColor, x, y, sampler); - + float fac = value[0]; fac = min(1.0f, fac); const float mfac = 1.0f - fac; - + output[0] = mfac * inputColor[0] + fac * colorbalance_lgg(inputColor[0], this->m_lift[0], this->m_gamma_inv[0], this->m_gain[0]); output[1] = mfac * inputColor[1] + fac * colorbalance_lgg(inputColor[1], this->m_lift[1], this->m_gamma_inv[1], this->m_gain[1]); output[2] = mfac * inputColor[2] + fac * colorbalance_lgg(inputColor[2], this->m_lift[2], this->m_gamma_inv[2], this->m_gain[2]); diff --git a/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h b/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h index 86d7abc92bc1..3dbe2e110585 100644 --- a/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h +++ b/source/blender/compositor/operations/COM_ColorBalanceLGGOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorBalanceLGGOperation_h -#define _COM_ColorBalanceLGGOperation_h +#ifndef __COM_COLORBALANCELGGOPERATION_H__ +#define __COM_COLORBALANCELGGOPERATION_H__ #include "COM_NodeOperation.h" @@ -36,7 +36,7 @@ class ColorBalanceLGGOperation : public NodeOperation { */ SocketReader *m_inputValueOperation; SocketReader *m_inputColorOperation; - + float m_gain[3]; float m_lift[3]; float m_gamma_inv[3]; @@ -46,22 +46,22 @@ class ColorBalanceLGGOperation : public NodeOperation { * Default constructor */ ColorBalanceLGGOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setGain(const float gain[3]) { copy_v3_v3(this->m_gain, gain); } void setLift(const float lift[3]) { copy_v3_v3(this->m_lift, lift); } void setGammaInv(const float gamma_inv[3]) { copy_v3_v3(this->m_gamma_inv, gamma_inv); } diff --git a/source/blender/compositor/operations/COM_ColorCorrectionOperation.cpp b/source/blender/compositor/operations/COM_ColorCorrectionOperation.cpp index 05edaf51a25f..a67540f846d1 100644 --- a/source/blender/compositor/operations/COM_ColorCorrectionOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorCorrectionOperation.cpp @@ -50,7 +50,7 @@ void ColorCorrectionOperation::executePixelSampled(float output[4], float x, flo float inputMask[4]; this->m_inputImage->readSampled(inputImageColor, x, y, sampler); this->m_inputMask->readSampled(inputMask, x, y, sampler); - + float level = (inputImageColor[0] + inputImageColor[1] + inputImageColor[2]) / 3.0f; float contrast = this->m_data->master.contrast; float saturation = this->m_data->master.saturation; @@ -58,11 +58,11 @@ void ColorCorrectionOperation::executePixelSampled(float output[4], float x, flo float gain = this->m_data->master.gain; float lift = this->m_data->master.lift; float r, g, b; - + float value = inputMask[0]; value = min(1.0f, value); const float mvalue = 1.0f - value; - + float levelShadows = 0.0; float levelMidtones = 0.0; float levelHighlights = 0.0; @@ -92,7 +92,7 @@ void ColorCorrectionOperation::executePixelSampled(float output[4], float x, flo gamma *= (levelShadows * this->m_data->shadows.gamma) + (levelMidtones * this->m_data->midtones.gamma) + (levelHighlights * this->m_data->highlights.gamma); gain *= (levelShadows * this->m_data->shadows.gain) + (levelMidtones * this->m_data->midtones.gain) + (levelHighlights * this->m_data->highlights.gain); lift += (levelShadows * this->m_data->shadows.lift) + (levelMidtones * this->m_data->midtones.lift) + (levelHighlights * this->m_data->highlights.lift); - + float invgamma = 1.0f / gamma; float luma = IMB_colormanagement_get_luminance(inputImageColor); @@ -103,21 +103,21 @@ void ColorCorrectionOperation::executePixelSampled(float output[4], float x, flo r = (luma + saturation * (r - luma)); g = (luma + saturation * (g - luma)); b = (luma + saturation * (b - luma)); - + r = 0.5f + ((r - 0.5f) * contrast); g = 0.5f + ((g - 0.5f) * contrast); b = 0.5f + ((b - 0.5f) * contrast); - + r = powf(r * gain + lift, invgamma); g = powf(g * gain + lift, invgamma); b = powf(b * gain + lift, invgamma); - - + + // mix with mask r = mvalue * inputImageColor[0] + value * r; g = mvalue * inputImageColor[1] + value * g; b = mvalue * inputImageColor[2] + value * b; - + if (this->m_redChannelEnabled) { output[0] = r; } @@ -144,4 +144,3 @@ void ColorCorrectionOperation::deinitExecution() this->m_inputImage = NULL; this->m_inputMask = NULL; } - diff --git a/source/blender/compositor/operations/COM_ColorCorrectionOperation.h b/source/blender/compositor/operations/COM_ColorCorrectionOperation.h index c386a2f3e6e3..9b691dcb0508 100644 --- a/source/blender/compositor/operations/COM_ColorCorrectionOperation.h +++ b/source/blender/compositor/operations/COM_ColorCorrectionOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorCorrectionOperation_h -#define _COM_ColorCorrectionOperation_h +#ifndef __COM_COLORCORRECTIONOPERATION_H__ +#define __COM_COLORCORRECTIONOPERATION_H__ #include "COM_NodeOperation.h" @@ -33,29 +33,29 @@ class ColorCorrectionOperation : public NodeOperation { SocketReader *m_inputImage; SocketReader *m_inputMask; NodeColorCorrection *m_data; - + bool m_redChannelEnabled; bool m_greenChannelEnabled; bool m_blueChannelEnabled; public: ColorCorrectionOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setData(NodeColorCorrection *data) { this->m_data = data; } void setRedChannelEnabled(bool enabled) { this->m_redChannelEnabled = enabled; } void setGreenChannelEnabled(bool enabled) { this->m_greenChannelEnabled = enabled; } diff --git a/source/blender/compositor/operations/COM_ColorCurveOperation.cpp b/source/blender/compositor/operations/COM_ColorCurveOperation.cpp index 5967147b3d14..4cecc53ad017 100644 --- a/source/blender/compositor/operations/COM_ColorCurveOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorCurveOperation.cpp @@ -61,7 +61,7 @@ void ColorCurveOperation::initExecution() void ColorCurveOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) { CurveMapping *cumap = this->m_curveMapping; - + float fac[4]; float image[4]; diff --git a/source/blender/compositor/operations/COM_ColorCurveOperation.h b/source/blender/compositor/operations/COM_ColorCurveOperation.h index 3b10786fb2c0..16e3455ceec9 100644 --- a/source/blender/compositor/operations/COM_ColorCurveOperation.h +++ b/source/blender/compositor/operations/COM_ColorCurveOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorCurveOperation_h -#define _COM_ColorCurveOperation_h +#ifndef __COM_COLORCURVEOPERATION_H__ +#define __COM_COLORCURVEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_color_types.h" #include "COM_CurveBaseOperation.h" @@ -37,17 +37,17 @@ class ColorCurveOperation : public CurveBaseOperation { SocketReader *m_inputWhiteProgram; public: ColorCurveOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -63,25 +63,25 @@ class ConstantLevelColorCurveOperation : public CurveBaseOperation { SocketReader *m_inputImageProgram; float m_black[3]; float m_white[3]; - + public: ConstantLevelColorCurveOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setBlackLevel(float black[3]) { copy_v3_v3(this->m_black, black); } void setWhiteLevel(float white[3]) { copy_v3_v3(this->m_white, white); } }; diff --git a/source/blender/compositor/operations/COM_ColorMatteOperation.cpp b/source/blender/compositor/operations/COM_ColorMatteOperation.cpp index c95811e5e11e..22aa4a5b2d70 100644 --- a/source/blender/compositor/operations/COM_ColorMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorMatteOperation.cpp @@ -82,4 +82,3 @@ void ColorMatteOperation::executePixelSampled(float output[4], float x, float y, output[0] = inColor[3]; /* make pixel just as transparent as it was before */ } } - diff --git a/source/blender/compositor/operations/COM_ColorMatteOperation.h b/source/blender/compositor/operations/COM_ColorMatteOperation.h index 53bbe8f6466c..0ceedd23efdc 100644 --- a/source/blender/compositor/operations/COM_ColorMatteOperation.h +++ b/source/blender/compositor/operations/COM_ColorMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_ColorMatteOperation_h -#define _COM_ColorMatteOperation_h +#ifndef __COM_COLORMATTEOPERATION_H__ +#define __COM_COLORMATTEOPERATION_H__ #include "COM_MixOperation.h" diff --git a/source/blender/compositor/operations/COM_ColorRampOperation.h b/source/blender/compositor/operations/COM_ColorRampOperation.h index 55f711165d67..ff6d32fc4e68 100644 --- a/source/blender/compositor/operations/COM_ColorRampOperation.h +++ b/source/blender/compositor/operations/COM_ColorRampOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorRampOperation_h -#define _COM_ColorRampOperation_h +#ifndef __COM_COLORRAMPOPERATION_H__ +#define __COM_COLORRAMPOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_texture_types.h" @@ -34,22 +34,22 @@ class ColorRampOperation : public NodeOperation { ColorBand *m_colorBand; public: ColorRampOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setColorBand(ColorBand *colorBand) { this->m_colorBand = colorBand; } diff --git a/source/blender/compositor/operations/COM_ColorSpillOperation.cpp b/source/blender/compositor/operations/COM_ColorSpillOperation.cpp index 0769e5d0b01c..2f30ed830430 100644 --- a/source/blender/compositor/operations/COM_ColorSpillOperation.cpp +++ b/source/blender/compositor/operations/COM_ColorSpillOperation.cpp @@ -68,7 +68,7 @@ void ColorSpillOperation::initExecution() this->m_rmut = 1.0f; this->m_gmut = 1.0f; this->m_bmut = -1.0f; - + this->m_channel2 = 0; this->m_channel3 = 1; if (this->m_settings->unspill == 0) { diff --git a/source/blender/compositor/operations/COM_ColorSpillOperation.h b/source/blender/compositor/operations/COM_ColorSpillOperation.h index 3b94c293ec95..519e9a22335c 100644 --- a/source/blender/compositor/operations/COM_ColorSpillOperation.h +++ b/source/blender/compositor/operations/COM_ColorSpillOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ColorSpillOperation_h -#define _COM_ColorSpillOperation_h +#ifndef __COM_COLORSPILLOPERATION_H__ +#define __COM_COLORSPILLOPERATION_H__ #include "COM_NodeOperation.h" /** @@ -55,7 +55,7 @@ class ColorSpillOperation : public NodeOperation { void setSettings(NodeColorspill *nodeColorSpill) { this->m_settings = nodeColorSpill; } void setSpillChannel(int channel) { this->m_spillChannel = channel; } void setSpillMethod(int method) { this->m_spillMethod = method; } - + float calculateMapValue(float fac, float *input); }; diff --git a/source/blender/compositor/operations/COM_CompositorOperation.h b/source/blender/compositor/operations/COM_CompositorOperation.h index 269a065a7931..19ed3180ace0 100644 --- a/source/blender/compositor/operations/COM_CompositorOperation.h +++ b/source/blender/compositor/operations/COM_CompositorOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CompositorOperation_h -#define _COM_CompositorOperation_h +#ifndef __COM_COMPOSITOROPERATION_H__ +#define __COM_COMPOSITOROPERATION_H__ #include "COM_NodeOperation.h" #include "BLI_rect.h" #include "BLI_string.h" @@ -100,4 +100,3 @@ class CompositorOperation : public NodeOperation { void setActive(bool active) { this->m_active = active; } }; #endif - diff --git a/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h b/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h index ceba2a85da0d..3dc7b67df8d7 100644 --- a/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h +++ b/source/blender/compositor/operations/COM_ConvertColorProfileOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ConvertColorProfileOperation_h -#define _COM_ConvertColorProfileOperation_h +#ifndef __COM_CONVERTCOLORPROFILEOPERATION_H__ +#define __COM_CONVERTCOLORPROFILEOPERATION_H__ #include "COM_NodeOperation.h" @@ -35,17 +35,17 @@ class ConvertColorProfileOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputOperation; - + /** * @brief color profile where to convert from */ int m_fromProfile; - + /** * @brief color profile where to convert to */ int m_toProfile; - + /** * @brief is color predivided */ @@ -55,22 +55,22 @@ class ConvertColorProfileOperation : public NodeOperation { * Default constructor */ ConvertColorProfileOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setFromColorProfile(int colorProfile) { this->m_fromProfile = colorProfile; } void setToColorProfile(int colorProfile) { this->m_toProfile = colorProfile; } void setPredivided(bool predivided) { this->m_predivided = predivided; } diff --git a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp index 9057c3c92ecb..111bfeadf355 100644 --- a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp +++ b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.cpp @@ -81,7 +81,7 @@ void ConvertDepthToRadiusOperation::executePixelSampled(float output[4], float x z = inputValue[0]; if (z != 0.0f) { float iZ = (1.0f / z); - + // bug #6656 part 2b, do not rescale #if 0 bcrad = 0.5f * fabs(aperture * (dof_sp * (cam_invfdist - iZ) - 1.0f)); diff --git a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h index 697ac455702b..5294d04352e1 100644 --- a/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h +++ b/source/blender/compositor/operations/COM_ConvertDepthToRadiusOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ConvertDepthToRadiusOperation_h -#define _COM_ConvertDepthToRadiusOperation_h +#ifndef __COM_CONVERTDEPTHTORADIUSOPERATION_H__ +#define __COM_CONVERTDEPTHTORADIUSOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_object_types.h" #include "COM_FastGaussianBlurOperation.h" @@ -43,34 +43,34 @@ class ConvertDepthToRadiusOperation : public NodeOperation { float m_cam_lens; float m_dof_sp; Object *m_cameraObject; - + FastGaussianBlurValueOperation *m_blurPostOperation; public: /** * Default constructor */ ConvertDepthToRadiusOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setfStop(float fStop) { this->m_fStop = fStop; } void setMaxRadius(float maxRadius) { this->m_maxRadius = maxRadius; } void setCameraObject(Object *camera) { this->m_cameraObject = camera; } float determineFocalDistance(); void setPostBlur(FastGaussianBlurValueOperation *operation) {this->m_blurPostOperation = operation;} - + }; #endif diff --git a/source/blender/compositor/operations/COM_ConvertOperation.h b/source/blender/compositor/operations/COM_ConvertOperation.h index 5dee63ea739e..2bbe14d6c172 100644 --- a/source/blender/compositor/operations/COM_ConvertOperation.h +++ b/source/blender/compositor/operations/COM_ConvertOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ConvertOperation_h -#define _COM_ConvertOperation_h +#ifndef __COM_CONVERTOPERATION_H__ +#define __COM_CONVERTOPERATION_H__ #include "COM_NodeOperation.h" @@ -29,10 +29,10 @@ class ConvertBaseOperation : public NodeOperation { protected: SocketReader *m_inputOperation; - + public: ConvertBaseOperation(); - + void initExecution(); void deinitExecution(); }; @@ -41,7 +41,7 @@ class ConvertBaseOperation : public NodeOperation { class ConvertValueToColorOperation : public ConvertBaseOperation { public: ConvertValueToColorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -49,7 +49,7 @@ class ConvertValueToColorOperation : public ConvertBaseOperation { class ConvertColorToValueOperation : public ConvertBaseOperation { public: ConvertColorToValueOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -57,7 +57,7 @@ class ConvertColorToValueOperation : public ConvertBaseOperation { class ConvertColorToBWOperation : public ConvertBaseOperation { public: ConvertColorToBWOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -65,7 +65,7 @@ class ConvertColorToBWOperation : public ConvertBaseOperation { class ConvertColorToVectorOperation : public ConvertBaseOperation { public: ConvertColorToVectorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -73,7 +73,7 @@ class ConvertColorToVectorOperation : public ConvertBaseOperation { class ConvertValueToVectorOperation : public ConvertBaseOperation { public: ConvertValueToVectorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -81,7 +81,7 @@ class ConvertValueToVectorOperation : public ConvertBaseOperation { class ConvertVectorToColorOperation : public ConvertBaseOperation { public: ConvertVectorToColorOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -89,7 +89,7 @@ class ConvertVectorToColorOperation : public ConvertBaseOperation { class ConvertVectorToValueOperation : public ConvertBaseOperation { public: ConvertVectorToValueOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -114,9 +114,9 @@ class ConvertYCCToRGBOperation : public ConvertBaseOperation { int m_mode; public: ConvertYCCToRGBOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** Set the YCC mode */ void setMode(int mode); }; @@ -125,7 +125,7 @@ class ConvertYCCToRGBOperation : public ConvertBaseOperation { class ConvertRGBToYUVOperation : public ConvertBaseOperation { public: ConvertRGBToYUVOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -133,7 +133,7 @@ class ConvertRGBToYUVOperation : public ConvertBaseOperation { class ConvertYUVToRGBOperation : public ConvertBaseOperation { public: ConvertYUVToRGBOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -141,7 +141,7 @@ class ConvertYUVToRGBOperation : public ConvertBaseOperation { class ConvertRGBToHSVOperation : public ConvertBaseOperation { public: ConvertRGBToHSVOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -149,7 +149,7 @@ class ConvertRGBToHSVOperation : public ConvertBaseOperation { class ConvertHSVToRGBOperation : public ConvertBaseOperation { public: ConvertHSVToRGBOperation(); - + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; @@ -177,10 +177,10 @@ class SeparateChannelOperation : public NodeOperation { public: SeparateChannelOperation(); void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); - + void setChannel(int channel) { this->m_channel = channel; } }; @@ -194,7 +194,7 @@ class CombineChannelsOperation : public NodeOperation { public: CombineChannelsOperation(); void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); }; diff --git a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp index 56815459ee7c..9eb2d1bfcc5d 100644 --- a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp +++ b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp @@ -44,7 +44,7 @@ void ConvolutionEdgeFilterOperation::executePixel(float output[4], int x, int y, CLAMP(y1, 0, getHeight() - 1); CLAMP(y2, 0, getHeight() - 1); CLAMP(y3, 0, getHeight() - 1); - + float value[4]; this->m_inputValueOperation->read(value, x2, y2, NULL); float mval = 1.0f - value[0]; @@ -52,47 +52,47 @@ void ConvolutionEdgeFilterOperation::executePixel(float output[4], int x, int y, this->m_inputOperation->read(in1, x1, y1, NULL); madd_v3_v3fl(res1, in1, this->m_filter[0]); madd_v3_v3fl(res2, in1, this->m_filter[0]); - + this->m_inputOperation->read(in1, x2, y1, NULL); madd_v3_v3fl(res1, in1, this->m_filter[1]); madd_v3_v3fl(res2, in1, this->m_filter[3]); - + this->m_inputOperation->read(in1, x3, y1, NULL); madd_v3_v3fl(res1, in1, this->m_filter[2]); madd_v3_v3fl(res2, in1, this->m_filter[6]); - + this->m_inputOperation->read(in1, x1, y2, NULL); madd_v3_v3fl(res1, in1, this->m_filter[3]); madd_v3_v3fl(res2, in1, this->m_filter[1]); - + this->m_inputOperation->read(in2, x2, y2, NULL); madd_v3_v3fl(res1, in2, this->m_filter[4]); madd_v3_v3fl(res2, in2, this->m_filter[4]); - + this->m_inputOperation->read(in1, x3, y2, NULL); madd_v3_v3fl(res1, in1, this->m_filter[5]); madd_v3_v3fl(res2, in1, this->m_filter[7]); - + this->m_inputOperation->read(in1, x1, y3, NULL); madd_v3_v3fl(res1, in1, this->m_filter[6]); madd_v3_v3fl(res2, in1, this->m_filter[2]); - + this->m_inputOperation->read(in1, x2, y3, NULL); madd_v3_v3fl(res1, in1, this->m_filter[7]); madd_v3_v3fl(res2, in1, this->m_filter[5]); - + this->m_inputOperation->read(in1, x3, y3, NULL); madd_v3_v3fl(res1, in1, this->m_filter[8]); madd_v3_v3fl(res2, in1, this->m_filter[8]); - + output[0] = sqrt(res1[0] * res1[0] + res2[0] * res2[0]); output[1] = sqrt(res1[1] * res1[1] + res2[1] * res2[1]); output[2] = sqrt(res1[2] * res1[2] + res2[2] * res2[2]); - + output[0] = output[0] * value[0] + in2[0] * mval; output[1] = output[1] * value[0] + in2[1] * mval; output[2] = output[2] * value[0] + in2[2] * mval; - + output[3] = in2[3]; /* Make sure we don't return negative color. */ diff --git a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.h b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.h index 650d3ddda58e..4689a5b34f11 100644 --- a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.h +++ b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ConvolutionEdgeFilterOperation_h_ -#define _COM_ConvolutionEdgeFilterOperation_h_ +#ifndef __COM_CONVOLUTIONEDGEFILTEROPERATION_H__ +#define __COM_CONVOLUTIONEDGEFILTEROPERATION_H__ #include "COM_ConvolutionFilterOperation.h" diff --git a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp index 41cc504af059..b14fdc811d49 100644 --- a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp +++ b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp @@ -102,7 +102,7 @@ void ConvolutionFilterOperation::executePixel(float output[4], int x, int y, voi madd_v4_v4fl(output, in1, this->m_filter[7]); this->m_inputOperation->read(in1, x3, y3, NULL); madd_v4_v4fl(output, in1, this->m_filter[8]); - + output[0] = output[0] * value[0] + in2[0] * mval; output[1] = output[1] * value[0] + in2[1] * mval; output[2] = output[2] * value[0] + in2[2] * mval; @@ -124,6 +124,6 @@ bool ConvolutionFilterOperation::determineDependingAreaOfInterest(rcti *input, R newInput.xmin = input->xmin - addx; newInput.ymax = input->ymax + addy; newInput.ymin = input->ymin - addy; - + return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } diff --git a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h index 75fba0ee1e42..20b8be3278dc 100644 --- a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h +++ b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ConvolutionFilterOperation_h_ -#define _COM_ConvolutionFilterOperation_h_ +#ifndef __COM_CONVOLUTIONFILTEROPERATION_H__ +#define __COM_CONVOLUTIONFILTEROPERATION_H__ #include "COM_NodeOperation.h" @@ -40,7 +40,7 @@ class ConvolutionFilterOperation : public NodeOperation { void set3x3Filter(float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void executePixel(float output[4], int x, int y, void *data); - + void initExecution(); void deinitExecution(); }; diff --git a/source/blender/compositor/operations/COM_CropOperation.cpp b/source/blender/compositor/operations/COM_CropOperation.cpp index 162811ac31da..af68fa09f1ab 100644 --- a/source/blender/compositor/operations/COM_CropOperation.cpp +++ b/source/blender/compositor/operations/COM_CropOperation.cpp @@ -37,7 +37,7 @@ void CropBaseOperation::updateArea() float width = inputReference->getWidth(); float height = inputReference->getHeight(); NodeTwoXYs local_settings = *this->m_settings; - + if (width > 0.0f && height > 0.0f) { if (this->m_relative) { local_settings.x1 = width * local_settings.fac_x1; @@ -53,7 +53,7 @@ void CropBaseOperation::updateArea() local_settings.x2 = width - 1; if (height <= local_settings.y2 + 1) local_settings.y2 = height - 1; - + this->m_xmax = max(local_settings.x1, local_settings.x2) + 1; this->m_xmin = min(local_settings.x1, local_settings.x2); this->m_ymax = max(local_settings.y1, local_settings.y2) + 1; @@ -101,12 +101,12 @@ CropImageOperation::CropImageOperation() : CropBaseOperation() bool CropImageOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output) { rcti newInput; - + newInput.xmax = input->xmax + this->m_xmin; newInput.xmin = input->xmin + this->m_xmin; newInput.ymax = input->ymax + this->m_ymin; newInput.ymin = input->ymin + this->m_ymin; - + return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } diff --git a/source/blender/compositor/operations/COM_CropOperation.h b/source/blender/compositor/operations/COM_CropOperation.h index 7c5b995fb173..0e0f25a2bf6e 100644 --- a/source/blender/compositor/operations/COM_CropOperation.h +++ b/source/blender/compositor/operations/COM_CropOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CropOperation_h_ -#define _COM_CropOperation_h_ +#ifndef __COM_CROPOPERATION_H__ +#define __COM_CROPOPERATION_H__ #include "COM_NodeOperation.h" @@ -34,7 +34,7 @@ class CropBaseOperation : public NodeOperation { int m_xmin; int m_ymax; int m_ymin; - + void updateArea(); public: CropBaseOperation(); diff --git a/source/blender/compositor/operations/COM_CryptomatteOperation.cpp b/source/blender/compositor/operations/COM_CryptomatteOperation.cpp new file mode 100644 index 000000000000..9a1cbdd7a00a --- /dev/null +++ b/source/blender/compositor/operations/COM_CryptomatteOperation.cpp @@ -0,0 +1,75 @@ +/* + * Copyright 2018, Blender Foundation. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contributor: Lukas Stockner, Stefan Werner + */ + +#include "COM_CryptomatteOperation.h" + +CryptomatteOperation::CryptomatteOperation(size_t num_inputs) : NodeOperation() +{ + for (size_t i = 0; i < num_inputs; i++) { + this->addInputSocket(COM_DT_COLOR); + } + inputs.resize(num_inputs); + this->addOutputSocket(COM_DT_COLOR); + this->setComplex(true); +} + +void CryptomatteOperation::initExecution() +{ + for (size_t i = 0; i < inputs.size(); i++) { + inputs[i] = this->getInputSocketReader(i); + } +} + +void CryptomatteOperation::addObjectIndex(float objectIndex) +{ + if (objectIndex != 0.0f) { + m_objectIndex.push_back(objectIndex); + } +} + +void CryptomatteOperation::executePixel(float output[4], + int x, + int y, + void *data) +{ + float input[4]; + output[0] = output[1] = output[2] = output[3] = 0.0f; + for (size_t i = 0; i < inputs.size(); i++) { + inputs[i]->read(input, x, y, data); + if (i == 0) { + /* Write the frontmost object as false color for picking. */ + output[0] = input[0]; + uint32_t m3hash; + ::memcpy(&m3hash, &input[0], sizeof(uint32_t)); + /* Since the red channel is likely to be out of display range, + * setting green and blue gives more meaningful images. */ + output[1] = ((float) ((m3hash << 8)) / (float) UINT32_MAX); + output[2] = ((float) ((m3hash << 16)) / (float) UINT32_MAX); + } + for (size_t i = 0; i < m_objectIndex.size(); i++) { + if (m_objectIndex[i] == input[0]) { + output[3] += input[1]; + } + if (m_objectIndex[i] == input[2]) { + output[3] += input[3]; + } + } + } +} diff --git a/source/blender/compositor/operations/COM_CryptomatteOperation.h b/source/blender/compositor/operations/COM_CryptomatteOperation.h new file mode 100644 index 000000000000..250c5ab8a495 --- /dev/null +++ b/source/blender/compositor/operations/COM_CryptomatteOperation.h @@ -0,0 +1,40 @@ +/* + * Copyright 2018, Blender Foundation. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contributor: Lukas Stockner, Stefan Werner + */ + +#ifndef __COM_CRYPTOMATTEOPERATION_H__ +#define __COM_CRYPTOMATTEOPERATION_H__ +#include "COM_NodeOperation.h" + + +class CryptomatteOperation : public NodeOperation { +private: + std::vector m_objectIndex; +public: + std::vector inputs; + + CryptomatteOperation(size_t num_inputs = 6); + + void initExecution(); + void executePixel(float output[4], int x, int y, void *data); + + void addObjectIndex(float objectIndex); + +}; +#endif diff --git a/source/blender/compositor/operations/COM_CurveBaseOperation.h b/source/blender/compositor/operations/COM_CurveBaseOperation.h index 169022de5f5b..1eb943dcc510 100644 --- a/source/blender/compositor/operations/COM_CurveBaseOperation.h +++ b/source/blender/compositor/operations/COM_CurveBaseOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_CurveBaseOperation_h -#define _COM_CurveBaseOperation_h +#ifndef __COM_CURVEBASEOPERATION_H__ +#define __COM_CURVEBASEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_color_types.h" @@ -34,13 +34,13 @@ class CurveBaseOperation : public NodeOperation { public: CurveBaseOperation(); ~CurveBaseOperation(); - + /** * Initialize the execution */ void initExecution(); void deinitExecution(); - + void setCurveMapping(CurveMapping *mapping); }; #endif diff --git a/source/blender/compositor/operations/COM_DespeckleOperation.h b/source/blender/compositor/operations/COM_DespeckleOperation.h index 00c5463c17aa..4ae0e8525d10 100644 --- a/source/blender/compositor/operations/COM_DespeckleOperation.h +++ b/source/blender/compositor/operations/COM_DespeckleOperation.h @@ -18,8 +18,8 @@ * Contributor: Campbell Barton */ -#ifndef _COM_DespeckleOperation_h -#define _COM_DespeckleOperation_h +#ifndef __COM_DESPECKLEOPERATION_H__ +#define __COM_DESPECKLEOPERATION_H__ #include "COM_NodeOperation.h" class DespeckleOperation : public NodeOperation { diff --git a/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp b/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp index 770a5bd205b8..f6417bb78a00 100644 --- a/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp @@ -85,4 +85,3 @@ void DifferenceMatteOperation::executePixelSampled(float output[4], float x, flo output[0] = inColor1[3]; } } - diff --git a/source/blender/compositor/operations/COM_DifferenceMatteOperation.h b/source/blender/compositor/operations/COM_DifferenceMatteOperation.h index ddf6bf6f8932..3ea27f85eb65 100644 --- a/source/blender/compositor/operations/COM_DifferenceMatteOperation.h +++ b/source/blender/compositor/operations/COM_DifferenceMatteOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DifferenceMatteOperation_h -#define _COM_DifferenceMatteOperation_h +#ifndef __COM_DIFFERENCEMATTEOPERATION_H__ +#define __COM_DIFFERENCEMATTEOPERATION_H__ #include "COM_MixOperation.h" @@ -39,15 +39,15 @@ class DifferenceMatteOperation : public NodeOperation { * Default constructor */ DifferenceMatteOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); - + void setSettings(NodeChroma *nodeChroma) { this->m_settings = nodeChroma; } }; #endif diff --git a/source/blender/compositor/operations/COM_DilateErodeOperation.cpp b/source/blender/compositor/operations/COM_DilateErodeOperation.cpp index 2ea438d070de..17f3dfeac624 100644 --- a/source/blender/compositor/operations/COM_DilateErodeOperation.cpp +++ b/source/blender/compositor/operations/COM_DilateErodeOperation.cpp @@ -200,7 +200,7 @@ void DilateDistanceOperation::executePixel(float output[4], int x, int y, void * const int maxy = min(y + this->m_scope, rect->ymax); const int bufferWidth = BLI_rcti_size_x(rect); int offset; - + float value = 0.0f; for (int yi = miny; yi < maxy; yi++) { @@ -244,7 +244,7 @@ void DilateDistanceOperation::executeOpenCL(OpenCLDevice *device, cl_int distanceSquared = this->m_distance * this->m_distance; cl_int scope = this->m_scope; - + device->COM_clAttachMemoryBufferToKernelParameter(dilateKernel, 0, 2, clMemToCleanUp, inputMemoryBuffers, this->m_inputProgram); device->COM_clAttachOutputMemoryBufferToKernelParameter(dilateKernel, 1, clOutputBuffer); device->COM_clAttachMemoryBufferOffsetToKernelParameter(dilateKernel, 3, outputMemoryBuffer); @@ -255,7 +255,7 @@ void DilateDistanceOperation::executeOpenCL(OpenCLDevice *device, } // Erode Distance -ErodeDistanceOperation::ErodeDistanceOperation() : DilateDistanceOperation() +ErodeDistanceOperation::ErodeDistanceOperation() : DilateDistanceOperation() { /* pass */ } @@ -274,7 +274,7 @@ void ErodeDistanceOperation::executePixel(float output[4], int x, int y, void *d const int maxy = min(y + this->m_scope, rect->ymax); const int bufferWidth = BLI_rcti_size_x(rect); int offset; - + float value = 1.0f; for (int yi = miny; yi < maxy; yi++) { @@ -301,7 +301,7 @@ void ErodeDistanceOperation::executeOpenCL(OpenCLDevice *device, cl_int distanceSquared = this->m_distance * this->m_distance; cl_int scope = this->m_scope; - + device->COM_clAttachMemoryBufferToKernelParameter(erodeKernel, 0, 2, clMemToCleanUp, inputMemoryBuffers, this->m_inputProgram); device->COM_clAttachOutputMemoryBufferToKernelParameter(erodeKernel, 1, clOutputBuffer); device->COM_clAttachMemoryBufferOffsetToKernelParameter(erodeKernel, 3, outputMemoryBuffer); diff --git a/source/blender/compositor/operations/COM_DilateErodeOperation.h b/source/blender/compositor/operations/COM_DilateErodeOperation.h index c929fcf7fec8..56dcbb9b4a67 100644 --- a/source/blender/compositor/operations/COM_DilateErodeOperation.h +++ b/source/blender/compositor/operations/COM_DilateErodeOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DilateErodeOperation_h -#define _COM_DilateErodeOperation_h +#ifndef __COM_DILATEERODEOPERATION_H__ +#define __COM_DILATEERODEOPERATION_H__ #include "COM_NodeOperation.h" @@ -31,11 +31,11 @@ class DilateErodeThresholdOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputProgram; - + float m_distance; float m__switch; float m_inset; - + /** * determines the area of interest to track pixels * keep this one as small as possible for speed gain. @@ -43,27 +43,27 @@ class DilateErodeThresholdOperation : public NodeOperation { int m_scope; public: DilateErodeThresholdOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); - + void setDistance(float distance) { this->m_distance = distance; } void setSwitch(float sw) { this->m__switch = sw; } void setInset(float inset) { this->m_inset = inset; } - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; @@ -79,43 +79,43 @@ class DilateDistanceOperation : public NodeOperation { int m_scope; public: DilateDistanceOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); - + void setDistance(float distance) { this->m_distance = distance; } bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); - + void executeOpenCL(OpenCLDevice *device, - MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list *clKernelsToCleanUp); }; class ErodeDistanceOperation : public DilateDistanceOperation { public: ErodeDistanceOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); void executeOpenCL(OpenCLDevice *device, - MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, - MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list *clKernelsToCleanUp); }; @@ -125,38 +125,38 @@ class DilateStepOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputProgram; - + int m_iterations; - + public: DilateStepOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); void deinitializeTileData(rcti *rect, void *data); - + void setIterations(int iterations) { this->m_iterations = iterations; } - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; class ErodeStepOperation : public DilateStepOperation { public: ErodeStepOperation(); - + void *initializeTileData(rcti *rect); }; diff --git a/source/blender/compositor/operations/COM_DirectionalBlurOperation.cpp b/source/blender/compositor/operations/COM_DirectionalBlurOperation.cpp index 2e0be8d8410d..e3dec838589c 100644 --- a/source/blender/compositor/operations/COM_DirectionalBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_DirectionalBlurOperation.cpp @@ -102,8 +102,8 @@ void DirectionalBlurOperation::executePixel(float output[4], int x, int y, void } void DirectionalBlurOperation::executeOpenCL(OpenCLDevice *device, - MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, - MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list * /*clKernelsToCleanUp*/) { cl_kernel directionalBlurKernel = device->COM_clCreateKernel("directionalBlurKernel", NULL); @@ -113,7 +113,7 @@ void DirectionalBlurOperation::executeOpenCL(OpenCLDevice *device, cl_float2 centerpix = {{this->m_center_x_pix, this->m_center_y_pix}}; cl_float lsc = this->m_sc; cl_float lrot = this->m_rot; - + device->COM_clAttachMemoryBufferToKernelParameter(directionalBlurKernel, 0, -1, clMemToCleanUp, inputMemoryBuffers, this->m_inputProgram); device->COM_clAttachOutputMemoryBufferToKernelParameter(directionalBlurKernel, 1, clOutputBuffer); device->COM_clAttachMemoryBufferOffsetToKernelParameter(directionalBlurKernel, 2, outputMemoryBuffer); @@ -122,7 +122,7 @@ void DirectionalBlurOperation::executeOpenCL(OpenCLDevice *device, clSetKernelArg(directionalBlurKernel, 5, sizeof(cl_float), &lrot); clSetKernelArg(directionalBlurKernel, 6, sizeof(cl_float2), <xy); clSetKernelArg(directionalBlurKernel, 7, sizeof(cl_float2), ¢erpix); - + device->COM_clEnqueueRange(directionalBlurKernel, outputMemoryBuffer, 8, this); } diff --git a/source/blender/compositor/operations/COM_DirectionalBlurOperation.h b/source/blender/compositor/operations/COM_DirectionalBlurOperation.h index a6194a0ca738..eaabf49bf744 100644 --- a/source/blender/compositor/operations/COM_DirectionalBlurOperation.h +++ b/source/blender/compositor/operations/COM_DirectionalBlurOperation.h @@ -41,25 +41,25 @@ class DirectionalBlurOperation : public NodeOperation, public QualityStepHelper * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); - + void setData(NodeDBlurData *data) { this->m_data = data; } void executeOpenCL(OpenCLDevice *device, MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list *clKernelsToCleanUp); - + }; #endif diff --git a/source/blender/compositor/operations/COM_DisplaceOperation.cpp b/source/blender/compositor/operations/COM_DisplaceOperation.cpp index 9b3377e887a5..0273a1de1336 100644 --- a/source/blender/compositor/operations/COM_DisplaceOperation.cpp +++ b/source/blender/compositor/operations/COM_DisplaceOperation.cpp @@ -92,7 +92,7 @@ void DisplaceOperation::pixelTransform(const float xy[2], float r_uv[2], float r float xs = col[0]; m_inputScaleYProgram->readSampled(col, xy[0], xy[1], COM_PS_NEAREST); float ys = col[0]; - /* clamp x and y displacement to triple image resolution - + /* clamp x and y displacement to triple image resolution - * to prevent hangs from huge values mistakenly plugged in eg. z buffers */ CLAMP(xs, -m_width_x4, m_width_x4); CLAMP(ys, -m_height_x4, m_height_x4); @@ -102,7 +102,7 @@ void DisplaceOperation::pixelTransform(const float xy[2], float r_uv[2], float r /* Estimate partial derivatives using 1-pixel offsets */ const float epsilon[2] = { 1.0f, 1.0f }; - + zero_v2(r_deriv[0]); zero_v2(r_deriv[1]); @@ -190,4 +190,3 @@ bool DisplaceOperation::determineDependingAreaOfInterest(rcti *input, ReadBuffer return false; } - diff --git a/source/blender/compositor/operations/COM_DisplaceOperation.h b/source/blender/compositor/operations/COM_DisplaceOperation.h index cec7937d9d6e..5a30f8972031 100644 --- a/source/blender/compositor/operations/COM_DisplaceOperation.h +++ b/source/blender/compositor/operations/COM_DisplaceOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DisplaceOperation_h -#define _COM_DisplaceOperation_h +#ifndef __COM_DISPLACEOPERATION_H__ +#define __COM_DISPLACEOPERATION_H__ #include "COM_NodeOperation.h" @@ -49,14 +49,14 @@ class DisplaceOperation : public NodeOperation { * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void pixelTransform(const float xy[2], float r_uv[2], float r_deriv[2][2]); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp index 40b4fdec28e7..98083add1f7a 100644 --- a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp +++ b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.cpp @@ -66,7 +66,7 @@ void DisplaceSimpleOperation::executePixelSampled(float output[4], float x, floa this->m_inputScaleYProgram->readSampled(inScale, x, y, sampler); float ys = inScale[0]; - /* clamp x and y displacement to triple image resolution - + /* clamp x and y displacement to triple image resolution - * to prevent hangs from huge values mistakenly plugged in eg. z buffers */ CLAMP(xs, -this->m_width_x4, this->m_width_x4); CLAMP(ys, -this->m_height_x4, this->m_height_x4); @@ -128,4 +128,3 @@ bool DisplaceSimpleOperation::determineDependingAreaOfInterest(rcti *input, Read return false; } - diff --git a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h index 6e52dfe86e9c..c0bd6bacdd44 100644 --- a/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h +++ b/source/blender/compositor/operations/COM_DisplaceSimpleOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DisplaceSimpleOperation_h -#define _COM_DisplaceSimpleOperation_h +#ifndef __COM_DISPLACESIMPLEOPERATION_H__ +#define __COM_DISPLACESIMPLEOPERATION_H__ #include "COM_NodeOperation.h" @@ -49,12 +49,12 @@ class DisplaceSimpleOperation : public NodeOperation { * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.cpp b/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.cpp index b9e6864b3401..adc977d014dd 100644 --- a/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.cpp @@ -62,13 +62,13 @@ void DistanceRGBMatteOperation::executePixelSampled(float output[4], float x, fl this->m_inputKeyProgram->readSampled(inKey, x, y, sampler); this->m_inputImageProgram->readSampled(inImage, x, y, sampler); - + distance = this->calculateDistance(inKey, inImage); /* store matte(alpha) value in [0] to go with * COM_SetAlphaOperation and the Value output */ - + /*make 100% transparent */ if (distance < tolerance) { output[0] = 0.0f; diff --git a/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h b/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h index a815caa5ef5d..0b45b0b75e91 100644 --- a/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h +++ b/source/blender/compositor/operations/COM_DistanceRGBMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DistanceRGBMatteOperation_h -#define _COM_DistanceRGBMatteOperation_h +#ifndef __COM_DISTANCERGBMATTEOPERATION_H__ +#define __COM_DISTANCERGBMATTEOPERATION_H__ #include "COM_MixOperation.h" @@ -41,15 +41,15 @@ class DistanceRGBMatteOperation : public NodeOperation { * Default constructor */ DistanceRGBMatteOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); - + void setSettings(NodeChroma *nodeChroma) { this->m_settings = nodeChroma; } }; #endif diff --git a/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.cpp b/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.cpp index 0a6f1fdfd316..69d77c43245b 100644 --- a/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.cpp @@ -32,4 +32,3 @@ float DistanceYCCMatteOperation::calculateDistance(float key[4], float image[4]) /* only measure the second 2 values */ return len_v2v2(key + 1, image + 1); } - diff --git a/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.h b/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.h index 27025188d494..afff1414d7a1 100644 --- a/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.h +++ b/source/blender/compositor/operations/COM_DistanceYCCMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_DistanceYCCMatteOperation_h -#define _COM_DistanceYCCMatteOperation_h +#ifndef __COM_DISTANCEYCCMATTEOPERATION_H__ +#define __COM_DISTANCEYCCMATTEOPERATION_H__ #include "COM_MixOperation.h" #include "COM_DistanceRGBMatteOperation.h" diff --git a/source/blender/compositor/operations/COM_DotproductOperation.h b/source/blender/compositor/operations/COM_DotproductOperation.h index 218409cbf5b3..43e38ee7c78e 100644 --- a/source/blender/compositor/operations/COM_DotproductOperation.h +++ b/source/blender/compositor/operations/COM_DotproductOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DotproductOperation_h_ -#define _COM_DotproductOperation_h_ +#ifndef __COM_DOTPRODUCTOPERATION_H__ +#define __COM_DOTPRODUCTOPERATION_H__ #include "COM_NodeOperation.h" @@ -32,7 +32,7 @@ class DotproductOperation : public NodeOperation { public: DotproductOperation(); void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); diff --git a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.cpp b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.cpp index 8d2a0f3b427e..3566eafa2dbb 100644 --- a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.cpp +++ b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.cpp @@ -108,7 +108,7 @@ static void do_adjacentKeepBorders(unsigned int t, unsigned int rw, unsigned int osz++; // increment outer edge size lres[x] = 3; // flag pixel as outer edge } - + /* Test the TOP row of pixels in buffer, except corners */ for (x = t - 1; x >= (t - rw) + 2; x--) { // test if inner mask is filled @@ -128,7 +128,7 @@ static void do_adjacentKeepBorders(unsigned int t, unsigned int rw, unsigned int lres[x] = 3; // flag pixel as outer edge } } - + /* Test the BOTTOM row of pixels in buffer, except corners */ for (x = rw - 2; x; x--) { // test if inner mask is filled @@ -167,7 +167,7 @@ static void do_adjacentKeepBorders(unsigned int t, unsigned int rw, unsigned int lres[x] = 3; // flag pixel as outer edge } } - + /* Test the RIGHT edge of pixels in buffer, except corners */ for (x = t - rw; x > rw; x -= rw) { // test if inner mask is filled @@ -187,7 +187,7 @@ static void do_adjacentKeepBorders(unsigned int t, unsigned int rw, unsigned int lres[x] = 3; // flag pixel as outer edge } } - + rsize[0] = isz; // fill in our return sizes for edges + fill rsize[1] = osz; rsize[2] = gsz; @@ -321,7 +321,7 @@ static void do_adjacentBleedBorders(unsigned int t, unsigned int rw, unsigned in } } } - + /* Test the BOTTOM row of pixels in buffer, except corners */ for (x = rw - 2; x; x--) { // test if inner mask is filled @@ -372,7 +372,7 @@ static void do_adjacentBleedBorders(unsigned int t, unsigned int rw, unsigned in } } } - + /* Test the RIGHT edge of pixels in buffer, except corners */ for (x = t - rw; x > rw; x -= rw) { // test if inner mask is filled @@ -398,7 +398,7 @@ static void do_adjacentBleedBorders(unsigned int t, unsigned int rw, unsigned in } } } - + rsize[0] = isz; // fill in our return sizes for edges + fill rsize[1] = osz; rsize[2] = gsz; @@ -479,7 +479,7 @@ static void do_allKeepBorders(unsigned int t, unsigned int rw, unsigned int *lim osz++; // increment outer edge size lres[x] = 3; // flag pixel as outer edge } - + /* Test the TOP row of pixels in buffer, except corners */ for (x = t - 1; x >= (t - rw) + 2; x--) { // test if inner mask is filled @@ -498,7 +498,7 @@ static void do_allKeepBorders(unsigned int t, unsigned int rw, unsigned int *lim lres[x] = 3; // flag pixel as outer edge } } - + /* Test the BOTTOM row of pixels in buffer, except corners */ for (x = rw - 2; x; x--) { // test if inner mask is filled @@ -535,7 +535,7 @@ static void do_allKeepBorders(unsigned int t, unsigned int rw, unsigned int *lim lres[x] = 3; // flag pixel as outer edge } } - + /* Test the RIGHT edge of pixels in buffer, except corners */ for (x = t - rw; x > rw; x -= rw) { // test if inner mask is filled @@ -554,7 +554,7 @@ static void do_allKeepBorders(unsigned int t, unsigned int rw, unsigned int *lim lres[x] = 3; // flag pixel as outer edge } } - + rsize[0] = isz; // fill in our return sizes for edges + fill rsize[1] = osz; rsize[2] = gsz; @@ -683,7 +683,7 @@ static void do_allBleedBorders(unsigned int t, unsigned int rw, unsigned int *li } } } - + /* Test the BOTTOM row of pixels in buffer, except corners */ for (x = rw - 2; x; x--) { // test if inner mask is filled @@ -732,7 +732,7 @@ static void do_allBleedBorders(unsigned int t, unsigned int rw, unsigned int *li } } } - + /* Test the RIGHT edge of pixels in buffer, except corners */ for (x = t - rw; x > rw; x -= rw) { // test if inner mask is filled @@ -757,7 +757,7 @@ static void do_allBleedBorders(unsigned int t, unsigned int rw, unsigned int *li } } } - + rsize[0] = isz; // fill in our return sizes for edges + fill rsize[1] = osz; rsize[2] = gsz; @@ -801,7 +801,7 @@ static void do_allEdgeDetection(unsigned int t, unsigned int rw, unsigned int *l lres[a] = 2; // flag pixel as gradient } } - + } else { if (!limask[pix_nextCol] || !limask[pix_prevCol] || !limask[pix_nextRow] || !limask[pix_prevRow]) { @@ -819,7 +819,7 @@ static void do_allEdgeDetection(unsigned int t, unsigned int rw, unsigned int *l pix_nextCol--; } } - + rsize[0] = in_isz; // fill in our return sizes for edges + fill rsize[1] = in_osz; rsize[2] = in_gsz; @@ -863,7 +863,7 @@ static void do_adjacentEdgeDetection(unsigned int t, unsigned int rw, unsigned i lres[a] = 2; // flag pixel as gradient } } - + } else { if ((!limask[pix_nextCol] && lomask[pix_nextCol]) || @@ -885,7 +885,7 @@ static void do_adjacentEdgeDetection(unsigned int t, unsigned int rw, unsigned i pix_nextCol--; } } - + rsize[0] = in_isz; // fill in our return sizes for edges + fill rsize[1] = in_osz; rsize[2] = in_gsz; @@ -897,7 +897,7 @@ static void do_createEdgeLocationBuffer(unsigned int t, unsigned int rw, unsigne int a; // a = temporary pixel index buffer loop counter unsigned int ud; // ud = unscaled edge distance unsigned int dmin; // dmin = minimum edge distance - + unsigned int rsl; // long used for finding fast 1.0/sqrt unsigned int gradientFillOffset; unsigned int innerAccum = 0; // for looping inner edge pixel indexes, represents current position from offset @@ -999,7 +999,7 @@ static void do_createEdgeLocationBuffer(unsigned int t, unsigned int rw, unsigne } } } - + } static void do_fillGradientBuffer(unsigned int rw, float *res, unsigned short *gbuf, unsigned int isz, unsigned int osz, unsigned int gsz, unsigned int innerEdgeOffset, unsigned int outerEdgeOffset) @@ -1010,7 +1010,7 @@ static void do_fillGradientBuffer(unsigned int rw, float *res, unsigned short *g unsigned int rsl; // long used for finding fast 1.0/sqrt float rsf; // float used for finding fast 1.0/sqrt const float rsopf = 1.5f; // constant float used for finding fast 1.0/sqrt - + unsigned int gradientFillOffset; unsigned int t; unsigned int ud; // ud = unscaled edge distance @@ -1019,7 +1019,7 @@ static void do_fillGradientBuffer(unsigned int rw, float *res, unsigned short *g float idist; // idist = current inner edge distance int dx; // dx = X-delta (used for distance proportion calculation) int dy; // dy = Y-delta (used for distance proportion calculation) - + /* * The general algorithm used to color each gradient pixel is: * @@ -1057,7 +1057,7 @@ static void do_fillGradientBuffer(unsigned int rw, float *res, unsigned short *g * G = gradient pixel * | * I = inside edge pixel - * + * * __ * *note that IO does not need to be a straight line, in fact * many cases can arise where straight lines do not work @@ -1120,14 +1120,14 @@ static void do_fillGradientBuffer(unsigned int rw, float *res, unsigned short *g * proportion is already the correct intensity, and does not need to be * subtracted from 1.0 like it would have if we used real distances. */ - + /* * Here we reconstruct the pixel's memory location in the CompBuf by * Pixel Index = Pixel Column + ( Pixel Row * Row Width ) */ res[gbuf[gradientFillOffset + 1] + (gbuf[gradientFillOffset] * rw)] = (idist / (idist + odist)); //set intensity } - + } // end of copy @@ -1137,31 +1137,31 @@ void DoubleEdgeMaskOperation::doDoubleEdgeMask(float *imask, float *omask, float unsigned int *lres; // lres = unsigned int pointer to output pixel buffer (for bit operations) unsigned int *limask; // limask = unsigned int pointer to inner mask (for bit operations) unsigned int *lomask; // lomask = unsigned int pointer to outer mask (for bit operations) - + int rw; // rw = pixel row width int t; // t = total number of pixels in buffer - 1 (used for loop starts) int fsz; // size of the frame - + unsigned int isz = 0; // size (in pixels) of inside edge pixel index buffer unsigned int osz = 0; // size (in pixels) of outside edge pixel index buffer unsigned int gsz = 0; // size (in pixels) of gradient pixel index buffer unsigned int rsize[3]; // size storage to pass to helper functions unsigned int innerEdgeOffset = 0; // offset into final buffer where inner edge pixel indexes start unsigned int outerEdgeOffset = 0; // offset into final buffer where outer edge pixel indexes start - + unsigned short *gbuf; // gradient/inner/outer pixel location index buffer - + if (true) { // if both input sockets have some data coming in... - + rw = this->getWidth(); // width of a row of pixels t = (rw * this->getHeight()) - 1; // determine size of the frame memset(res, 0, sizeof(float) * (t + 1)); // clear output buffer (not all pixels will be written later) - + lres = (unsigned int *)res; // unsigned int pointer to output buffer (for bit level ops) limask = (unsigned int *)imask; // unsigned int pointer to input mask (for bit level ops) lomask = (unsigned int *)omask; // unsigned int pointer to output mask (for bit level ops) - - + + /* * The whole buffer is broken up into 4 parts. The four CORNERS, the FIRST and LAST rows, the * LEFT and RIGHT edges (excluding the corner pixels), and all OTHER rows. @@ -1213,17 +1213,17 @@ void DoubleEdgeMaskOperation::doDoubleEdgeMask(float *imask, float *omask, float // detect edges in all non-border pixels in the buffer do_allEdgeDetection(t, rw, limask, lomask, lres, res, rsize, isz, osz, gsz); } - + isz = rsize[0]; // set edge and gradient buffer sizes once again... osz = rsize[1]; // the sizes in rsize[] may have been modified gsz = rsize[2]; // by the do_*EdgeDetection() function. - + fsz = gsz + isz + osz; // calculate size of pixel index buffer needed gbuf = (unsigned short *)MEM_callocN(sizeof(unsigned short) * fsz * 2, "DEM"); // allocate edge/gradient pixel index buffer - + do_createEdgeLocationBuffer(t, rw, lres, res, gbuf, &innerEdgeOffset, &outerEdgeOffset, isz, gsz); do_fillGradientBuffer(rw, res, gbuf, isz, osz, gsz, innerEdgeOffset, outerEdgeOffset); - + MEM_freeN(gbuf); // free the gradient index buffer } } @@ -1267,7 +1267,7 @@ void *DoubleEdgeMaskOperation::initializeTileData(rcti *rect) { if (this->m_cachedInstance) return this->m_cachedInstance; - + lockMutex(); if (this->m_cachedInstance == NULL) { MemoryBuffer *innerMask = (MemoryBuffer *)this->m_inputInnerMask->initializeTileData(rect); @@ -1298,4 +1298,3 @@ void DoubleEdgeMaskOperation::deinitExecution() this->m_cachedInstance = NULL; } } - diff --git a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h index a12c44b02a16..1e5a3bb52a5b 100644 --- a/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h +++ b/source/blender/compositor/operations/COM_DoubleEdgeMaskOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_DoubleEdgeMaskOperation_h -#define _COM_DoubleEdgeMaskOperation_h +#ifndef __COM_DOUBLEEDGEMASKOPERATION_H__ +#define __COM_DOUBLEEDGEMASKOPERATION_H__ #include "COM_NodeOperation.h" @@ -43,12 +43,12 @@ class DoubleEdgeMaskOperation : public NodeOperation { * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -57,7 +57,7 @@ class DoubleEdgeMaskOperation : public NodeOperation { void *initializeTileData(rcti *rect); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); - + void setAdjecentOnly(bool adjecentOnly) { this->m_adjecentOnly = adjecentOnly; } void setKeepInside(bool keepInside) { this->m_keepInside = keepInside; } }; diff --git a/source/blender/compositor/operations/COM_EllipseMaskOperation.cpp b/source/blender/compositor/operations/COM_EllipseMaskOperation.cpp index 482473cbe1ff..f0293a02724b 100644 --- a/source/blender/compositor/operations/COM_EllipseMaskOperation.cpp +++ b/source/blender/compositor/operations/COM_EllipseMaskOperation.cpp @@ -48,18 +48,18 @@ void EllipseMaskOperation::executePixelSampled(float output[4], float x, float y { float inputMask[4]; float inputValue[4]; - + float rx = x / this->getWidth(); float ry = y / this->getHeight(); - + const float dy = (ry - this->m_data->y) / this->m_aspectRatio; const float dx = rx - this->m_data->x; rx = this->m_data->x + (this->m_cosine * dx + this->m_sine * dy); ry = this->m_data->y + (-this->m_sine * dx + this->m_cosine * dy); - + this->m_inputMask->readSampled(inputMask, x, y, sampler); this->m_inputValue->readSampled(inputValue, x, y, sampler); - + const float halfHeight = (this->m_data->height) / 2.0f; const float halfWidth = this->m_data->width / 2.0f; float sx = rx - this->m_data->x; @@ -68,9 +68,9 @@ void EllipseMaskOperation::executePixelSampled(float output[4], float x, float y float sy = ry - this->m_data->y; sy *= sy; const float ty = halfHeight * halfHeight; - + bool inside = ((sx / tx) + (sy / ty)) < 1.0f; - + switch (this->m_maskType) { case CMP_NODE_MASKTYPE_ADD: if (inside) { @@ -118,4 +118,3 @@ void EllipseMaskOperation::deinitExecution() this->m_inputMask = NULL; this->m_inputValue = NULL; } - diff --git a/source/blender/compositor/operations/COM_EllipseMaskOperation.h b/source/blender/compositor/operations/COM_EllipseMaskOperation.h index 419b2c2d63ba..59451d2046af 100644 --- a/source/blender/compositor/operations/COM_EllipseMaskOperation.h +++ b/source/blender/compositor/operations/COM_EllipseMaskOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_EllipseMaskOperation_h -#define _COM_EllipseMaskOperation_h +#ifndef __COM_ELLIPSEMASKOPERATION_H__ +#define __COM_ELLIPSEMASKOPERATION_H__ #include "COM_NodeOperation.h" @@ -32,34 +32,34 @@ class EllipseMaskOperation : public NodeOperation { */ SocketReader *m_inputMask; SocketReader *m_inputValue; - + float m_sine; float m_cosine; float m_aspectRatio; int m_maskType; - + NodeEllipseMask *m_data; public: EllipseMaskOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setData(NodeEllipseMask *data) { this->m_data = data; } void setMaskType(int maskType) { this->m_maskType = maskType; } - + }; #endif diff --git a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp index a223ac31e3d8..d570424cb694 100644 --- a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.cpp @@ -70,7 +70,7 @@ void FastGaussianBlurOperation::initExecution() BlurBaseOperation::initMutex(); } -void FastGaussianBlurOperation::deinitExecution() +void FastGaussianBlurOperation::deinitExecution() { if (this->m_iirgaus) { delete this->m_iirgaus; @@ -90,7 +90,7 @@ void *FastGaussianBlurOperation::initializeTileData(rcti *rect) int c; this->m_sx = this->m_data.sizex * this->m_size / 2.0f; this->m_sy = this->m_data.sizey * this->m_size / 2.0f; - + if ((this->m_sx == this->m_sy) && (this->m_sx > 0.0f)) { for (c = 0; c < COM_NUM_CHANNELS_COLOR; ++c) IIR_gauss(copy, this->m_sx, c, 3); @@ -121,18 +121,18 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign unsigned int i; float *buffer = src->getBuffer(); const unsigned int num_channels = src->get_num_channels(); - + // <0.5 not valid, though can have a possibly useful sort of sharpening effect if (sigma < 0.5f) return; - + if ((xy < 1) || (xy > 3)) xy = 3; - + // XXX The YVV macro defined below explicitly expects sources of at least 3x3 pixels, // so just skiping blur along faulty direction if src's def is below that limit! if (src_width < 3) xy &= ~1; if (src_height < 3) xy &= ~2; if (xy < 1) return; - + // see "Recursive Gabor Filtering" by Young/VanVliet // all factors here in double.prec. Required, because for single.prec it seems to blow up if sigma > ~200 if (sigma >= 3.556f) @@ -148,7 +148,7 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign // 0 & 3 unchanged cf[3] = q2 * q / sc; cf[0] = 1.0 - cf[1] - cf[2] - cf[3]; - + // Triggs/Sdika border corrections, // it seems to work, not entirely sure if it is actually totally correct, // Besides J.M.Geusebroek's anigauss.c (see http://www.science.uva.nl/~mark), @@ -166,7 +166,7 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign tsM[6] = sc * (cf[3] * cf[1] + cf[2] + cf[1] * cf[1] - cf[2] * cf[2]); tsM[7] = sc * (cf[1] * cf[2] + cf[3] * cf[2] * cf[2] - cf[1] * cf[3] * cf[3] - cf[3] * cf[3] * cf[3] - cf[3] * cf[2] + cf[3]); tsM[8] = sc * (cf[3] * (cf[1] + cf[3] * cf[2])); - + #define YVV(L) \ { \ W[0] = cf[0] * X[0] + cf[1] * X[0] + cf[2] * X[0] + cf[3] * X[0]; \ @@ -189,7 +189,7 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign Y[i] = cf[0] * W[i] + cf[1] * Y[i + 1] + cf[2] * Y[i + 2] + cf[3] * Y[i + 3]; \ } \ } (void)0 - + // intermediate buffers sz = max(src_width, src_height); X = (double *)MEM_callocN(sz * sizeof(double), "IIR_gauss X buf"); @@ -230,12 +230,12 @@ void FastGaussianBlurOperation::IIR_gauss(MemoryBuffer *src, float sigma, unsign } } } - + MEM_freeN(X); MEM_freeN(W); MEM_freeN(Y); #undef YVV - + } @@ -260,7 +260,7 @@ void FastGaussianBlurValueOperation::executePixel(float output[4], int x, int y, bool FastGaussianBlurValueOperation::determineDependingAreaOfInterest(rcti * /*input*/, ReadBufferOperation *readOperation, rcti *output) { rcti newInput; - + if (this->m_iirgaus) { return false; } @@ -279,7 +279,7 @@ void FastGaussianBlurValueOperation::initExecution() initMutex(); } -void FastGaussianBlurValueOperation::deinitExecution() +void FastGaussianBlurValueOperation::deinitExecution() { if (this->m_iirgaus) { delete this->m_iirgaus; @@ -322,4 +322,3 @@ void *FastGaussianBlurValueOperation::initializeTileData(rcti *rect) unlockMutex(); return this->m_iirgaus; } - diff --git a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h index 1cfaee3f537c..840849d61261 100644 --- a/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h +++ b/source/blender/compositor/operations/COM_FastGaussianBlurOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_FastGaussianBlurOperation_h -#define _COM_FastGaussianBlurOperation_h +#ifndef __COM_FASTGAUSSIANBLUROPERATION_H__ +#define __COM_FASTGAUSSIANBLUROPERATION_H__ #include "COM_BlurBaseOperation.h" #include "DNA_node_types.h" @@ -35,7 +35,7 @@ class FastGaussianBlurOperation : public BlurBaseOperation { FastGaussianBlurOperation(); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void executePixel(float output[4], int x, int y, void *data); - + static void IIR_gauss(MemoryBuffer *src, float sigma, unsigned int channel, unsigned int xy); void *initializeTileData(rcti *rect); void deinitExecution(); @@ -63,7 +63,7 @@ class FastGaussianBlurValueOperation : public NodeOperation { FastGaussianBlurValueOperation(); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void executePixel(float output[4], int x, int y, void *data); - + void *initializeTileData(rcti *rect); void deinitExecution(); void initExecution(); @@ -74,4 +74,3 @@ class FastGaussianBlurValueOperation : public NodeOperation { }; #endif - diff --git a/source/blender/compositor/operations/COM_FlipOperation.cpp b/source/blender/compositor/operations/COM_FlipOperation.cpp index 80e67a7297b5..c75201903ebe 100644 --- a/source/blender/compositor/operations/COM_FlipOperation.cpp +++ b/source/blender/compositor/operations/COM_FlipOperation.cpp @@ -46,14 +46,14 @@ void FlipOperation::executePixelSampled(float output[4], float x, float y, Pixel { float nx = this->m_flipX ? ((int)this->getWidth() - 1) - x : x; float ny = this->m_flipY ? ((int)this->getHeight() - 1) - y : y; - + this->m_inputOperation->readSampled(output, nx, ny, sampler); } bool FlipOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output) { rcti newInput; - + if (this->m_flipX) { const int w = (int)this->getWidth() - 1; newInput.xmax = (w - input->xmin) + 1; @@ -72,6 +72,6 @@ bool FlipOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOper newInput.ymin = input->ymin; newInput.ymax = input->ymax; } - + return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } diff --git a/source/blender/compositor/operations/COM_FlipOperation.h b/source/blender/compositor/operations/COM_FlipOperation.h index 3a7bf77f29b0..039f3af5064c 100644 --- a/source/blender/compositor/operations/COM_FlipOperation.h +++ b/source/blender/compositor/operations/COM_FlipOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_FlipOperation_h_ -#define _COM_FlipOperation_h_ +#ifndef __COM_FLIPOPERATION_H__ +#define __COM_FLIPOPERATION_H__ #include "COM_NodeOperation.h" @@ -34,7 +34,7 @@ class FlipOperation : public NodeOperation { FlipOperation(); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); void setFlipX(bool flipX) { this->m_flipX = flipX; } diff --git a/source/blender/compositor/operations/COM_GammaCorrectOperation.h b/source/blender/compositor/operations/COM_GammaCorrectOperation.h index b3f0cedce22c..e9b6691349b7 100644 --- a/source/blender/compositor/operations/COM_GammaCorrectOperation.h +++ b/source/blender/compositor/operations/COM_GammaCorrectOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GammaCorrectOperation_h -#define _COM_GammaCorrectOperation_h +#ifndef __COM_GAMMACORRECTOPERATION_H__ +#define __COM_GAMMACORRECTOPERATION_H__ #include "COM_NodeOperation.h" @@ -34,17 +34,17 @@ class GammaCorrectOperation : public NodeOperation { public: GammaCorrectOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -60,17 +60,17 @@ class GammaUncorrectOperation : public NodeOperation { public: GammaUncorrectOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_GammaOperation.cpp b/source/blender/compositor/operations/COM_GammaOperation.cpp index 79b70b5170ec..0cc0cbefd464 100644 --- a/source/blender/compositor/operations/COM_GammaOperation.cpp +++ b/source/blender/compositor/operations/COM_GammaOperation.cpp @@ -41,7 +41,7 @@ void GammaOperation::executePixelSampled(float output[4], float x, float y, Pixe { float inputValue[4]; float inputGamma[4]; - + this->m_inputProgram->readSampled(inputValue, x, y, sampler); this->m_inputGammaProgram->readSampled(inputGamma, x, y, sampler); const float gamma = inputGamma[0]; @@ -49,7 +49,7 @@ void GammaOperation::executePixelSampled(float output[4], float x, float y, Pixe output[0] = inputValue[0] > 0.0f ? powf(inputValue[0], gamma) : inputValue[0]; output[1] = inputValue[1] > 0.0f ? powf(inputValue[1], gamma) : inputValue[1]; output[2] = inputValue[2] > 0.0f ? powf(inputValue[2], gamma) : inputValue[2]; - + output[3] = inputValue[3]; } diff --git a/source/blender/compositor/operations/COM_GammaOperation.h b/source/blender/compositor/operations/COM_GammaOperation.h index 9243ece6b303..b51c86f7fd30 100644 --- a/source/blender/compositor/operations/COM_GammaOperation.h +++ b/source/blender/compositor/operations/COM_GammaOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GammaOperation_h -#define _COM_GammaOperation_h +#ifndef __COM_GAMMAOPERATION_H__ +#define __COM_GAMMAOPERATION_H__ #include "COM_NodeOperation.h" @@ -35,17 +35,17 @@ class GammaOperation : public NodeOperation { public: GammaOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp index 0fab888b9d92..c560257b859f 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.cpp @@ -56,7 +56,7 @@ void GaussianAlphaXBlurOperation::initExecution() if (this->m_sizeavailable) { float rad = max_ff(m_size * m_data.sizex, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_gausstab = BlurBaseOperation::make_gausstab(rad, m_filtersize); m_distbuf_inv = BlurBaseOperation::make_dist_fac_inverse(rad, m_filtersize, m_falloff); } @@ -68,7 +68,7 @@ void GaussianAlphaXBlurOperation::updateGauss() updateSize(); float rad = max_ff(m_size * m_data.sizex, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_gausstab = BlurBaseOperation::make_gausstab(rad, m_filtersize); } @@ -76,7 +76,7 @@ void GaussianAlphaXBlurOperation::updateGauss() updateSize(); float rad = max_ff(m_size * m_data.sizex, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_distbuf_inv = BlurBaseOperation::make_dist_fac_inverse(rad, m_filtersize, m_falloff); } } diff --git a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h index fc5b3384749d..985f56e3ef62 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianAlphaXBlurOperation.h @@ -21,8 +21,8 @@ * Campbell Barton */ -#ifndef _COM_GaussianAlphaXBlurOperation_h -#define _COM_GaussianAlphaXBlurOperation_h +#ifndef __COM_GAUSSIANALPHAXBLUROPERATION_H__ +#define __COM_GAUSSIANALPHAXBLUROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_BlurBaseOperation.h" @@ -41,7 +41,7 @@ class GaussianAlphaXBlurOperation : public BlurBaseOperation { * @brief the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * @brief initialize the execution */ @@ -51,7 +51,7 @@ class GaussianAlphaXBlurOperation : public BlurBaseOperation { * @brief Deinitialize the execution */ void deinitExecution(); - + void *initializeTileData(rcti *rect); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); diff --git a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp index b4e535cbf20d..b90320afdeb1 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.cpp @@ -56,7 +56,7 @@ void GaussianAlphaYBlurOperation::initExecution() if (this->m_sizeavailable) { float rad = max_ff(m_size * m_data.sizey, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_gausstab = BlurBaseOperation::make_gausstab(rad, m_filtersize); m_distbuf_inv = BlurBaseOperation::make_dist_fac_inverse(rad, m_filtersize, m_falloff); } @@ -68,7 +68,7 @@ void GaussianAlphaYBlurOperation::updateGauss() updateSize(); float rad = max_ff(m_size * m_data.sizey, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_gausstab = BlurBaseOperation::make_gausstab(rad, m_filtersize); } @@ -76,7 +76,7 @@ void GaussianAlphaYBlurOperation::updateGauss() updateSize(); float rad = max_ff(m_size * m_data.sizey, 0.0f); m_filtersize = min_ii(ceil(rad), MAX_GAUSSTAB_RADIUS); - + m_distbuf_inv = BlurBaseOperation::make_dist_fac_inverse(rad, m_filtersize, m_falloff); } } diff --git a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h index 4f2f2ec3fe4c..3935dcd65689 100644 --- a/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianAlphaYBlurOperation.h @@ -21,8 +21,8 @@ * Campbell Barton */ -#ifndef _COM_GaussianAlphaYBlurOperation_h -#define _COM_GaussianAlphaYBlurOperation_h +#ifndef __COM_GAUSSIANALPHAYBLUROPERATION_H__ +#define __COM_GAUSSIANALPHAYBLUROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_BlurBaseOperation.h" @@ -36,12 +36,12 @@ class GaussianAlphaYBlurOperation : public BlurBaseOperation { void updateGauss(); public: GaussianAlphaYBlurOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * @brief initialize the execution */ @@ -51,7 +51,7 @@ class GaussianAlphaYBlurOperation : public BlurBaseOperation { * Deinitialize the execution */ void deinitExecution(); - + void *initializeTileData(rcti *rect); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); diff --git a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp index c268cff557a4..bbcec45ea1f4 100644 --- a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.cpp @@ -70,18 +70,18 @@ void GaussianBokehBlurOperation::updateGauss() } radxf = this->m_size * (float)this->m_data.sizex; CLAMP(radxf, 0.0f, width / 2.0f); - + /* vertical */ radyf = this->m_size * (float)this->m_data.sizey; CLAMP(radyf, 0.0f, height / 2.0f); - + this->m_radx = ceil(radxf); this->m_rady = ceil(radyf); - + int ddwidth = 2 * this->m_radx + 1; int ddheight = 2 * this->m_rady + 1; n = ddwidth * ddheight; - + /* create a full filter image */ ddgauss = (float *)MEM_mallocN(sizeof(float) * n, __func__); dgauss = ddgauss; @@ -94,7 +94,7 @@ void GaussianBokehBlurOperation::updateGauss() float fi = (float)i * facx; float dist = sqrt(fj * fj + fi * fi); *dgauss = RE_filter_value(this->m_data.filtertype, dist); - + sum += *dgauss; } } @@ -109,7 +109,7 @@ void GaussianBokehBlurOperation::updateGauss() int center = m_rady * ddwidth + m_radx; ddgauss[center] = 1.0f; } - + this->m_gausstab = ddgauss; } } @@ -175,7 +175,7 @@ bool GaussianBokehBlurOperation::determineDependingAreaOfInterest(rcti *input, R sizeInput.xmax = 5; sizeInput.ymax = 5; NodeOperation *operation = this->getInputOperation(1); - + if (operation->determineDependingAreaOfInterest(&sizeInput, readOperation, output)) { return true; } @@ -233,8 +233,8 @@ void GaussianBlurReferenceOperation::initExecution() break; } } - - + + /* horizontal */ m_filtersizex = (float)this->m_data.sizex; int imgx = getWidth() / 2; @@ -307,7 +307,7 @@ void GaussianBlurReferenceOperation::executePixel(float output[4], int x, int y, for (i = minyr; i < maxyr; i++, srcd += COM_NUM_CHANNELS_COLOR * imgx) { src = srcd; for (j = minxr; j < maxxr; j++, src += COM_NUM_CHANNELS_COLOR) { - + val = gausstabcenty[i] * gausstabcentx[j]; sum += val; rval += val * src[0]; @@ -340,7 +340,7 @@ bool GaussianBlurReferenceOperation::determineDependingAreaOfInterest(rcti *inpu { rcti newInput; NodeOperation *operation = this->getInputOperation(1); - + if (operation->determineDependingAreaOfInterest(input, readOperation, output)) { return true; } @@ -354,4 +354,3 @@ bool GaussianBlurReferenceOperation::determineDependingAreaOfInterest(rcti *inpu return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } } - diff --git a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h index e483ffd4f2dc..9089838add58 100644 --- a/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianBokehBlurOperation.h @@ -40,19 +40,19 @@ class GaussianBokehBlurOperation : public BlurBaseOperation { * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; class GaussianBlurReferenceOperation : public BlurBaseOperation { private: float **m_maintabs; - + void updateGauss(); int m_filtersizex; int m_filtersizey; @@ -67,12 +67,12 @@ class GaussianBlurReferenceOperation : public BlurBaseOperation { * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; diff --git a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp index ef438e1d3641..3eafc7a1bfe6 100644 --- a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp @@ -170,7 +170,7 @@ void GaussianXBlurOperation::deinitExecution() bool GaussianXBlurOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output) { rcti newInput; - + if (!this->m_sizeavailable) { rcti sizeInput; sizeInput.xmin = 0; diff --git a/source/blender/compositor/operations/COM_GaussianXBlurOperation.h b/source/blender/compositor/operations/COM_GaussianXBlurOperation.h index 46a5c4e3c039..88d8ed44de66 100644 --- a/source/blender/compositor/operations/COM_GaussianXBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianXBlurOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GaussianXBlurOperation_h -#define _COM_GaussianXBlurOperation_h +#ifndef __COM_GAUSSIANXBLUROPERATION_H__ +#define __COM_GAUSSIANXBLUROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_BlurBaseOperation.h" @@ -55,7 +55,7 @@ class GaussianXBlurOperation : public BlurBaseOperation { * @brief Deinitialize the execution */ void deinitExecution(); - + void *initializeTileData(rcti *rect); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); diff --git a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp index 6f8f96a63441..45089598af50 100644 --- a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp @@ -172,7 +172,7 @@ void GaussianYBlurOperation::deinitExecution() bool GaussianYBlurOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output) { rcti newInput; - + if (!m_sizeavailable) { rcti sizeInput; sizeInput.xmin = 0; diff --git a/source/blender/compositor/operations/COM_GaussianYBlurOperation.h b/source/blender/compositor/operations/COM_GaussianYBlurOperation.h index ca3172bd5057..5df77eb28ceb 100644 --- a/source/blender/compositor/operations/COM_GaussianYBlurOperation.h +++ b/source/blender/compositor/operations/COM_GaussianYBlurOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GaussianYBlurOperation_h -#define _COM_GaussianYBlurOperation_h +#ifndef __COM_GAUSSIANYBLUROPERATION_H__ +#define __COM_GAUSSIANYBLUROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_BlurBaseOperation.h" @@ -35,7 +35,7 @@ class GaussianYBlurOperation : public BlurBaseOperation { void updateGauss(); public: GaussianYBlurOperation(); - + /** * the inner loop of this program */ @@ -55,7 +55,7 @@ class GaussianYBlurOperation : public BlurBaseOperation { * Deinitialize the execution */ void deinitExecution(); - + void *initializeTileData(rcti *rect); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); diff --git a/source/blender/compositor/operations/COM_GlareBaseOperation.h b/source/blender/compositor/operations/COM_GlareBaseOperation.h index 3f0893d895f0..3fa676f4d316 100644 --- a/source/blender/compositor/operations/COM_GlareBaseOperation.h +++ b/source/blender/compositor/operations/COM_GlareBaseOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareBaseOperation_h -#define _COM_GlareBaseOperation_h +#ifndef __COM_GLAREBASEOPERATION_H__ +#define __COM_GLAREBASEOPERATION_H__ #include "COM_SingleThreadedOperation.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/operations/COM_GlareFogGlowOperation.h b/source/blender/compositor/operations/COM_GlareFogGlowOperation.h index 1231185a21a7..5bfe40d3a233 100644 --- a/source/blender/compositor/operations/COM_GlareFogGlowOperation.h +++ b/source/blender/compositor/operations/COM_GlareFogGlowOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareFogGlowOperation_h -#define _COM_GlareFogGlowOperation_h +#ifndef __COM_GLAREFOGGLOWOPERATION_H__ +#define __COM_GLAREFOGGLOWOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_GlareBaseOperation.h" diff --git a/source/blender/compositor/operations/COM_GlareGhostOperation.h b/source/blender/compositor/operations/COM_GlareGhostOperation.h index 7ce1048efe92..bff13d1bccec 100644 --- a/source/blender/compositor/operations/COM_GlareGhostOperation.h +++ b/source/blender/compositor/operations/COM_GlareGhostOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareGhostOperation_h -#define _COM_GlareGhostOperation_h +#ifndef __COM_GLAREGHOSTOPERATION_H__ +#define __COM_GLAREGHOSTOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_GlareBaseOperation.h" diff --git a/source/blender/compositor/operations/COM_GlareSimpleStarOperation.h b/source/blender/compositor/operations/COM_GlareSimpleStarOperation.h index 440f3ba147a2..7f0cf7be46af 100644 --- a/source/blender/compositor/operations/COM_GlareSimpleStarOperation.h +++ b/source/blender/compositor/operations/COM_GlareSimpleStarOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareSimpleStarOperation_h -#define _COM_GlareSimpleStarOperation_h +#ifndef __COM_GLARESIMPLESTAROPERATION_H__ +#define __COM_GLARESIMPLESTAROPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_GlareBaseOperation.h" diff --git a/source/blender/compositor/operations/COM_GlareStreaksOperation.h b/source/blender/compositor/operations/COM_GlareStreaksOperation.h index e629ac116234..0671c0b25574 100644 --- a/source/blender/compositor/operations/COM_GlareStreaksOperation.h +++ b/source/blender/compositor/operations/COM_GlareStreaksOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareStreaksOperation_h -#define _COM_GlareStreaksOperation_h +#ifndef __COM_GLARESTREAKSOPERATION_H__ +#define __COM_GLARESTREAKSOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_GlareBaseOperation.h" diff --git a/source/blender/compositor/operations/COM_GlareThresholdOperation.cpp b/source/blender/compositor/operations/COM_GlareThresholdOperation.cpp index f54e75a6b353..62ebe601d8d7 100644 --- a/source/blender/compositor/operations/COM_GlareThresholdOperation.cpp +++ b/source/blender/compositor/operations/COM_GlareThresholdOperation.cpp @@ -49,7 +49,7 @@ void GlareThresholdOperation::initExecution() void GlareThresholdOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) { const float threshold = this->m_settings->threshold; - + this->m_inputProgram->readSampled(output, x, y, sampler); if (IMB_colormanagement_get_luminance(output) >= threshold) { output[0] -= threshold; diff --git a/source/blender/compositor/operations/COM_GlareThresholdOperation.h b/source/blender/compositor/operations/COM_GlareThresholdOperation.h index 7760a19251b4..9a922a5889c1 100644 --- a/source/blender/compositor/operations/COM_GlareThresholdOperation.h +++ b/source/blender/compositor/operations/COM_GlareThresholdOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_GlareScaleOperation_h -#define _COM_GlareScaleOperation_h +#ifndef __COM_GLARETHRESHOLDOPERATION_H__ +#define __COM_GLARETHRESHOLDOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_lamp_types.h" @@ -57,7 +57,7 @@ class GlareThresholdOperation : public NodeOperation { void setGlareSettings(NodeGlare *settings) { this->m_settings = settings; } - + void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); }; #endif diff --git a/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h b/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h index 06d785f2c518..2a749fef1f8f 100644 --- a/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h +++ b/source/blender/compositor/operations/COM_HueSaturationValueCorrectOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_HueSaturationValueCorrectOperation_h -#define _COM_HueSaturationValueCorrectOperation_h +#ifndef __COM_HUESATURATIONVALUECORRECTOPERATION_H__ +#define __COM_HUESATURATIONVALUECORRECTOPERATION_H__ #include "COM_NodeOperation.h" #include "COM_CurveBaseOperation.h" @@ -33,17 +33,17 @@ class HueSaturationValueCorrectOperation : public CurveBaseOperation { SocketReader *m_inputProgram; public: HueSaturationValueCorrectOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_IDMaskOperation.h b/source/blender/compositor/operations/COM_IDMaskOperation.h index 89f9855303c0..53c2fd154a00 100644 --- a/source/blender/compositor/operations/COM_IDMaskOperation.h +++ b/source/blender/compositor/operations/COM_IDMaskOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_IDMaskOperation_h -#define _COM_IDMaskOperation_h +#ifndef __COM_IDMASKOPERATION_H__ +#define __COM_IDMASKOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_ImageOperation.h b/source/blender/compositor/operations/COM_ImageOperation.h index 1f9a9a45af14..60172eb64136 100644 --- a/source/blender/compositor/operations/COM_ImageOperation.h +++ b/source/blender/compositor/operations/COM_ImageOperation.h @@ -21,8 +21,8 @@ */ -#ifndef _COM_ImageOperation_h -#define _COM_ImageOperation_h +#ifndef __COM_IMAGEOPERATION_H__ +#define __COM_IMAGEOPERATION_H__ #include "COM_NodeOperation.h" #include "BLI_listbase.h" @@ -57,11 +57,11 @@ class BaseImageOperation : public NodeOperation { * Determine the output resolution. The resolution is retrieved from the Renderer */ void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + virtual ImBuf *getImBuf(); public: - + void initExecution(); void deinitExecution(); void setImage(Image *image) { this->m_image = image; } diff --git a/source/blender/compositor/operations/COM_InpaintOperation.cpp b/source/blender/compositor/operations/COM_InpaintOperation.cpp index 11896b1d78c3..f22270108aec 100644 --- a/source/blender/compositor/operations/COM_InpaintOperation.cpp +++ b/source/blender/compositor/operations/COM_InpaintOperation.cpp @@ -87,7 +87,7 @@ float *InpaintSimpleOperation::get_pixel(int x, int y) x * COM_NUM_CHANNELS_COLOR]; } -int InpaintSimpleOperation::mdist(int x, int y) +int InpaintSimpleOperation::mdist(int x, int y) { int width = this->getWidth(); @@ -103,7 +103,7 @@ bool InpaintSimpleOperation::next_pixel(int &x, int &y, int & curr, int iters) if (curr >= this->m_area_size) { return false; } - + int r = this->m_pixelorder[curr++]; x = r % width; @@ -112,11 +112,11 @@ bool InpaintSimpleOperation::next_pixel(int &x, int &y, int & curr, int iters) if (this->mdist(x, y) > iters) { return false; } - + return true; } -void InpaintSimpleOperation::calc_manhatten_distance() +void InpaintSimpleOperation::calc_manhatten_distance() { int width = this->getWidth(); int height = this->getHeight(); @@ -131,9 +131,9 @@ void InpaintSimpleOperation::calc_manhatten_distance() /* no need to clamp here */ if (this->get_pixel(i, j)[3] < 1.0f) { r = width + height; - if (i > 0) + if (i > 0) r = min_ii(r, m[j * width + i - 1] + 1); - if (j > 0) + if (j > 0) r = min_ii(r, m[(j - 1) * width + i] + 1); } m[j * width + i] = r; @@ -143,27 +143,27 @@ void InpaintSimpleOperation::calc_manhatten_distance() for (int j = height - 1; j >= 0; j--) { for (int i = width - 1; i >= 0; i--) { int r = m[j * width + i]; - - if (i + 1 < width) + + if (i + 1 < width) r = min_ii(r, m[j * width + i + 1] + 1); - if (j + 1 < height) + if (j + 1 < height) r = min_ii(r, m[(j + 1) * width + i] + 1); - + m[j * width + i] = r; - + offsets[r]++; } } - + offsets[0] = 0; - + for (int i = 1; i < width + height + 1; i++) { offsets[i] += offsets[i - 1]; } - + this->m_area_size = offsets[width + height]; this->m_pixelorder = (int *)MEM_mallocN(sizeof(int) * this->m_area_size, __func__); - + for (int i = 0; i < width * height; i++) { if (m[i] > 0) { this->m_pixelorder[offsets[m[i] - 1]++] = i; @@ -230,7 +230,7 @@ void *InpaintSimpleOperation::initializeTileData(rcti *rect) int curr = 0; int x, y; - + while (this->next_pixel(x, y, curr, this->m_iterations)) { this->pix_step(x, y); } @@ -275,13 +275,12 @@ bool InpaintSimpleOperation::determineDependingAreaOfInterest(rcti * /*input*/, } else { rcti newInput; - + newInput.xmax = getWidth(); newInput.xmin = 0; newInput.ymax = getHeight(); newInput.ymin = 0; - + return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } } - diff --git a/source/blender/compositor/operations/COM_InpaintOperation.h b/source/blender/compositor/operations/COM_InpaintOperation.h index 9ddcac93c5cc..bd430a3690c0 100644 --- a/source/blender/compositor/operations/COM_InpaintOperation.h +++ b/source/blender/compositor/operations/COM_InpaintOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_InpaintOperation_h -#define _COM_InpaintOperation_h +#ifndef __COM_INPAINTOPERATION_H__ +#define __COM_INPAINTOPERATION_H__ #include "COM_NodeOperation.h" class InpaintSimpleOperation : public NodeOperation { @@ -30,9 +30,9 @@ class InpaintSimpleOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputImageProgram; - + int m_iterations; - + float *m_cached_buffer; bool m_cached_buffer_ready; @@ -41,25 +41,25 @@ class InpaintSimpleOperation : public NodeOperation { short *m_manhatten_distance; public: InpaintSimpleOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); - + void setIterations(int iterations) { this->m_iterations = iterations; } - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); private: diff --git a/source/blender/compositor/operations/COM_InvertOperation.cpp b/source/blender/compositor/operations/COM_InvertOperation.cpp index 833b91ac1e3d..ac0c91394e80 100644 --- a/source/blender/compositor/operations/COM_InvertOperation.cpp +++ b/source/blender/compositor/operations/COM_InvertOperation.cpp @@ -45,10 +45,10 @@ void InvertOperation::executePixelSampled(float output[4], float x, float y, Pix float inputColor[4]; this->m_inputValueProgram->readSampled(inputValue, x, y, sampler); this->m_inputColorProgram->readSampled(inputColor, x, y, sampler); - + const float value = inputValue[0]; const float invertedValue = 1.0f - value; - + if (this->m_color) { output[0] = (1.0f - inputColor[0]) * value + inputColor[0] * invertedValue; output[1] = (1.0f - inputColor[1]) * value + inputColor[1] * invertedValue; @@ -57,7 +57,7 @@ void InvertOperation::executePixelSampled(float output[4], float x, float y, Pix else { copy_v3_v3(output, inputColor); } - + if (this->m_alpha) output[3] = (1.0f - inputColor[3]) * value + inputColor[3] * invertedValue; else @@ -70,4 +70,3 @@ void InvertOperation::deinitExecution() this->m_inputValueProgram = NULL; this->m_inputColorProgram = NULL; } - diff --git a/source/blender/compositor/operations/COM_InvertOperation.h b/source/blender/compositor/operations/COM_InvertOperation.h index 977feeb87afd..2aeb33a76f58 100644 --- a/source/blender/compositor/operations/COM_InvertOperation.h +++ b/source/blender/compositor/operations/COM_InvertOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_InvertOperation_h -#define _COM_InvertOperation_h +#ifndef __COM_INVERTOPERATION_H__ +#define __COM_INVERTOPERATION_H__ #include "COM_NodeOperation.h" @@ -32,28 +32,28 @@ class InvertOperation : public NodeOperation { */ SocketReader *m_inputValueProgram; SocketReader *m_inputColorProgram; - + bool m_alpha; bool m_color; public: InvertOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setColor(bool color) { this->m_color = color; } void setAlpha(bool alpha) { this->m_alpha = alpha; } }; diff --git a/source/blender/compositor/operations/COM_KeyingBlurOperation.h b/source/blender/compositor/operations/COM_KeyingBlurOperation.h index a1c56cc9c079..2bea3ca86166 100644 --- a/source/blender/compositor/operations/COM_KeyingBlurOperation.h +++ b/source/blender/compositor/operations/COM_KeyingBlurOperation.h @@ -21,8 +21,8 @@ * Sergey Sharybin */ -#ifndef _COM_KeyingBlurOperation_h -#define _COM_KeyingBlurOperation_h +#ifndef __COM_KEYINGBLUROPERATION_H__ +#define __COM_KEYINGBLUROPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_KeyingClipOperation.h b/source/blender/compositor/operations/COM_KeyingClipOperation.h index d79bd14b900c..e0571bf15cd7 100644 --- a/source/blender/compositor/operations/COM_KeyingClipOperation.h +++ b/source/blender/compositor/operations/COM_KeyingClipOperation.h @@ -21,8 +21,8 @@ * Sergey Sharybin */ -#ifndef _COM_KeyingClipOperation_h -#define _COM_KeyingClipOperation_h +#ifndef __COM_KEYINGCLIPOPERATION_H__ +#define __COM_KEYINGCLIPOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_KeyingDespillOperation.h b/source/blender/compositor/operations/COM_KeyingDespillOperation.h index da9924d5b4b2..6b7fc82367bf 100644 --- a/source/blender/compositor/operations/COM_KeyingDespillOperation.h +++ b/source/blender/compositor/operations/COM_KeyingDespillOperation.h @@ -21,8 +21,8 @@ * Sergey Sharybin */ -#ifndef _COM_KeyingDespillOperation_h -#define _COM_KeyingDespillOperation_h +#ifndef __COM_KEYINGDESPILLOPERATION_H__ +#define __COM_KEYINGDESPILLOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_KeyingOperation.h b/source/blender/compositor/operations/COM_KeyingOperation.h index e4542e2c6dd9..a9f3034f6d17 100644 --- a/source/blender/compositor/operations/COM_KeyingOperation.h +++ b/source/blender/compositor/operations/COM_KeyingOperation.h @@ -22,8 +22,8 @@ */ -#ifndef _COM_KeyingOperation_h -#define _COM_KeyingOperation_h +#ifndef __COM_KEYINGOPERATION_H__ +#define __COM_KEYINGOPERATION_H__ #include diff --git a/source/blender/compositor/operations/COM_KeyingScreenOperation.h b/source/blender/compositor/operations/COM_KeyingScreenOperation.h index 45195b1e98da..25a3dcb6897e 100644 --- a/source/blender/compositor/operations/COM_KeyingScreenOperation.h +++ b/source/blender/compositor/operations/COM_KeyingScreenOperation.h @@ -22,8 +22,8 @@ */ -#ifndef _COM_KeyingScreenOperation_h -#define _COM_KeyingScreenOperation_h +#ifndef __COM_KEYINGSCREENOPERATION_H__ +#define __COM_KEYINGSCREENOPERATION_H__ #include diff --git a/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp b/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp index 1401ab56fbd9..391d6f8d9e93 100644 --- a/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp +++ b/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp @@ -54,11 +54,11 @@ void LuminanceMatteOperation::executePixelSampled(float output[4], float x, floa const float luminance = IMB_colormanagement_get_luminance(inColor); float alpha; - + /* one line thread-friend algorithm: * output[0] = min(inputValue[3], min(1.0f, max(0.0f, ((luminance - low) / (high - low)))); */ - + /* test range */ if (luminance > high) { alpha = 1.0f; @@ -77,4 +77,3 @@ void LuminanceMatteOperation::executePixelSampled(float output[4], float x, floa /* don't make something that was more transparent less transparent */ output[0] = min_ff(alpha, inColor[3]); } - diff --git a/source/blender/compositor/operations/COM_LuminanceMatteOperation.h b/source/blender/compositor/operations/COM_LuminanceMatteOperation.h index 93051f52228e..64d4638c5cd8 100644 --- a/source/blender/compositor/operations/COM_LuminanceMatteOperation.h +++ b/source/blender/compositor/operations/COM_LuminanceMatteOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_LuminanceMatteOperation_h -#define _COM_LuminanceMatteOperation_h +#ifndef __COM_LUMINANCEMATTEOPERATION_H__ +#define __COM_LUMINANCEMATTEOPERATION_H__ #include "COM_MixOperation.h" @@ -37,15 +37,15 @@ class LuminanceMatteOperation : public NodeOperation { * Default constructor */ LuminanceMatteOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); - + void setSettings(NodeChroma *nodeChroma) { this->m_settings = nodeChroma; } }; #endif diff --git a/source/blender/compositor/operations/COM_MapRangeOperation.cpp b/source/blender/compositor/operations/COM_MapRangeOperation.cpp index 6124a53d5b92..f5d3b1461968 100644 --- a/source/blender/compositor/operations/COM_MapRangeOperation.cpp +++ b/source/blender/compositor/operations/COM_MapRangeOperation.cpp @@ -58,7 +58,7 @@ void MapRangeOperation::executePixelSampled(float output[4], float x, float y, P this->m_sourceMaxOperation->readSampled(inputs + 2, x, y, sampler); this->m_destMinOperation->readSampled(inputs + 3, x, y, sampler); this->m_destMaxOperation->readSampled(inputs + 4, x, y, sampler); - + value = inputs[0]; source_min = inputs[1]; source_max = inputs[2]; diff --git a/source/blender/compositor/operations/COM_MapRangeOperation.h b/source/blender/compositor/operations/COM_MapRangeOperation.h index 48ecad9d2261..6598c89a09ca 100644 --- a/source/blender/compositor/operations/COM_MapRangeOperation.h +++ b/source/blender/compositor/operations/COM_MapRangeOperation.h @@ -20,8 +20,8 @@ * Daniel Salazar */ -#ifndef _COM_MapRangeOperation_h -#define _COM_MapRangeOperation_h +#ifndef __COM_MAPRANGEOPERATION_H__ +#define __COM_MAPRANGEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_texture_types.h" @@ -46,26 +46,26 @@ class MapRangeOperation : public NodeOperation { * Default constructor */ MapRangeOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + /** * Clamp the output */ void setUseClamp(bool value) { this->m_useClamp = value; } - + }; #endif diff --git a/source/blender/compositor/operations/COM_MapUVOperation.cpp b/source/blender/compositor/operations/COM_MapUVOperation.cpp index 0112f4bbf215..9e8b28e871e8 100644 --- a/source/blender/compositor/operations/COM_MapUVOperation.cpp +++ b/source/blender/compositor/operations/COM_MapUVOperation.cpp @@ -54,7 +54,7 @@ void MapUVOperation::executePixelSampled(float output[4], float x, float y, Pixe /* EWA filtering */ this->m_inputColorProgram->readFiltered(output, uv[0], uv[1], deriv[0], deriv[1]); - + /* UV to alpha threshold */ const float threshold = this->m_alpha * 0.05f; /* XXX alpha threshold is used to fade out pixels on boundaries with invalid derivatives. @@ -174,4 +174,3 @@ bool MapUVOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOpe return false; } - diff --git a/source/blender/compositor/operations/COM_MapUVOperation.h b/source/blender/compositor/operations/COM_MapUVOperation.h index 796ee9526072..599a07e1afa7 100644 --- a/source/blender/compositor/operations/COM_MapUVOperation.h +++ b/source/blender/compositor/operations/COM_MapUVOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_MapUVOperation_h -#define _COM_MapUVOperation_h +#ifndef __COM_MAPUVOPERATION_H__ +#define __COM_MAPUVOPERATION_H__ #include "COM_NodeOperation.h" @@ -33,7 +33,7 @@ class MapUVOperation : public NodeOperation { SocketReader *m_inputColorProgram; float m_alpha; - + public: MapUVOperation(); @@ -53,7 +53,7 @@ class MapUVOperation : public NodeOperation { * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_MapValueOperation.cpp b/source/blender/compositor/operations/COM_MapValueOperation.cpp index 59d4d836b1b2..afe3961dbf14 100644 --- a/source/blender/compositor/operations/COM_MapValueOperation.cpp +++ b/source/blender/compositor/operations/COM_MapValueOperation.cpp @@ -46,7 +46,7 @@ void MapValueOperation::executePixelSampled(float output[4], float x, float y, P if (texmap->flag & TEXMAP_CLIP_MAX) if (value > texmap->max[0]) value = texmap->max[0]; - + output[0] = value; } diff --git a/source/blender/compositor/operations/COM_MapValueOperation.h b/source/blender/compositor/operations/COM_MapValueOperation.h index ba19e76f4db7..33513c6f39ce 100644 --- a/source/blender/compositor/operations/COM_MapValueOperation.h +++ b/source/blender/compositor/operations/COM_MapValueOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MapValueOperation_h -#define _COM_MapValueOperation_h +#ifndef __COM_MAPVALUEOPERATION_H__ +#define __COM_MAPVALUEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_texture_types.h" @@ -41,26 +41,26 @@ class MapValueOperation : public NodeOperation { * Default constructor */ MapValueOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ void deinitExecution(); - + /** * @brief set the TexMapping settings */ void setSettings(TexMapping *settings) { this->m_settings = settings; } - + }; #endif diff --git a/source/blender/compositor/operations/COM_MaskOperation.h b/source/blender/compositor/operations/COM_MaskOperation.h index 522b873e167d..a586a91682ea 100644 --- a/source/blender/compositor/operations/COM_MaskOperation.h +++ b/source/blender/compositor/operations/COM_MaskOperation.h @@ -21,8 +21,8 @@ * Sergey Sharybin */ -#ifndef _COM_MaskOperation_h -#define _COM_MaskOperation_h +#ifndef __COM_MASKOPERATION_H__ +#define __COM_MASKOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_MathBaseOperation.cpp b/source/blender/compositor/operations/COM_MathBaseOperation.cpp index bb6e1f9da8d1..99385a5073a7 100644 --- a/source/blender/compositor/operations/COM_MathBaseOperation.cpp +++ b/source/blender/compositor/operations/COM_MathBaseOperation.cpp @@ -76,10 +76,10 @@ void MathAddOperation::executePixelSampled(float output[4], float x, float y, Pi { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = inputValue1[0] + inputValue2[0]; clampIfNeeded(output); @@ -89,10 +89,10 @@ void MathSubtractOperation::executePixelSampled(float output[4], float x, float { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = inputValue1[0] - inputValue2[0]; clampIfNeeded(output); @@ -102,10 +102,10 @@ void MathMultiplyOperation::executePixelSampled(float output[4], float x, float { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = inputValue1[0] * inputValue2[0]; clampIfNeeded(output); @@ -115,10 +115,10 @@ void MathDivideOperation::executePixelSampled(float output[4], float x, float y, { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue2[0] == 0) /* We don't want to divide by zero. */ output[0] = 0.0; else @@ -131,10 +131,10 @@ void MathSineOperation::executePixelSampled(float output[4], float x, float y, P { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = sin(inputValue1[0]); clampIfNeeded(output); @@ -144,10 +144,10 @@ void MathCosineOperation::executePixelSampled(float output[4], float x, float y, { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = cos(inputValue1[0]); clampIfNeeded(output); @@ -157,10 +157,10 @@ void MathTangentOperation::executePixelSampled(float output[4], float x, float y { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = tan(inputValue1[0]); clampIfNeeded(output); @@ -170,10 +170,10 @@ void MathArcSineOperation::executePixelSampled(float output[4], float x, float y { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue1[0] <= 1 && inputValue1[0] >= -1) output[0] = asin(inputValue1[0]); else @@ -186,10 +186,10 @@ void MathArcCosineOperation::executePixelSampled(float output[4], float x, float { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue1[0] <= 1 && inputValue1[0] >= -1) output[0] = acos(inputValue1[0]); else @@ -202,10 +202,10 @@ void MathArcTangentOperation::executePixelSampled(float output[4], float x, floa { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = atan(inputValue1[0]); clampIfNeeded(output); @@ -215,10 +215,10 @@ void MathPowerOperation::executePixelSampled(float output[4], float x, float y, { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue1[0] >= 0) { output[0] = pow(inputValue1[0], inputValue2[0]); } @@ -240,10 +240,10 @@ void MathLogarithmOperation::executePixelSampled(float output[4], float x, float { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue1[0] > 0 && inputValue2[0] > 0) output[0] = log(inputValue1[0]) / log(inputValue2[0]); else @@ -256,10 +256,10 @@ void MathMinimumOperation::executePixelSampled(float output[4], float x, float y { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = min(inputValue1[0], inputValue2[0]); clampIfNeeded(output); @@ -269,10 +269,10 @@ void MathMaximumOperation::executePixelSampled(float output[4], float x, float y { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = max(inputValue1[0], inputValue2[0]); clampIfNeeded(output); @@ -282,10 +282,10 @@ void MathRoundOperation::executePixelSampled(float output[4], float x, float y, { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = round(inputValue1[0]); clampIfNeeded(output); @@ -295,10 +295,10 @@ void MathLessThanOperation::executePixelSampled(float output[4], float x, float { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = inputValue1[0] < inputValue2[0] ? 1.0f : 0.0f; clampIfNeeded(output); @@ -308,10 +308,10 @@ void MathGreaterThanOperation::executePixelSampled(float output[4], float x, flo { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + output[0] = inputValue1[0] > inputValue2[0] ? 1.0f : 0.0f; clampIfNeeded(output); @@ -321,10 +321,10 @@ void MathModuloOperation::executePixelSampled(float output[4], float x, float y, { float inputValue1[4]; float inputValue2[4]; - + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); this->m_inputValue2Operation->readSampled(inputValue2, x, y, sampler); - + if (inputValue2[0] == 0) output[0] = 0.0; else @@ -355,4 +355,51 @@ void MathArcTan2Operation::executePixelSampled(float output[4], float x, float y output[0] = atan2(inputValue1[0], inputValue2[0]); clampIfNeeded(output); -} \ No newline at end of file +} + +void MathFloorOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) +{ + float inputValue1[4]; + + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); + + output[0] = floor(inputValue1[0]); + + clampIfNeeded(output); +} + +void MathCeilOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) +{ + float inputValue1[4]; + + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); + + output[0] = ceil(inputValue1[0]); + + clampIfNeeded(output); +} + +void MathFractOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) +{ + float inputValue1[4]; + + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); + + output[0] = inputValue1[0] - floor(inputValue1[0]); + + clampIfNeeded(output); +} + +void MathSqrtOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) +{ + float inputValue1[4]; + + this->m_inputValue1Operation->readSampled(inputValue1, x, y, sampler); + + if (inputValue1[0] > 0) + output[0] = sqrt(inputValue1[0]); + else + output[0] = 0.0f; + + clampIfNeeded(output); +} diff --git a/source/blender/compositor/operations/COM_MathBaseOperation.h b/source/blender/compositor/operations/COM_MathBaseOperation.h index 862783fff5d2..54fd3c5d2b92 100644 --- a/source/blender/compositor/operations/COM_MathBaseOperation.h +++ b/source/blender/compositor/operations/COM_MathBaseOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MathBaseOperation_h -#define _COM_MathBaseOperation_h +#ifndef __COM_MATHBASEOPERATION_H__ +#define __COM_MATHBASEOPERATION_H__ #include "COM_NodeOperation.h" @@ -51,12 +51,12 @@ class MathBaseOperation : public NodeOperation { * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler) = 0; - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -175,4 +175,28 @@ class MathArcTan2Operation : public MathBaseOperation { void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); }; +class MathFloorOperation : public MathBaseOperation { +public: + MathFloorOperation() : MathBaseOperation() {} + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); +}; + +class MathCeilOperation : public MathBaseOperation { +public: + MathCeilOperation() : MathBaseOperation() {} + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); +}; + +class MathFractOperation : public MathBaseOperation { +public: + MathFractOperation() : MathBaseOperation() {} + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); +}; + +class MathSqrtOperation : public MathBaseOperation { +public: + MathSqrtOperation() : MathBaseOperation() {} + void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); +}; + #endif diff --git a/source/blender/compositor/operations/COM_MixOperation.cpp b/source/blender/compositor/operations/COM_MixOperation.cpp index 314e16895f36..0acbe63e20e3 100644 --- a/source/blender/compositor/operations/COM_MixOperation.cpp +++ b/source/blender/compositor/operations/COM_MixOperation.cpp @@ -53,11 +53,11 @@ void MixBaseOperation::executePixelSampled(float output[4], float x, float y, Pi float inputColor1[4]; float inputColor2[4]; float inputValue[4]; - + this->m_inputValueOperation->readSampled(inputValue, x, y, sampler); this->m_inputColor1Operation->readSampled(inputColor1, x, y, sampler); this->m_inputColor2Operation->readSampled(inputColor2, x, y, sampler); - + float value = inputValue[0]; if (this->useValueAlphaMultiply()) { value *= inputColor2[3]; @@ -147,7 +147,7 @@ void MixBlendOperation::executePixelSampled(float output[4], float x, float y, P this->m_inputColor1Operation->readSampled(inputColor1, x, y, sampler); this->m_inputColor2Operation->readSampled(inputColor2, x, y, sampler); value = inputValue[0]; - + if (this->useValueAlphaMultiply()) { value *= inputColor2[3]; } diff --git a/source/blender/compositor/operations/COM_MixOperation.h b/source/blender/compositor/operations/COM_MixOperation.h index f375a47f0878..9063635fda0a 100644 --- a/source/blender/compositor/operations/COM_MixOperation.h +++ b/source/blender/compositor/operations/COM_MixOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MixBaseOperation_h -#define _COM_MixBaseOperation_h +#ifndef __COM_MIXOPERATION_H__ +#define __COM_MIXOPERATION_H__ #include "COM_NodeOperation.h" @@ -50,23 +50,23 @@ class MixBaseOperation : public NodeOperation { CLAMP(color[3], 0.0f, 1.0f); } } - + public: /** * Default constructor */ MixBaseOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -74,7 +74,7 @@ class MixBaseOperation : public NodeOperation { void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + void setUseValueAlphaMultiply(const bool value) { this->m_valueAlphaMultiply = value; } inline bool useValueAlphaMultiply() { return this->m_valueAlphaMultiply; } void setUseClamp(bool value) { this->m_useClamp = value; } diff --git a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp index 5f8c3ef435cb..c1c159f80a0c 100644 --- a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp +++ b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp @@ -87,4 +87,3 @@ void MovieClipAttributeOperation::determineResolution( resolution[0] = preferredResolution[0]; resolution[1] = preferredResolution[1]; } - diff --git a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h index 436b89a0dfba..9ac38da55d34 100644 --- a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h +++ b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_MovieClipAttributeOperation_h -#define _COM_MovieClipAttributeOperation_h +#ifndef __COM_MOVIECLIPATTRIBUTEOPERATION_H__ +#define __COM_MOVIECLIPATTRIBUTEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_movieclip_types.h" diff --git a/source/blender/compositor/operations/COM_MovieClipOperation.h b/source/blender/compositor/operations/COM_MovieClipOperation.h index 93452752234f..2b696cd5df6a 100644 --- a/source/blender/compositor/operations/COM_MovieClipOperation.h +++ b/source/blender/compositor/operations/COM_MovieClipOperation.h @@ -21,8 +21,8 @@ */ -#ifndef _COM_ImageOperation_h -#define _COM_ImageOperation_h +#ifndef __COM_MOVIECLIPOPERATION_H__ +#define __COM_MOVIECLIPOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_movieclip_types.h" @@ -41,7 +41,7 @@ class MovieClipBaseOperation : public NodeOperation { int m_movieClipwidth; int m_framenumber; bool m_cacheFrame; - + /** * Determine the output resolution. The resolution is retrieved from the Renderer */ @@ -49,7 +49,7 @@ class MovieClipBaseOperation : public NodeOperation { public: MovieClipBaseOperation(); - + void initExecution(); void deinitExecution(); void setMovieClip(MovieClip *image) { this->m_movieClip = image; } diff --git a/source/blender/compositor/operations/COM_MovieDistortionOperation.h b/source/blender/compositor/operations/COM_MovieDistortionOperation.h index 689fcfe11ad3..f09e9c29d012 100644 --- a/source/blender/compositor/operations/COM_MovieDistortionOperation.h +++ b/source/blender/compositor/operations/COM_MovieDistortionOperation.h @@ -21,8 +21,8 @@ * Sergey Sharybin */ -#ifndef _COM_MovieDistortionOperation_h_ -#define _COM_MovieDistortionOperation_h_ +#ifndef __COM_MOVIEDISTORTIONOPERATION_H__ +#define __COM_MOVIEDISTORTIONOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_movieclip_types.h" diff --git a/source/blender/compositor/operations/COM_MultilayerImageOperation.h b/source/blender/compositor/operations/COM_MultilayerImageOperation.h index 2e68f922dd95..4074b80374f8 100644 --- a/source/blender/compositor/operations/COM_MultilayerImageOperation.h +++ b/source/blender/compositor/operations/COM_MultilayerImageOperation.h @@ -22,8 +22,8 @@ */ -#ifndef _COM_MultilayerImageOperation_h -#define _COM_MultilayerImageOperation_h +#ifndef __COM_MULTILAYERIMAGEOPERATION_H__ +#define __COM_MULTILAYERIMAGEOPERATION_H__ #include "COM_ImageOperation.h" diff --git a/source/blender/compositor/operations/COM_NormalizeOperation.cpp b/source/blender/compositor/operations/COM_NormalizeOperation.cpp index 6106a805f870..3527c874bcf1 100644 --- a/source/blender/compositor/operations/COM_NormalizeOperation.cpp +++ b/source/blender/compositor/operations/COM_NormalizeOperation.cpp @@ -64,7 +64,7 @@ bool NormalizeOperation::determineDependingAreaOfInterest(rcti * /*input*/, Read { rcti imageInput; if (this->m_cachedInstance) return false; - + NodeOperation *operation = getInputOperation(0); imageInput.xmax = operation->getWidth(); imageInput.xmin = 0; diff --git a/source/blender/compositor/operations/COM_NormalizeOperation.h b/source/blender/compositor/operations/COM_NormalizeOperation.h index 32f39a4d9cae..de1a23926f4f 100644 --- a/source/blender/compositor/operations/COM_NormalizeOperation.h +++ b/source/blender/compositor/operations/COM_NormalizeOperation.h @@ -19,8 +19,8 @@ * Dalai Felinto */ -#ifndef _COM_NormalizeOperation_h -#define _COM_NormalizeOperation_h +#ifndef __COM_NORMALIZEOPERATION_H__ +#define __COM_NORMALIZEOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" diff --git a/source/blender/compositor/operations/COM_OutputFileMultiViewOperation.h b/source/blender/compositor/operations/COM_OutputFileMultiViewOperation.h index 25ed8816399c..74ba8ff22265 100644 --- a/source/blender/compositor/operations/COM_OutputFileMultiViewOperation.h +++ b/source/blender/compositor/operations/COM_OutputFileMultiViewOperation.h @@ -22,8 +22,8 @@ * Dalai Felinto */ -#ifndef _COM_OutputFileMultiViewOperation_h -#define _COM_OutputFileMultiViewOperation_h +#ifndef __COM_OUTPUTFILEMULTIVIEWOPERATION_H__ +#define __COM_OUTPUTFILEMULTIVIEWOPERATION_H__ #include "COM_NodeOperation.h" #include "BLI_rect.h" diff --git a/source/blender/compositor/operations/COM_OutputFileOperation.cpp b/source/blender/compositor/operations/COM_OutputFileOperation.cpp index 39877e356050..de1a807f1372 100644 --- a/source/blender/compositor/operations/COM_OutputFileOperation.cpp +++ b/source/blender/compositor/operations/COM_OutputFileOperation.cpp @@ -135,11 +135,11 @@ static void write_buffer_rect(rcti *rect, const bNodeTree *tree, for (y = y1; y < y2 && (!breaked); y++) { for (x = x1; x < x2 && (!breaked); x++) { reader->readSampled(color, x, y, COM_PS_NEAREST); - + for (i = 0; i < size; ++i) buffer[offset + i] = color[i]; offset += size; - + if (tree->test_break && tree->test_break(tree->tbh)) breaked = true; } @@ -154,13 +154,13 @@ OutputSingleLayerOperation::OutputSingleLayerOperation( { this->m_rd = rd; this->m_tree = tree; - + this->addInputSocket(datatype); - + this->m_outputBuffer = NULL; this->m_datatype = datatype; this->m_imageInput = NULL; - + this->m_format = format; BLI_strncpy(this->m_path, path, sizeof(this->m_path)); @@ -183,17 +183,17 @@ void OutputSingleLayerOperation::executeRegion(rcti *rect, unsigned int /*tileNu void OutputSingleLayerOperation::deinitExecution() { if (this->getWidth() * this->getHeight() != 0) { - + int size = get_datatype_size(this->m_datatype); ImBuf *ibuf = IMB_allocImBuf(this->getWidth(), this->getHeight(), this->m_format->planes, 0); char filename[FILE_MAX]; const char *suffix; - + ibuf->channels = size; ibuf->rect_float = this->m_outputBuffer; - ibuf->mall |= IB_rectfloat; + ibuf->mall |= IB_rectfloat; ibuf->dither = this->m_rd->dither_intensity; - + IMB_colormanagement_imbuf_for_write(ibuf, true, false, m_viewSettings, m_displaySettings, this->m_format); @@ -207,7 +207,7 @@ void OutputSingleLayerOperation::deinitExecution() printf("Cannot save Node File Output to %s\n", filename); else printf("Saved: %s\n", filename); - + IMB_freeImBuf(ibuf); } this->m_outputBuffer = NULL; @@ -221,7 +221,7 @@ OutputOpenExrLayer::OutputOpenExrLayer(const char *name_, DataType datatype_, bo BLI_strncpy(this->name, name_, sizeof(this->name)); this->datatype = datatype_; this->use_layer = use_layer_; - + /* these are created in initExecution */ this->outputBuffer = 0; this->imageInput = 0; @@ -233,7 +233,7 @@ OutputOpenExrMultiLayerOperation::OutputOpenExrMultiLayerOperation( { this->m_rd = rd; this->m_tree = tree; - + BLI_strncpy(this->m_path, path, sizeof(this->m_path)); this->m_exr_codec = exr_codec; this->m_exr_half_float = exr_half_float; @@ -285,11 +285,11 @@ void OutputOpenExrMultiLayerOperation::deinitExecution() OutputOpenExrLayer &layer = this->m_layers[i]; if (!layer.imageInput) continue; /* skip unconnected sockets */ - + add_exr_channels(exrhandle, this->m_layers[i].name, this->m_layers[i].datatype, "", width, this->m_exr_half_float, this->m_layers[i].outputBuffer); } - + /* when the filename has no permissions, this can fail */ if (IMB_exr_begin_write(exrhandle, filename, width, height, this->m_exr_codec, NULL)) { IMB_exr_write_channels(exrhandle); @@ -299,16 +299,15 @@ void OutputOpenExrMultiLayerOperation::deinitExecution() /* XXX nice way to do report? */ printf("Error Writing Render Result, see console\n"); } - + IMB_exr_close(exrhandle); for (unsigned int i = 0; i < this->m_layers.size(); ++i) { if (this->m_layers[i].outputBuffer) { MEM_freeN(this->m_layers[i].outputBuffer); this->m_layers[i].outputBuffer = NULL; } - + this->m_layers[i].imageInput = NULL; } } } - diff --git a/source/blender/compositor/operations/COM_OutputFileOperation.h b/source/blender/compositor/operations/COM_OutputFileOperation.h index 60862de48cb8..cc800ca222a5 100644 --- a/source/blender/compositor/operations/COM_OutputFileOperation.h +++ b/source/blender/compositor/operations/COM_OutputFileOperation.h @@ -21,8 +21,8 @@ * Lukas Tönne */ -#ifndef _COM_OutputFileOperation_h -#define _COM_OutputFileOperation_h +#ifndef __COM_OUTPUTFILEOPERATION_H__ +#define __COM_OUTPUTFILEOPERATION_H__ #include "COM_NodeOperation.h" #include "BLI_rect.h" @@ -37,10 +37,10 @@ class OutputSingleLayerOperation : public NodeOperation { protected: const RenderData *m_rd; const bNodeTree *m_tree; - + ImageFormatData *m_format; char m_path[FILE_MAX]; - + float *m_outputBuffer; DataType m_datatype; SocketReader *m_imageInput; @@ -52,7 +52,7 @@ class OutputSingleLayerOperation : public NodeOperation { public: OutputSingleLayerOperation(const RenderData *rd, const bNodeTree *tree, DataType datatype, ImageFormatData *format, const char *path, const ColorManagedViewSettings *viewSettings, const ColorManagedDisplaySettings *displaySettings, const char *viewName); - + void executeRegion(rcti *rect, unsigned int tileNumber); bool isOutputOperation(bool /*rendering*/) const { return true; } void initExecution(); @@ -65,11 +65,11 @@ class OutputSingleLayerOperation : public NodeOperation { /* extra info for OpenEXR layers */ struct OutputOpenExrLayer { OutputOpenExrLayer(const char *name, DataType datatype, bool use_layer); - + char name[EXR_TOT_MAXNAME - 2]; DataType datatype; bool use_layer; - + /* internals */ float *outputBuffer; SocketReader *imageInput; @@ -79,22 +79,22 @@ struct OutputOpenExrLayer { class OutputOpenExrMultiLayerOperation : public NodeOperation { protected: typedef std::vector LayerList; - + const RenderData *m_rd; const bNodeTree *m_tree; - + char m_path[FILE_MAX]; char m_exr_codec; bool m_exr_half_float; LayerList m_layers; const char *m_viewName; - + public: OutputOpenExrMultiLayerOperation(const RenderData *rd, const bNodeTree *tree, const char *path, char exr_codec, bool exr_half_float, const char *viewName); - + void add_layer(const char *name, DataType datatype, bool use_layer); - + void executeRegion(rcti *rect, unsigned int tileNumber); bool isOutputOperation(bool /*rendering*/) const { return true; } void initExecution(); diff --git a/source/blender/compositor/operations/COM_PixelateOperation.cpp b/source/blender/compositor/operations/COM_PixelateOperation.cpp index eed6d1d01b91..4373c3511ea3 100644 --- a/source/blender/compositor/operations/COM_PixelateOperation.cpp +++ b/source/blender/compositor/operations/COM_PixelateOperation.cpp @@ -46,4 +46,3 @@ void PixelateOperation::executePixelSampled(float output[4], float x, float y, P float ny = round(y); this->m_inputOperation->readSampled(output, nx, ny, sampler); } - diff --git a/source/blender/compositor/operations/COM_PixelateOperation.h b/source/blender/compositor/operations/COM_PixelateOperation.h index 8e60baf7f052..5b08cb429f44 100644 --- a/source/blender/compositor/operations/COM_PixelateOperation.h +++ b/source/blender/compositor/operations/COM_PixelateOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_PixelateOperation_h_ -#define _COM_PixelateOperation_h_ +#ifndef __COM_PIXELATEOPERATION_H__ +#define __COM_PIXELATEOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp index d6affa6eee9a..4e4e803c7574 100644 --- a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp +++ b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp @@ -49,7 +49,7 @@ static bool check_corners(float corners[4][2]) cur_cross = cross_v2v2(v1, v2); if (fabsf(cur_cross) <= FLT_EPSILON) return false; - + if (cross == 0.0f) cross = cur_cross; else if (cross * cur_cross < 0.0f) @@ -67,7 +67,7 @@ static void readCornersFromSockets(rcti *rect, SocketReader *readers[4], float c corners[i][0] = result[0]; corners[i][1] = result[1]; } - + /* convexity check: * concave corners need to be prevented, otherwise * BKE_tracking_homography_between_two_quads will freeze @@ -95,7 +95,7 @@ PlaneCornerPinMaskOperation::PlaneCornerPinMaskOperation() : addInputSocket(COM_DT_VECTOR); addInputSocket(COM_DT_VECTOR); addInputSocket(COM_DT_VECTOR); - + /* XXX this is stupid: we need to make this "complex", * so we can use the initializeTileData function * to read corners from input sockets ... @@ -106,21 +106,21 @@ PlaneCornerPinMaskOperation::PlaneCornerPinMaskOperation() : void PlaneCornerPinMaskOperation::initExecution() { PlaneDistortMaskOperation::initExecution(); - + initMutex(); } void PlaneCornerPinMaskOperation::deinitExecution() { PlaneDistortMaskOperation::deinitExecution(); - + deinitMutex(); } void *PlaneCornerPinMaskOperation::initializeTileData(rcti *rect) { void *data = PlaneDistortMaskOperation::initializeTileData(rect); - + /* get corner values once, by reading inputs at (0,0) * XXX this assumes invariable values (no image inputs), * we don't have a nice generic system for that yet @@ -134,11 +134,11 @@ void *PlaneCornerPinMaskOperation::initializeTileData(rcti *rect) float corners[4][2]; readCornersFromSockets(rect, readers, corners); calculateCorners(corners, true, 0); - + m_corners_ready = true; } unlockMutex(); - + return data; } @@ -164,21 +164,21 @@ PlaneCornerPinWarpImageOperation::PlaneCornerPinWarpImageOperation() : void PlaneCornerPinWarpImageOperation::initExecution() { PlaneDistortWarpImageOperation::initExecution(); - + initMutex(); } void PlaneCornerPinWarpImageOperation::deinitExecution() { PlaneDistortWarpImageOperation::deinitExecution(); - + deinitMutex(); } void *PlaneCornerPinWarpImageOperation::initializeTileData(rcti *rect) { void *data = PlaneDistortWarpImageOperation::initializeTileData(rect); - + /* get corner values once, by reading inputs at (0,0) * XXX this assumes invariable values (no image inputs), * we don't have a nice generic system for that yet @@ -193,11 +193,11 @@ void *PlaneCornerPinWarpImageOperation::initializeTileData(rcti *rect) float corners[4][2]; readCornersFromSockets(rect, readers, corners); calculateCorners(corners, true, 0); - + m_corners_ready = true; } unlockMutex(); - + return data; } @@ -206,7 +206,7 @@ bool PlaneCornerPinWarpImageOperation::determineDependingAreaOfInterest(rcti *in for (int i = 0; i < 4; ++i) if (getInputOperation(i + 1)->determineDependingAreaOfInterest(input, readOperation, output)) return true; - + /* XXX this is bad, but unavoidable with the current design: * we don't know the actual corners and matrix at this point, * so all we can do is get the full input image diff --git a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h index ed70d9c80a3c..980f57c4ceac 100644 --- a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h +++ b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.h @@ -20,8 +20,8 @@ * Lukas Toenne */ -#ifndef _COM_CornerPinWarpImageOperation_h -#define _COM_CornerPinWarpImageOperation_h +#ifndef __COM_PLANECORNERPINOPERATION_H__ +#define __COM_PLANECORNERPINOPERATION_H__ #include @@ -37,15 +37,15 @@ class PlaneCornerPinMaskOperation : public PlaneDistortMaskOperation { private: bool m_corners_ready; - + public: PlaneCornerPinMaskOperation(); - + void initExecution(); void deinitExecution(); - + void *initializeTileData(rcti *rect); - + void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); }; @@ -53,15 +53,15 @@ class PlaneCornerPinMaskOperation : public PlaneDistortMaskOperation { class PlaneCornerPinWarpImageOperation : public PlaneDistortWarpImageOperation { private: bool m_corners_ready; - + public: PlaneCornerPinWarpImageOperation(); - + void initExecution(); void deinitExecution(); - + void *initializeTileData(rcti *rect); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; diff --git a/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.h b/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.h index fc5dd1ff7d85..adf13685b4a1 100644 --- a/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.h +++ b/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.h @@ -20,8 +20,8 @@ * Sergey Sharybin */ -#ifndef _COM_PlaneTrackCommonOperation_h -#define _COM_PlaneTrackCommonOperation_h +#ifndef __COM_PLANEDISTORTCOMMONOPERATION_H__ +#define __COM_PLANEDISTORTCOMMONOPERATION_H__ #include diff --git a/source/blender/compositor/operations/COM_PlaneTrackOperation.h b/source/blender/compositor/operations/COM_PlaneTrackOperation.h index 41761493e123..493d9cb3be1b 100644 --- a/source/blender/compositor/operations/COM_PlaneTrackOperation.h +++ b/source/blender/compositor/operations/COM_PlaneTrackOperation.h @@ -20,8 +20,8 @@ * Sergey Sharybin */ -#ifndef _COM_PlaneTrackWarpImageOperation_h -#define _COM_PlaneTrackWarpImageOperation_h +#ifndef __COM_PLANETRACKOPERATION_H__ +#define __COM_PLANETRACKOPERATION_H__ #include diff --git a/source/blender/compositor/operations/COM_PreviewOperation.cpp b/source/blender/compositor/operations/COM_PreviewOperation.cpp index d4075844f0e9..90e1bba3cd91 100644 --- a/source/blender/compositor/operations/COM_PreviewOperation.cpp +++ b/source/blender/compositor/operations/COM_PreviewOperation.cpp @@ -61,7 +61,7 @@ void PreviewOperation::verifyPreview(bNodeInstanceHash *previews, bNodeInstanceK void PreviewOperation::initExecution() { this->m_input = getInputSocketReader(0); - + if (this->getWidth() == (unsigned int)this->m_preview->xsize && this->getHeight() == (unsigned int)this->m_preview->ysize) { @@ -98,7 +98,7 @@ void PreviewOperation::executeRegion(rcti *rect, unsigned int /*tileNumber*/) for (int x = rect->xmin; x < rect->xmax; x++) { float rx = floor(x / this->m_divider); float ry = floor(y / this->m_divider); - + color[0] = 0.0f; color[1] = 0.0f; color[2] = 0.0f; @@ -137,7 +137,7 @@ void PreviewOperation::determineResolution(unsigned int resolution[2], unsigned } width = width * this->m_divider; height = height * this->m_divider; - + resolution[0] = width; resolution[1] = height; } diff --git a/source/blender/compositor/operations/COM_PreviewOperation.h b/source/blender/compositor/operations/COM_PreviewOperation.h index ca1d6f54cdca..753177488971 100644 --- a/source/blender/compositor/operations/COM_PreviewOperation.h +++ b/source/blender/compositor/operations/COM_PreviewOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_PreviewOperation_h -#define _COM_PreviewOperation_h +#ifndef __COM_PREVIEWOPERATION_H__ +#define __COM_PREVIEWOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_image_types.h" #include "DNA_color_types.h" @@ -44,16 +44,16 @@ class PreviewOperation : public NodeOperation { public: PreviewOperation(const ColorManagedViewSettings *viewSettings, const ColorManagedDisplaySettings *displaySettings); void verifyPreview(bNodeInstanceHash *previews, bNodeInstanceKey key); - + bool isOutputOperation(bool /*rendering*/) const { return !G.background; } void initExecution(); void deinitExecution(); const CompositorPriority getRenderPriority() const; - + void executeRegion(rcti *rect, unsigned int tileNumber); void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); bool isPreviewOperation() const { return true; } - + }; #endif diff --git a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp index 020bdde8c93e..e135abe5f20f 100644 --- a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp +++ b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.cpp @@ -96,7 +96,7 @@ bool ProjectorLensDistortionOperation::determineDependingAreaOfInterest(rcti *in return false; } -void ProjectorLensDistortionOperation::updateDispersion() +void ProjectorLensDistortionOperation::updateDispersion() { if (this->m_dispersionAvailable) return; this->lockMutex(); diff --git a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h index 9eb90b6006be..79bd5586d8f7 100644 --- a/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h +++ b/source/blender/compositor/operations/COM_ProjectorLensDistortionOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ProjectorLensDistortionOperation_h -#define _COM_ProjectorLensDistortionOperation_h +#ifndef __COM_PROJECTORLENSDISTORTIONOPERATION_H__ +#define __COM_PROJECTORLENSDISTORTIONOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" @@ -31,30 +31,30 @@ class ProjectorLensDistortionOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputProgram; - + float m_dispersion; bool m_dispersionAvailable; - + float m_kr, m_kr2; public: ProjectorLensDistortionOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void updateDispersion(); diff --git a/source/blender/compositor/operations/COM_QualityStepHelper.cpp b/source/blender/compositor/operations/COM_QualityStepHelper.cpp index a1d84e7d569c..9a9db86f720c 100644 --- a/source/blender/compositor/operations/COM_QualityStepHelper.cpp +++ b/source/blender/compositor/operations/COM_QualityStepHelper.cpp @@ -68,4 +68,3 @@ void QualityStepHelper::initExecution(QualityHelper helper) break; } } - diff --git a/source/blender/compositor/operations/COM_QualityStepHelper.h b/source/blender/compositor/operations/COM_QualityStepHelper.h index 9076e5a07761..67419cfbc871 100644 --- a/source/blender/compositor/operations/COM_QualityStepHelper.h +++ b/source/blender/compositor/operations/COM_QualityStepHelper.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_QualityStepHelper_h -#define _COM_QualityStepHelper_h +#ifndef __COM_QUALITYSTEPHELPER_H__ +#define __COM_QUALITYSTEPHELPER_H__ #include "COM_defines.h" typedef enum QualityHelper { diff --git a/source/blender/compositor/operations/COM_ReadBufferOperation.cpp b/source/blender/compositor/operations/COM_ReadBufferOperation.cpp index f256d3a6aa13..6e7a32ba5a95 100644 --- a/source/blender/compositor/operations/COM_ReadBufferOperation.cpp +++ b/source/blender/compositor/operations/COM_ReadBufferOperation.cpp @@ -120,8 +120,8 @@ void ReadBufferOperation::readResolutionFromWriteBuffer() } } -void ReadBufferOperation::updateMemoryBuffer() +void ReadBufferOperation::updateMemoryBuffer() { this->m_buffer = this->getMemoryProxy()->getBuffer(); - + } diff --git a/source/blender/compositor/operations/COM_ReadBufferOperation.h b/source/blender/compositor/operations/COM_ReadBufferOperation.h index 898b568bb912..c73acbaf300f 100644 --- a/source/blender/compositor/operations/COM_ReadBufferOperation.h +++ b/source/blender/compositor/operations/COM_ReadBufferOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ReadBufferOperation_h -#define _COM_ReadBufferOperation_h +#ifndef __COM_READBUFFEROPERATION_H__ +#define __COM_READBUFFEROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_MemoryProxy.h" @@ -38,7 +38,7 @@ class ReadBufferOperation : public NodeOperation { void setMemoryProxy(MemoryProxy *memoryProxy) { this->m_memoryProxy = memoryProxy; } MemoryProxy *getMemoryProxy() { return this->m_memoryProxy; } void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + void *initializeTileData(rcti *rect); void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); void executePixelExtend(float output[4], float x, float y, PixelSampler sampler, diff --git a/source/blender/compositor/operations/COM_RenderLayersProg.cpp b/source/blender/compositor/operations/COM_RenderLayersProg.cpp index c7afa67a306d..5331f198aa42 100644 --- a/source/blender/compositor/operations/COM_RenderLayersProg.cpp +++ b/source/blender/compositor/operations/COM_RenderLayersProg.cpp @@ -50,10 +50,10 @@ void RenderLayersProg::initExecution() Scene *scene = this->getScene(); Render *re = (scene) ? RE_GetSceneRender(scene) : NULL; RenderResult *rr = NULL; - + if (re) rr = RE_AcquireResultRead(re); - + if (rr) { SceneRenderLayer *srl = (SceneRenderLayer *)BLI_findlink(&scene->r.layers, getLayerId()); if (srl) { @@ -181,13 +181,13 @@ void RenderLayersProg::determineResolution(unsigned int resolution[2], unsigned Scene *sce = this->getScene(); Render *re = (sce) ? RE_GetSceneRender(sce) : NULL; RenderResult *rr = NULL; - + resolution[0] = 0; resolution[1] = 0; - + if (re) rr = RE_AcquireResultRead(re); - + if (rr) { SceneRenderLayer *srl = (SceneRenderLayer *)BLI_findlink(&sce->r.layers, getLayerId()); if (srl) { @@ -198,7 +198,7 @@ void RenderLayersProg::determineResolution(unsigned int resolution[2], unsigned } } } - + if (re) RE_ReleaseResult(re); diff --git a/source/blender/compositor/operations/COM_RenderLayersProg.h b/source/blender/compositor/operations/COM_RenderLayersProg.h index 90d57d422e31..2a0f7efc9f8c 100644 --- a/source/blender/compositor/operations/COM_RenderLayersProg.h +++ b/source/blender/compositor/operations/COM_RenderLayersProg.h @@ -21,8 +21,8 @@ */ -#ifndef _COM_RenderLayersBaseProg_h -#define _COM_RenderLayersBaseProg_h +#ifndef __COM_RENDERLAYERSPROG_H__ +#define __COM_RENDERLAYERSPROG_H__ #include "COM_NodeOperation.h" #include "DNA_scene_types.h" diff --git a/source/blender/compositor/operations/COM_RotateOperation.cpp b/source/blender/compositor/operations/COM_RotateOperation.cpp index 2d0d5aaf8d34..4186a0e1fc85 100644 --- a/source/blender/compositor/operations/COM_RotateOperation.cpp +++ b/source/blender/compositor/operations/COM_RotateOperation.cpp @@ -62,7 +62,7 @@ inline void RotateOperation::ensureDegree() } this->m_cosine = cos(rad); this->m_sine = sin(rad); - + this->m_isDegreeSet = true; } } @@ -82,12 +82,12 @@ bool RotateOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOp { ensureDegree(); rcti newInput; - + const float dxmin = input->xmin - this->m_centerX; const float dymin = input->ymin - this->m_centerY; const float dxmax = input->xmax - this->m_centerX; const float dymax = input->ymax - this->m_centerY; - + const float x1 = this->m_centerX + (this->m_cosine * dxmin + this->m_sine * dymin); const float x2 = this->m_centerX + (this->m_cosine * dxmax + this->m_sine * dymin); const float x3 = this->m_centerX + (this->m_cosine * dxmin + this->m_sine * dymax); @@ -100,11 +100,11 @@ bool RotateOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOp const float maxx = max(x1, max(x2, max(x3, x4))); const float miny = min(y1, min(y2, min(y3, y4))); const float maxy = max(y1, max(y2, max(y3, y4))); - + newInput.xmax = ceil(maxx) + 1; newInput.xmin = floor(minx) - 1; newInput.ymax = ceil(maxy) + 1; newInput.ymin = floor(miny) - 1; - + return NodeOperation::determineDependingAreaOfInterest(&newInput, readOperation, output); } diff --git a/source/blender/compositor/operations/COM_RotateOperation.h b/source/blender/compositor/operations/COM_RotateOperation.h index 7b99b6faa976..59fb92054e17 100644 --- a/source/blender/compositor/operations/COM_RotateOperation.h +++ b/source/blender/compositor/operations/COM_RotateOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_RotateOperation_h_ -#define _COM_RotateOperation_h_ +#ifndef __COM_ROTATEOPERATION_H__ +#define __COM_ROTATEOPERATION_H__ #include "COM_NodeOperation.h" @@ -42,7 +42,7 @@ class RotateOperation : public NodeOperation { void initExecution(); void deinitExecution(); void setDoDegree2RadConversion(bool abool) { this->m_doDegree2RadConversion = abool; } - + void ensureDegree(); }; diff --git a/source/blender/compositor/operations/COM_ScaleOperation.h b/source/blender/compositor/operations/COM_ScaleOperation.h index 93f9827aabf5..b4aecb1515d7 100644 --- a/source/blender/compositor/operations/COM_ScaleOperation.h +++ b/source/blender/compositor/operations/COM_ScaleOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ScaleOperation_h_ -#define _COM_ScaleOperation_h_ +#ifndef __COM_SCALEOPERATION_H__ +#define __COM_SCALEOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp index 651c336452e3..5d50640d5828 100644 --- a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp +++ b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.cpp @@ -59,10 +59,10 @@ void ScreenLensDistortionOperation::initExecution() { this->m_inputProgram = this->getInputSocketReader(0); this->initMutex(); - + this->m_cx = 0.5f * (float)getWidth(); this->m_cy = 0.5f * (float)getHeight(); - + /* if both are constant, init variables once */ if (m_distortion_const && m_dispersion_const) { updateVariables(m_distortion, m_dispersion); @@ -80,7 +80,7 @@ void *ScreenLensDistortionOperation::initializeTileData(rcti * /*rect*/) */ if (!m_variables_ready) { this->lockMutex(); - + if (!m_distortion_const) { float result[4]; getInputSocketReader(1)->readSampled(result, 0, 0, COM_PS_NEAREST); @@ -91,13 +91,13 @@ void *ScreenLensDistortionOperation::initializeTileData(rcti * /*rect*/) getInputSocketReader(2)->readSampled(result, 0, 0, COM_PS_NEAREST); m_dispersion = result[0]; } - + updateVariables(m_distortion, m_dispersion); m_variables_ready = true; - + this->unlockMutex(); } - + return buffer; } @@ -123,7 +123,7 @@ bool ScreenLensDistortionOperation::get_delta(float r_sq, float k4, const float } else return false; - + } void ScreenLensDistortionOperation::accumulate(MemoryBuffer *buffer, @@ -133,7 +133,7 @@ void ScreenLensDistortionOperation::accumulate(MemoryBuffer *buffer, float sum[4], int count[3]) const { float color[4]; - + float dsf = len_v2v2(delta[a], delta[b]) + 1.0f; int ds = m_jitter ? (dsf < 4.0f ? 2 : (int)sqrtf(dsf)) : (int)dsf; float sd = 1.0f / (float)ds; @@ -144,11 +144,11 @@ void ScreenLensDistortionOperation::accumulate(MemoryBuffer *buffer, for (float z = 0; z < ds; ++z) { float tz = (z + (m_jitter ? BLI_frand() : 0.5f)) * sd; float t = 1.0f - (k4 + tz * dk4) * r_sq; - + float xy[2]; distort_uv(uv, t, xy); buffer->readBilinear(color, xy[0], xy[1]); - + sum[a] += (1.0f - tz) * color[a]; sum[b] += (tz ) * color[b]; count[a]++; @@ -175,11 +175,11 @@ void ScreenLensDistortionOperation::executePixel(float output[4], int x, int y, if (valid_r && valid_g && valid_b) { accumulate(buffer, 0, 1, uv_dot, uv, delta, sum, count); accumulate(buffer, 1, 2, uv_dot, uv, delta, sum, count); - + if (count[0]) output[0] = 2.0f * sum[0] / (float)count[0]; if (count[1]) output[1] = 2.0f * sum[1] / (float)count[1]; if (count[2]) output[2] = 2.0f * sum[2] / (float)count[2]; - + /* set alpha */ output[3] = 1.0f; } @@ -200,7 +200,7 @@ void ScreenLensDistortionOperation::determineUV(float result[6], float x, float float uv[2]; get_uv(xy, uv); float uv_dot = len_squared_v2(uv); - + copy_v2_v2(result + 0, xy); copy_v2_v2(result + 2, xy); copy_v2_v2(result + 4, xy); @@ -216,7 +216,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in newInputValue.ymin = 0; newInputValue.xmax = 2; newInputValue.ymax = 2; - + NodeOperation *operation = getInputOperation(1); if (operation->determineDependingAreaOfInterest(&newInputValue, readOperation, output) ) { return true; @@ -226,7 +226,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in if (operation->determineDependingAreaOfInterest(&newInputValue, readOperation, output) ) { return true; } - + /* XXX the original method of estimating the area-of-interest does not work * it assumes a linear increase/decrease of mapped coordinates, which does not * yield correct results for the area and leaves uninitialized buffer areas. @@ -234,7 +234,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in */ #if 1 rcti imageInput; - + operation = getInputOperation(0); imageInput.xmax = operation->getWidth(); imageInput.xmin = 0; @@ -248,9 +248,9 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in #else rcti newInput; const float margin = 2; - + BLI_rcti_init_minmax(&newInput); - + if (m_dispersion_const && m_distortion_const) { /* update from fixed distortion/dispersion */ #define UPDATE_INPUT(x, y) \ @@ -284,7 +284,7 @@ bool ScreenLensDistortionOperation::determineDependingAreaOfInterest(rcti * /*in newInput.xmax = max_ffff(newInput.xmax, coords[0], coords[2], coords[4]); \ newInput.ymax = max_ffff(newInput.ymax, coords[1], coords[3], coords[5]); \ } (void)0 - + if (m_distortion_const) { /* update from fixed distortion */ UPDATE_INPUT(input->xmin, input->xmax, m_distortion); diff --git a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h index 648a7a6e5518..f89af962211d 100644 --- a/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h +++ b/source/blender/compositor/operations/COM_ScreenLensDistortionOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ScreenLensDistortionOperation_h -#define _COM_ScreenLensDistortionOperation_h +#ifndef __COM_SCREENLENSDISTORTIONOPERATION_H__ +#define __COM_SCREENLENSDISTORTIONOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" @@ -31,10 +31,10 @@ class ScreenLensDistortionOperation : public NodeOperation { * Cached reference to the inputProgram */ SocketReader *m_inputProgram; - + bool m_fit; bool m_jitter; - + float m_dispersion; float m_distortion; bool m_dispersion_const; @@ -47,31 +47,31 @@ class ScreenLensDistortionOperation : public NodeOperation { float m_sc, m_cx, m_cy; public: ScreenLensDistortionOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); /** * Deinitialize the execution */ void deinitExecution(); - + void setFit(bool fit) { m_fit = fit; } void setJitter(bool jitter) { m_jitter = jitter; } - + /** Set constant distortion value */ void setDistortion(float distortion); /** Set constant dispersion value */ void setDispersion(float dispersion); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); private: diff --git a/source/blender/compositor/operations/COM_SetAlphaOperation.cpp b/source/blender/compositor/operations/COM_SetAlphaOperation.cpp index 91933484027c..e6c04a4b68cf 100644 --- a/source/blender/compositor/operations/COM_SetAlphaOperation.cpp +++ b/source/blender/compositor/operations/COM_SetAlphaOperation.cpp @@ -27,7 +27,7 @@ SetAlphaOperation::SetAlphaOperation() : NodeOperation() this->addInputSocket(COM_DT_COLOR); this->addInputSocket(COM_DT_VALUE); this->addOutputSocket(COM_DT_COLOR); - + this->m_inputColor = NULL; this->m_inputAlpha = NULL; } @@ -41,10 +41,10 @@ void SetAlphaOperation::initExecution() void SetAlphaOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) { float alphaInput[4]; - + this->m_inputColor->readSampled(output, x, y, sampler); this->m_inputAlpha->readSampled(alphaInput, x, y, sampler); - + output[3] = alphaInput[0]; } diff --git a/source/blender/compositor/operations/COM_SetAlphaOperation.h b/source/blender/compositor/operations/COM_SetAlphaOperation.h index 12e3debf3d39..90deb69a67db 100644 --- a/source/blender/compositor/operations/COM_SetAlphaOperation.h +++ b/source/blender/compositor/operations/COM_SetAlphaOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetAlphaOperation_h -#define _COM_SetAlphaOperation_h +#ifndef __COM_SETALPHAOPERATION_H__ +#define __COM_SETALPHAOPERATION_H__ #include "COM_NodeOperation.h" @@ -39,12 +39,12 @@ class SetAlphaOperation : public NodeOperation { * Default constructor */ SetAlphaOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + void initExecution(); void deinitExecution(); }; diff --git a/source/blender/compositor/operations/COM_SetColorOperation.h b/source/blender/compositor/operations/COM_SetColorOperation.h index f9fa06f5132f..9a509f6fb0ca 100644 --- a/source/blender/compositor/operations/COM_SetColorOperation.h +++ b/source/blender/compositor/operations/COM_SetColorOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetColorOperation_h -#define _COM_SetColorOperation_h +#ifndef __COM_SETCOLOROPERATION_H__ +#define __COM_SETCOLOROPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_SetSamplerOperation.h b/source/blender/compositor/operations/COM_SetSamplerOperation.h index 903bcef95f05..24b14a3ce486 100644 --- a/source/blender/compositor/operations/COM_SetSamplerOperation.h +++ b/source/blender/compositor/operations/COM_SetSamplerOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetSamplerOperation_h -#define _COM_SetSamplerOperation_h +#ifndef __COM_SETSAMPLEROPERATION_H__ +#define __COM_SETSAMPLEROPERATION_H__ #include "COM_NodeOperation.h" @@ -38,9 +38,9 @@ class SetSamplerOperation : public NodeOperation { * Default constructor */ SetSamplerOperation(); - + void setSampler(PixelSampler sampler) { this->m_sampler = sampler; } - + /** * the inner loop of this program */ diff --git a/source/blender/compositor/operations/COM_SetValueOperation.h b/source/blender/compositor/operations/COM_SetValueOperation.h index 10de8825d382..4e274816f27d 100644 --- a/source/blender/compositor/operations/COM_SetValueOperation.h +++ b/source/blender/compositor/operations/COM_SetValueOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetValueOperation_h -#define _COM_SetValueOperation_h +#ifndef __COM_SETVALUEOPERATION_H__ +#define __COM_SETVALUEOPERATION_H__ #include "COM_NodeOperation.h" @@ -38,17 +38,17 @@ class SetValueOperation : public NodeOperation { * Default constructor */ SetValueOperation(); - + const float getValue() { return this->m_value; } void setValue(float value) { this->m_value = value; } - - + + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + bool isSetOperation() const { return true; } }; #endif diff --git a/source/blender/compositor/operations/COM_SetVectorOperation.h b/source/blender/compositor/operations/COM_SetVectorOperation.h index b01f2f7a6b57..ca35784ff9ac 100644 --- a/source/blender/compositor/operations/COM_SetVectorOperation.h +++ b/source/blender/compositor/operations/COM_SetVectorOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SetVectorOperation_h -#define _COM_SetVectorOperation_h +#ifndef __COM_SETVECTOROPERATION_H__ +#define __COM_SETVECTOROPERATION_H__ #include "COM_NodeOperation.h" @@ -41,7 +41,7 @@ class SetVectorOperation : public NodeOperation { * Default constructor */ SetVectorOperation(); - + const float getX() { return this->m_x; } void setX(float value) { this->m_x = value; } const float getY() { return this->m_y; } @@ -50,7 +50,7 @@ class SetVectorOperation : public NodeOperation { void setZ(float value) { this->m_z = value; } const float getW() { return this->m_w; } void setW(float value) { this->m_w = value; } - + /** * the inner loop of this program */ diff --git a/source/blender/compositor/operations/COM_SocketProxyOperation.h b/source/blender/compositor/operations/COM_SocketProxyOperation.h index 86c8b23b1154..61575ac6b2c7 100644 --- a/source/blender/compositor/operations/COM_SocketProxyOperation.h +++ b/source/blender/compositor/operations/COM_SocketProxyOperation.h @@ -20,21 +20,21 @@ * Monique Dewanchand */ -#ifndef _COM_SocketProxyOperation_h_ -#define _COM_SocketProxyOperation_h_ +#ifndef __COM_SOCKETPROXYOPERATION_H__ +#define __COM_SOCKETPROXYOPERATION_H__ #include "COM_NodeOperation.h" class SocketProxyOperation : public NodeOperation { public: SocketProxyOperation(DataType type, bool use_conversion); - + bool isProxyOperation() const { return true; } bool useDatatypeConversion() const { return m_use_conversion; } - + bool getUseConversion() const { return m_use_conversion; } void setUseConversion(bool use_conversion) { m_use_conversion = use_conversion; } - + private: bool m_use_conversion; }; diff --git a/source/blender/compositor/operations/COM_SplitOperation.h b/source/blender/compositor/operations/COM_SplitOperation.h index 4375c760963d..a7c7146ddeac 100644 --- a/source/blender/compositor/operations/COM_SplitOperation.h +++ b/source/blender/compositor/operations/COM_SplitOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_SplitOperation_h -#define _COM_SplitOperation_h +#ifndef __COM_SPLITOPERATION_H__ +#define __COM_SPLITOPERATION_H__ #include "COM_NodeOperation.h" class SplitOperation : public NodeOperation { diff --git a/source/blender/compositor/operations/COM_SunBeamsOperation.cpp b/source/blender/compositor/operations/COM_SunBeamsOperation.cpp index 81b967bf5303..40f2ee226aed 100644 --- a/source/blender/compositor/operations/COM_SunBeamsOperation.cpp +++ b/source/blender/compositor/operations/COM_SunBeamsOperation.cpp @@ -61,7 +61,7 @@ template struct BufferLineAccumulator { /* utility functions implementing the matrix transform to/from sector space */ - + static inline void buffer_to_sector(const float source[2], int x, int y, int &u, int &v) { int x0 = (int)source[0]; @@ -155,9 +155,9 @@ struct BufferLineAccumulator { float v, dv; float falloff_factor; float border[4]; - + zero_v4(output); - + if ((int)(co[0] - source[0]) == 0 && (int)(co[1] - source[1]) == 0) { copy_v4_v4(output, input->getBuffer() + COM_NUM_CHANNELS_COLOR * ((int)source[0] + input->getWidth() * (int)source[1])); return; @@ -174,7 +174,7 @@ struct BufferLineAccumulator { for (int i = 0; i < num; i++) { float weight = 1.0f - (float)i * falloff_factor; weight *= weight; - + /* range check, use last valid color when running beyond the image border */ if (x >= rect.xmin && x < rect.xmax && y >= rect.ymin && y < rect.ymax) { madd_v4_v4fl(output, buffer, buffer[3] * weight); @@ -184,7 +184,7 @@ struct BufferLineAccumulator { else { madd_v4_v4fl(output, border, border[3] * weight); } - + /* TODO implement proper filtering here, see * https://en.wikipedia.org/wiki/Lanczos_resampling * https://en.wikipedia.org/wiki/Sinc_function @@ -335,4 +335,3 @@ bool SunBeamsOperation::determineDependingAreaOfInterest(rcti *input, ReadBuffer return NodeOperation::determineDependingAreaOfInterest(&rect, readOperation, output); } - diff --git a/source/blender/compositor/operations/COM_SunBeamsOperation.h b/source/blender/compositor/operations/COM_SunBeamsOperation.h index ef80a31fe40d..43846ab24d1b 100644 --- a/source/blender/compositor/operations/COM_SunBeamsOperation.h +++ b/source/blender/compositor/operations/COM_SunBeamsOperation.h @@ -19,8 +19,8 @@ * Lukas Toenne */ -#ifndef _COM_SunBeamsOperation_h -#define _COM_SunBeamsOperation_h +#ifndef __COM_SUNBEAMSOPERATION_H__ +#define __COM_SUNBEAMSOPERATION_H__ #include "COM_NodeOperation.h" diff --git a/source/blender/compositor/operations/COM_TextureOperation.h b/source/blender/compositor/operations/COM_TextureOperation.h index a2fb7c7501f4..9f0f539800d8 100644 --- a/source/blender/compositor/operations/COM_TextureOperation.h +++ b/source/blender/compositor/operations/COM_TextureOperation.h @@ -21,8 +21,8 @@ */ -#ifndef _COM_TextureOperation_h -#define _COM_TextureOperation_h +#ifndef __COM_TEXTUREOPERATION_H__ +#define __COM_TEXTUREOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_texture_types.h" @@ -54,7 +54,7 @@ class TextureBaseOperation : public NodeOperation { * Determine the output resolution. The resolution is retrieved from the Renderer */ void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + /** * Constructor */ diff --git a/source/blender/compositor/operations/COM_TonemapOperation.h b/source/blender/compositor/operations/COM_TonemapOperation.h index 51ffaac85036..2b07ded73052 100644 --- a/source/blender/compositor/operations/COM_TonemapOperation.h +++ b/source/blender/compositor/operations/COM_TonemapOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_TonemapOperation_h -#define _COM_TonemapOperation_h +#ifndef __COM_TONEMAPOPERATION_H__ +#define __COM_TONEMAPOPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" @@ -47,12 +47,12 @@ class TonemapOperation : public NodeOperation { * @brief Cached reference to the reader */ SocketReader *m_imageReader; - + /** * @brief settings of the Tonemap */ NodeTonemap *m_data; - + /** * @brief temporarily cache of the execution storage */ @@ -60,27 +60,27 @@ class TonemapOperation : public NodeOperation { public: TonemapOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); void deinitializeTileData(rcti *rect, void *data); - + /** * Deinitialize the execution */ void deinitExecution(); - + void setData(NodeTonemap *data) { this->m_data = data; } - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); }; diff --git a/source/blender/compositor/operations/COM_TrackPositionOperation.h b/source/blender/compositor/operations/COM_TrackPositionOperation.h index 87bb0623ad5e..add6ccd34591 100644 --- a/source/blender/compositor/operations/COM_TrackPositionOperation.h +++ b/source/blender/compositor/operations/COM_TrackPositionOperation.h @@ -22,8 +22,8 @@ */ -#ifndef _COM_TrackPositionOperation_h -#define _COM_TrackPositionOperation_h +#ifndef __COM_TRACKPOSITIONOPERATION_H__ +#define __COM_TRACKPOSITIONOPERATION_H__ #include diff --git a/source/blender/compositor/operations/COM_TranslateOperation.cpp b/source/blender/compositor/operations/COM_TranslateOperation.cpp index fcf99a10a734..89092cf85665 100644 --- a/source/blender/compositor/operations/COM_TranslateOperation.cpp +++ b/source/blender/compositor/operations/COM_TranslateOperation.cpp @@ -81,4 +81,3 @@ void TranslateOperation::setFactorXY(float factorX, float factorY) m_factorX = factorX; m_factorY = factorY; } - diff --git a/source/blender/compositor/operations/COM_TranslateOperation.h b/source/blender/compositor/operations/COM_TranslateOperation.h index e30ba7ff2d79..1c54ec62284c 100644 --- a/source/blender/compositor/operations/COM_TranslateOperation.h +++ b/source/blender/compositor/operations/COM_TranslateOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_TranslateOperation_h_ -#define _COM_TranslateOperation_h_ +#ifndef __COM_TRANSLATEOPERATION_H__ +#define __COM_TRANSLATEOPERATION_H__ #include "COM_NodeOperation.h" @@ -45,7 +45,7 @@ class TranslateOperation : public NodeOperation { float getDeltaX() { return this->m_deltaX * this->m_factorX; } float getDeltaY() { return this->m_deltaY * this->m_factorY; } - + inline void ensureDelta() { if (!this->m_isDeltaSet) { float tempDelta[4]; diff --git a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp index e8dbff9b2d7b..a252af053cca 100644 --- a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp +++ b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp @@ -135,7 +135,7 @@ void VariableSizeBokehBlurOperation::executePixel(float output[4], int x, int y, copy_v4_v4(color_accum, readColor); copy_v4_fl(multiplier_accum, 1.0f); float size_center = tempSize[0] * scalar; - + const int addXStepValue = QualityStepHelper::getStep(); const int addYStepValue = addXStepValue; const int addXStepColor = addXStepValue * COM_NUM_CHANNELS_COLOR; @@ -184,8 +184,8 @@ void VariableSizeBokehBlurOperation::executePixel(float output[4], int x, int y, } void VariableSizeBokehBlurOperation::executeOpenCL(OpenCLDevice *device, - MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, - MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, + MemoryBuffer *outputMemoryBuffer, cl_mem clOutputBuffer, + MemoryBuffer **inputMemoryBuffers, list *clMemToCleanUp, list * /*clKernelsToCleanUp*/) { cl_kernel defocusKernel = device->COM_clCreateKernel("defocusKernel", NULL); @@ -193,7 +193,7 @@ void VariableSizeBokehBlurOperation::executeOpenCL(OpenCLDevice *device, cl_int step = this->getStep(); cl_int maxBlur; cl_float threshold = this->m_threshold; - + MemoryBuffer *sizeMemoryBuffer = this->m_inputSizeProgram->getInputMemoryBuffer(inputMemoryBuffers); const float max_dim = max(m_width, m_height); @@ -212,7 +212,7 @@ void VariableSizeBokehBlurOperation::executeOpenCL(OpenCLDevice *device, clSetKernelArg(defocusKernel, 8, sizeof(cl_float), &threshold); clSetKernelArg(defocusKernel, 9, sizeof(cl_float), &scalar); device->COM_clAttachSizeToKernelParameter(defocusKernel, 10, this); - + device->COM_clEnqueueRange(defocusKernel, outputMemoryBuffer, 11, this); } @@ -243,7 +243,7 @@ bool VariableSizeBokehBlurOperation::determineDependingAreaOfInterest(rcti *inpu bokehInput.xmin = 0; bokehInput.ymax = COM_BLUR_BOKEH_PIXELS; bokehInput.ymin = 0; - + NodeOperation *operation = getInputOperation(2); if (operation->determineDependingAreaOfInterest(&newInput, readOperation, output) ) { @@ -273,7 +273,7 @@ bool VariableSizeBokehBlurOperation::determineDependingAreaOfInterest(rcti *inpu #ifdef COM_DEFOCUS_SEARCH // InverseSearchRadiusOperation -InverseSearchRadiusOperation::InverseSearchRadiusOperation() : NodeOperation() +InverseSearchRadiusOperation::InverseSearchRadiusOperation() : NodeOperation() { this->addInputSocket(COM_DT_VALUE, COM_SC_NO_RESIZE); // radius this->addOutputSocket(COM_DT_COLOR); @@ -281,7 +281,7 @@ InverseSearchRadiusOperation::InverseSearchRadiusOperation() : NodeOperation() this->m_inputRadius = NULL; } -void InverseSearchRadiusOperation::initExecution() +void InverseSearchRadiusOperation::initExecution() { this->m_inputRadius = this->getInputSocketReader(0); } @@ -313,7 +313,7 @@ void *InverseSearchRadiusOperation::initializeTileData(rcti *rect) // float radius = 0.0f; // float maxx = x; // float maxy = y; - + // for (int x2 = 0 ; x2 < DIVIDER ; x2 ++) { // for (int y2 = 0 ; y2 < DIVIDER ; y2 ++) { // this->m_inputRadius->read(temp, rx+x2, ry+y2, COM_PS_NEAREST); @@ -346,7 +346,7 @@ void InverseSearchRadiusOperation::executePixelChunk(float output[4], int x, int buffer->readNoCheck(output, x, y); } -void InverseSearchRadiusOperation::deinitializeTileData(rcti *rect, void *data) +void InverseSearchRadiusOperation::deinitializeTileData(rcti *rect, void *data) { if (data) { MemoryBuffer *mb = (MemoryBuffer *)data; @@ -354,7 +354,7 @@ void InverseSearchRadiusOperation::deinitializeTileData(rcti *rect, void *data) } } -void InverseSearchRadiusOperation::deinitExecution() +void InverseSearchRadiusOperation::deinitExecution() { this->m_inputRadius = NULL; } diff --git a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h index 110bb6b4952c..57ffde6d398c 100644 --- a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h +++ b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.h @@ -46,23 +46,23 @@ class VariableSizeBokehBlurOperation : public NodeOperation, public QualityStepH * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + void *initializeTileData(rcti *rect); - + void deinitializeTileData(rcti *rect, void *data); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); - + void setMaxBlur(int maxRadius) { this->m_maxBlur = maxRadius; } void setThreshold(float threshold) { this->m_threshold = threshold; } @@ -79,29 +79,29 @@ class InverseSearchRadiusOperation : public NodeOperation { SocketReader *m_inputRadius; public: static const int DIVIDER = 4; - + InverseSearchRadiusOperation(); /** * the inner loop of this program */ void executePixelChunk(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); void *initializeTileData(rcti *rect); void deinitializeTileData(rcti *rect, void *data); - + /** * Deinitialize the execution */ void deinitExecution(); - + bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]); - + void setMaxBlur(int maxRadius) { this->m_maxBlur = maxRadius; } }; #endif diff --git a/source/blender/compositor/operations/COM_VectorBlurOperation.h b/source/blender/compositor/operations/COM_VectorBlurOperation.h index 05c2c3183c17..a33761166c65 100644 --- a/source/blender/compositor/operations/COM_VectorBlurOperation.h +++ b/source/blender/compositor/operations/COM_VectorBlurOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_VectorBlurOperation_h -#define _COM_VectorBlurOperation_h +#ifndef __COM_VECTORBLUROPERATION_H__ +#define __COM_VECTORBLUROPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_node_types.h" #include "COM_QualityStepHelper.h" @@ -34,27 +34,27 @@ class VectorBlurOperation : public NodeOperation, public QualityStepHelper { SocketReader *m_inputImageProgram; SocketReader *m_inputSpeedProgram; SocketReader *m_inputZProgram; - + /** * @brief settings of the glare node. */ NodeBlurData *m_settings; - + float *m_cachedInstance; public: VectorBlurOperation(); - + /** * the inner loop of this program */ void executePixel(float output[4], int x, int y, void *data); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ @@ -65,9 +65,9 @@ class VectorBlurOperation : public NodeOperation, public QualityStepHelper { void setVectorBlurSettings(NodeBlurData *settings) { this->m_settings = settings; } bool determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output); protected: - + void generateVectorBlur(float *data, MemoryBuffer *inputImage, MemoryBuffer *inputSpeed, MemoryBuffer *inputZ); - - + + }; #endif diff --git a/source/blender/compositor/operations/COM_VectorCurveOperation.h b/source/blender/compositor/operations/COM_VectorCurveOperation.h index 444f848cb0a6..a5c1cb6d4464 100644 --- a/source/blender/compositor/operations/COM_VectorCurveOperation.h +++ b/source/blender/compositor/operations/COM_VectorCurveOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_VectorCurveOperation_h -#define _COM_VectorCurveOperation_h +#ifndef __COM_VECTORCURVEOPERATION_H__ +#define __COM_VECTORCURVEOPERATION_H__ #include "COM_NodeOperation.h" #include "COM_CurveBaseOperation.h" @@ -33,17 +33,17 @@ class VectorCurveOperation : public CurveBaseOperation { SocketReader *m_inputProgram; public: VectorCurveOperation(); - + /** * the inner loop of this program */ void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); - + /** * Initialize the execution */ void initExecution(); - + /** * Deinitialize the execution */ diff --git a/source/blender/compositor/operations/COM_ViewerOperation.cpp b/source/blender/compositor/operations/COM_ViewerOperation.cpp index 0eff52f4d9a7..51fd5d4dc76c 100644 --- a/source/blender/compositor/operations/COM_ViewerOperation.cpp +++ b/source/blender/compositor/operations/COM_ViewerOperation.cpp @@ -50,7 +50,7 @@ ViewerOperation::ViewerOperation() : NodeOperation() this->m_viewSettings = NULL; this->m_displaySettings = NULL; this->m_useAlphaInput = false; - + this->addInputSocket(COM_DT_COLOR); this->addInputSocket(COM_DT_VALUE); this->addInputSocket(COM_DT_VALUE); @@ -69,7 +69,7 @@ void ViewerOperation::initExecution() this->m_alphaInput = getInputSocketReader(1); this->m_depthInput = getInputSocketReader(2); this->m_doDepthBuffer = (this->m_depthInput != NULL); - + if (isActiveViewerOutput()) { initImage(); } diff --git a/source/blender/compositor/operations/COM_ViewerOperation.h b/source/blender/compositor/operations/COM_ViewerOperation.h index e5eed3e80240..43e305fb2917 100644 --- a/source/blender/compositor/operations/COM_ViewerOperation.h +++ b/source/blender/compositor/operations/COM_ViewerOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ViewerOperation_h -#define _COM_ViewerOperation_h +#ifndef __COM_VIEWEROPERATION_H__ +#define __COM_VIEWEROPERATION_H__ #include "COM_NodeOperation.h" #include "DNA_image_types.h" #include "BLI_rect.h" @@ -45,7 +45,7 @@ class ViewerOperation : public NodeOperation { const ColorManagedViewSettings *m_viewSettings; const ColorManagedDisplaySettings *m_displaySettings; - + SocketReader *m_imageInput; SocketReader *m_alphaInput; SocketReader *m_depthInput; diff --git a/source/blender/compositor/operations/COM_WrapOperation.h b/source/blender/compositor/operations/COM_WrapOperation.h index 4a17b29ede88..4b8d1d8846b7 100644 --- a/source/blender/compositor/operations/COM_WrapOperation.h +++ b/source/blender/compositor/operations/COM_WrapOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_WrapOperation_h_ -#define _COM_WrapOperation_h_ +#ifndef __COM_WRAPOPERATION_H__ +#define __COM_WRAPOPERATION_H__ #include "COM_ReadBufferOperation.h" diff --git a/source/blender/compositor/operations/COM_WriteBufferOperation.cpp b/source/blender/compositor/operations/COM_WriteBufferOperation.cpp index 85602e6741cc..5a34673b2bde 100644 --- a/source/blender/compositor/operations/COM_WriteBufferOperation.cpp +++ b/source/blender/compositor/operations/COM_WriteBufferOperation.cpp @@ -131,7 +131,7 @@ void WriteBufferOperation::executeOpenCLRegion(OpenCLDevice *device, rcti * /*re cl_mem clOutputBuffer = clCreateImage2D(device->getContext(), CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, imageFormat, outputBufferWidth, outputBufferHeight, 0, outputFloatBuffer, &error); if (error != CL_SUCCESS) { printf("CLERROR[%d]: %s\n", error, clewErrorString(error)); } - + // STEP 2 list *clMemToCleanUp = new list(); clMemToCleanUp->push_back(clOutputBuffer); @@ -151,7 +151,7 @@ void WriteBufferOperation::executeOpenCLRegion(OpenCLDevice *device, rcti * /*re if (error != CL_SUCCESS) { printf("CLERROR[%d]: %s\n", error, clewErrorString(error)); } error = clEnqueueReadImage(device->getQueue(), clOutputBuffer, CL_TRUE, origin, region, 0, 0, outputFloatBuffer, 0, NULL, NULL); if (error != CL_SUCCESS) { printf("CLERROR[%d]: %s\n", error, clewErrorString(error)); } - + this->getMemoryProxy()->getBuffer()->copyContentFrom(outputBuffer); // STEP 4 diff --git a/source/blender/compositor/operations/COM_WriteBufferOperation.h b/source/blender/compositor/operations/COM_WriteBufferOperation.h index afcdc70889b7..583d58e7b993 100644 --- a/source/blender/compositor/operations/COM_WriteBufferOperation.h +++ b/source/blender/compositor/operations/COM_WriteBufferOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_WriteBufferOperation_h_ -#define _COM_WriteBufferOperation_h_ +#ifndef __COM_WRITEBUFFEROPERATION_H__ +#define __COM_WRITEBUFFEROPERATION_H__ #include "COM_NodeOperation.h" #include "COM_MemoryProxy.h" @@ -41,7 +41,7 @@ class WriteBufferOperation : public NodeOperation { void executePixelSampled(float output[4], float x, float y, PixelSampler sampler); const bool isWriteBufferOperation() const { return true; } bool isSingleValue() const { return m_single_value; } - + void executeRegion(rcti *rect, unsigned int tileNumber); void initExecution(); void deinitExecution(); diff --git a/source/blender/compositor/operations/COM_ZCombineOperation.h b/source/blender/compositor/operations/COM_ZCombineOperation.h index a89a2c7bd625..be6fb0fe5765 100644 --- a/source/blender/compositor/operations/COM_ZCombineOperation.h +++ b/source/blender/compositor/operations/COM_ZCombineOperation.h @@ -20,8 +20,8 @@ * Monique Dewanchand */ -#ifndef _COM_ZCombineOperation_h -#define _COM_ZCombineOperation_h +#ifndef __COM_ZCOMBINEOPERATION_H__ +#define __COM_ZCOMBINEOPERATION_H__ #include "COM_MixOperation.h" @@ -40,10 +40,10 @@ class ZCombineOperation : public NodeOperation { * Default constructor */ ZCombineOperation(); - + void initExecution(); void deinitExecution(); - + /** * the inner loop of this program */ diff --git a/source/blender/datatoc/datatoc_icon_split.py b/source/blender/datatoc/datatoc_icon_split.py index aae907ec3400..e7cc3a71446d 100755 --- a/source/blender/datatoc/datatoc_icon_split.py +++ b/source/blender/datatoc/datatoc_icon_split.py @@ -68,7 +68,7 @@ def image_from_file(filepath): if bpy is not None: pixels, pixel_w, pixel_h = image_from_file__bpy(filepath) - #else: + # else: # pixels, pixel_w, pixel_h = image_from_file__py(filepath) return pixels, pixel_w, pixel_h @@ -95,12 +95,14 @@ def write_subimage(sub_x, sub_y, sub_w, sub_h, with open(filepath, 'wb') as f: - f.write(struct.pack('<6I', + f.write( + struct.pack( + '<6I', sub_w, sub_h, sub_x, sub_y, # redundant but including to maintain consistency pixel_w, pixel_h, - )) + )) for y in range(sub_h): for x in range(sub_w): @@ -113,8 +115,9 @@ def write_subimage(sub_x, sub_y, sub_w, sub_h, _dice_icon_name_cache = {} -def dice_icon_name(x, y, parts_x, parts_y, - name_style=None, prefix=""): +def dice_icon_name( + x, y, parts_x, parts_y, + name_style=None, prefix=""): """ How to name icons, this is mainly for what name we get in git, the actual names don't really matter, its just nice to have the @@ -143,7 +146,7 @@ def dice_icon_name(x, y, parts_x, parts_y, icon_name = _dice_icon_name_cache[index] # for debugging its handy to sort by number - #~ id_str = "%03d_%s%s.dat" % (index, prefix, icon_name) + # ~ id_str = "%03d_%s%s.dat" % (index, prefix, icon_name) id_str = "%s%s.dat" % (prefix, icon_name) @@ -158,16 +161,18 @@ def dice_icon_name(x, y, parts_x, parts_y, return id_str -def dice(filepath, output, output_prefix, name_style, - parts_x, parts_y, - minx, miny, maxx, maxy, - minx_icon, miny_icon, maxx_icon, maxy_icon, - spacex_icon, spacey_icon, - ): +def dice( + filepath, output, output_prefix, name_style, + parts_x, parts_y, + minx, miny, maxx, maxy, + minx_icon, miny_icon, maxx_icon, maxy_icon, + spacex_icon, spacey_icon, +): - is_simple = (max(minx, miny, maxx, maxy, - minx_icon, miny_icon, maxx_icon, maxy_icon, - spacex_icon, spacey_icon) == 0) + is_simple = (max( + minx, miny, maxx, maxy, + minx_icon, miny_icon, maxx_icon, maxy_icon, + spacex_icon, spacey_icon) == 0) pixels, pixel_w, pixel_h = image_from_file(filepath) @@ -199,9 +204,11 @@ def dice(filepath, output, output_prefix, name_style, for x in range(parts_x): for y in range(parts_y): - id_str = dice_icon_name(x, y, - parts_x, parts_y, - name_style=name_style, prefix=output_prefix) + id_str = dice_icon_name( + x, y, + parts_x, parts_y, + name_style=name_style, prefix=output_prefix + ) filepath = os.path.join(output, id_str) if VERBOSE: print(" writing:", filepath) @@ -235,25 +242,35 @@ def main(): parser = argparse.ArgumentParser(description=__doc__, epilog=epilog) # File path options - parser.add_argument("--image", dest="image", metavar='FILE', - help="Image file") - - parser.add_argument("--output", dest="output", metavar='DIR', - help="Output directory") - - parser.add_argument("--output_prefix", dest="output_prefix", metavar='STRING', - help="Output prefix") + parser.add_argument( + "--image", dest="image", metavar='FILE', + help="Image file", + ) + parser.add_argument( + "--output", dest="output", metavar='DIR', + help="Output directory", + ) + parser.add_argument( + "--output_prefix", dest="output_prefix", metavar='STRING', + help="Output prefix", + ) # Icon naming option - parser.add_argument("--name_style", dest="name_style", metavar='ENUM', type=str, - choices=('', 'UI_ICONS'), - help="The metod used for naming output data") + parser.add_argument( + "--name_style", dest="name_style", metavar='ENUM', type=str, + choices=('', 'UI_ICONS'), + help="The metod used for naming output data", + ) # Options for dicing up the image - parser.add_argument("--parts_x", dest="parts_x", metavar='INT', type=int, - help="Grid X parts") - parser.add_argument("--parts_y", dest="parts_y", metavar='INT', type=int, - help="Grid Y parts") + parser.add_argument( + "--parts_x", dest="parts_x", metavar='INT', type=int, + help="Grid X parts", + ) + parser.add_argument( + "--parts_y", dest="parts_y", metavar='INT', type=int, + help="Grid Y parts", + ) _help = "Inset from the outer edge (in pixels)" parser.add_argument("--minx", dest="minx", metavar='INT', type=int, help=_help) @@ -287,5 +304,6 @@ def main(): args.spacex_icon, args.spacey_icon, ) + if __name__ == "__main__": main() diff --git a/source/blender/datatoc/datatoc_icon_split_to_png.py b/source/blender/datatoc/datatoc_icon_split_to_png.py index 39bbf1110fbd..b583b10b9ff2 100755 --- a/source/blender/datatoc/datatoc_icon_split_to_png.py +++ b/source/blender/datatoc/datatoc_icon_split_to_png.py @@ -67,5 +67,6 @@ def main(): icondata_to_png(file_src, file_dst) + if __name__ == "__main__": main() diff --git a/source/blender/depsgraph/CMakeLists.txt b/source/blender/depsgraph/CMakeLists.txt index 50c0910ef022..ced045e9e2fc 100644 --- a/source/blender/depsgraph/CMakeLists.txt +++ b/source/blender/depsgraph/CMakeLists.txt @@ -100,28 +100,6 @@ set(SRC util/deg_util_function.h ) -if(WITH_CXX11) - add_definitions(-DDEG_STD_UNORDERED_MAP) -elseif(HAVE_STD_UNORDERED_MAP_HEADER) - if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE) - add_definitions(-DDEG_STD_UNORDERED_MAP) - else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - add_definitions(-DDEG_STD_UNORDERED_MAP_IN_TR1_NAMESPACE) - else() - add_definitions(-DDEG_NO_UNORDERED_MAP) - message(STATUS "Replacing unordered_map/set with map/set (warning: slower!)") - endif() - endif() -else() - if(HAVE_UNORDERED_MAP_IN_TR1_NAMESPACE) - add_definitions(-DDEG_TR1_UNORDERED_MAP) - else() - add_definitions(-DDEG_NO_UNORDERED_MAP) - message(STATUS "Replacing unordered_map/set with map/set (warning: slower!)") - endif() -endif() - if(WITH_LEGACY_DEPSGRAPH) add_definitions(-DWITH_LEGACY_DEPSGRAPH) endif() diff --git a/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc b/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc index 026aa309b02f..feaba1a4aa8f 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc @@ -68,7 +68,9 @@ struct CyclesSolverState { : graph(graph), traversal_stack(BLI_stack_new(sizeof(StackEntry), "DEG detect cycles stack")), - num_cycles(0) { + num_cycles(0) + { + /* pass */ } ~CyclesSolverState() { BLI_stack_free(traversal_stack); diff --git a/source/blender/depsgraph/intern/builder/deg_builder_map.cc b/source/blender/depsgraph/intern/builder/deg_builder_map.cc index 218483d1dc53..bf29156c3fef 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_map.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder_map.cc @@ -54,7 +54,8 @@ void BuilderMap::tagBuild(ID *id) { BLI_gset_insert(set, id); } -bool BuilderMap::checkIsBuiltAndTag(ID *id) { +bool BuilderMap::checkIsBuiltAndTag(ID *id) +{ void **key_p; if (!BLI_gset_ensure_p_ex(set, id, &key_p)) { *key_p = id; diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc index b08941014140..953c8db0b3be 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc +++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc @@ -264,7 +264,8 @@ OperationDepsNode *DepsgraphNodeBuilder::find_operation_node( void DepsgraphNodeBuilder::begin_build() { } -void DepsgraphNodeBuilder::build_id(ID* id) { +void DepsgraphNodeBuilder::build_id(ID *id) +{ if (id == NULL) { return; } diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes.h b/source/blender/depsgraph/intern/builder/deg_builder_nodes.h index f2154e58703a..5ecfbf2f6926 100644 --- a/source/blender/depsgraph/intern/builder/deg_builder_nodes.h +++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes.h @@ -126,7 +126,7 @@ struct DepsgraphNodeBuilder { const char *name = "", int name_tag = -1); - void build_id(ID* id); + void build_id(ID *id); void build_scene(Scene *scene); void build_group(Base *base, Group *group); void build_object(Base *base, Object *object); diff --git a/source/blender/depsgraph/intern/depsgraph.cc b/source/blender/depsgraph/intern/depsgraph.cc index 34fb20ee2bac..241c3fb9ac3f 100644 --- a/source/blender/depsgraph/intern/depsgraph.cc +++ b/source/blender/depsgraph/intern/depsgraph.cc @@ -128,9 +128,9 @@ static bool pointer_to_component_node_criteria( bPoseChannel *pchan = (bPoseChannel *)ptr->data; if (prop != NULL && RNA_property_is_idprop(prop)) { *type = DEG_NODE_TYPE_PARAMETERS; - *subdata = ""; - *operation_code = DEG_OPCODE_PARAMETERS_EVAL; - *operation_name = pchan->name; + *operation_code = DEG_OPCODE_ID_PROPERTY; + *operation_name = RNA_property_identifier((PropertyRNA *)prop); + *operation_name_tag = -1; } else { /* Bone - generally, we just want the bone component. */ diff --git a/source/blender/depsgraph/intern/depsgraph_build.cc b/source/blender/depsgraph/intern/depsgraph_build.cc index 1b270e71d64b..d3c34cc63a9b 100644 --- a/source/blender/depsgraph/intern/depsgraph_build.cc +++ b/source/blender/depsgraph/intern/depsgraph_build.cc @@ -287,7 +287,7 @@ void DEG_scene_relations_update(Main *bmain, Scene *scene) BLI_gset_clear(graph->entry_tags, NULL); /* Build new nodes and relations. */ - DEG_graph_build_from_scene(reinterpret_cast< ::Depsgraph * >(graph), + DEG_graph_build_from_scene(reinterpret_cast< ::Depsgraph *>(graph), bmain, scene); @@ -349,7 +349,7 @@ void DEG_add_forcefield_relations(DepsNodeHandle *handle, if (effectors == NULL) { return; } - for (EffectorCache *eff = (EffectorCache*)effectors->first; eff; eff = eff->next) { + for (EffectorCache *eff = (EffectorCache *)effectors->first; eff; eff = eff->next) { if (eff->ob != object && eff->pd->forcefield != skip_forcefield) { DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_TRANSFORM, name); if (eff->psys) { diff --git a/source/blender/depsgraph/util/deg_util_foreach.h b/source/blender/depsgraph/util/deg_util_foreach.h index cb7361fc708e..5484192207b5 100644 --- a/source/blender/depsgraph/util/deg_util_foreach.h +++ b/source/blender/depsgraph/util/deg_util_foreach.h @@ -30,19 +30,4 @@ #pragma once -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# define foreach(x, y) for(x : y) -#elif defined(HAVE_BOOST_FUNCTION_BINDINGS) -# include -# define foreach BOOST_FOREACH -#else -#pragma message("No available foreach() implementation. Using stub instead, disabling new depsgraph") - -#ifndef WITH_LEGACY_DEPSGRAPH -# error "Unable to build new depsgraph and legacy one is disabled." -#endif - -#define DISABLE_NEW_DEPSGRAPH - -# define foreach(x, y) for (x; false; (void)y) -#endif +#define foreach(x, y) for(x : y) diff --git a/source/blender/depsgraph/util/deg_util_function.h b/source/blender/depsgraph/util/deg_util_function.h index 38e753ce9258..8863d92eb746 100644 --- a/source/blender/depsgraph/util/deg_util_function.h +++ b/source/blender/depsgraph/util/deg_util_function.h @@ -30,81 +30,8 @@ #pragma once -#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1900) - #include using std::function; using namespace std::placeholders; #define function_bind std::bind - -#elif defined(HAVE_BOOST_FUNCTION_BINDINGS) - -#include -#include - -using boost::function; -#define function_bind boost::bind - -#else - -#pragma message("No available function binding implementation. Using stub instead, disabling new depsgraph") - -#ifndef WITH_LEGACY_DEPSGRAPH -# error "Unable to build new depsgraph and legacy one is disabled." -#endif - -#define DISABLE_NEW_DEPSGRAPH - -#include "BLI_utildefines.h" -#include - -template -class function { -public: - function() {}; - function(void *) {} - operator bool() const { return false; } - bool operator== (void *) { return false; } - - template - void operator() (T1) { - BLI_assert(!"Should not be used"); - } -}; - -class Wrap { -public: - Wrap() {} - template - Wrap(T /*arg*/) {} -}; - -template -void *function_bind(T func, - Wrap arg1 = Wrap(), - Wrap arg2 = Wrap(), - Wrap arg3 = Wrap(), - Wrap arg4 = Wrap(), - Wrap arg5 = Wrap(), - Wrap arg6 = Wrap(), - Wrap arg7 = Wrap()) -{ - BLI_assert(!"Should not be used"); - (void)func; - (void)arg1; - (void)arg2; - (void)arg3; - (void)arg4; - (void)arg5; - (void)arg6; - (void)arg7; - return NULL; -} - -#define _1 Wrap() -#define _2 Wrap() -#define _3 Wrap() -#define _4 Wrap() - -#endif diff --git a/source/blender/editors/animation/anim_channels_edit.c b/source/blender/editors/animation/anim_channels_edit.c index 1158145ad6b7..0366ef3a026a 100644 --- a/source/blender/editors/animation/anim_channels_edit.c +++ b/source/blender/editors/animation/anim_channels_edit.c @@ -657,7 +657,7 @@ void ANIM_fcurve_delete_from_animdata(bAnimContext *ac, AnimData *adt, FCurve *f /* ****************** Operator Utilities ********************************** */ /* poll callback for being in an Animation Editor channels list region */ -static int animedit_poll_channels_active(bContext *C) +static bool animedit_poll_channels_active(bContext *C) { ScrArea *sa = CTX_wm_area(C); @@ -673,7 +673,7 @@ static int animedit_poll_channels_active(bContext *C) } /* poll callback for Animation Editor channels list region + not in NLA-tweakmode for NLA */ -static int animedit_poll_channels_nla_tweakmode_off(bContext *C) +static bool animedit_poll_channels_nla_tweakmode_off(bContext *C) { ScrArea *sa = CTX_wm_area(C); Scene *scene = CTX_data_scene(C); @@ -1413,7 +1413,7 @@ static void ANIM_OT_channels_move(wmOperatorType *ot) /* ******************** Group Channel Operator ************************ */ -static int animchannels_grouping_poll(bContext *C) +static bool animchannels_grouping_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); SpaceLink *sl; @@ -2188,7 +2188,7 @@ static void ANIM_OT_channels_clean_empty(wmOperatorType *ot) /* ******************* Reenable Disabled Operator ******************* */ -static int animchannels_enable_poll(bContext *C) +static bool animchannels_enable_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); @@ -2262,7 +2262,7 @@ static void ANIM_OT_channels_fcurves_enable(wmOperatorType *ot) /* ****************** Find / Set Filter Operator ******************** */ /* XXX: make this generic? */ -static int animchannels_find_poll(bContext *C) +static bool animchannels_find_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); @@ -3184,7 +3184,7 @@ void ED_operatortypes_animchannels(void) // TODO: check on a poll callback for this, to get hotkeys into menus void ED_keymap_animchannels(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Animation Channels", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Animation Channels", 0, 0); wmKeyMapItem *kmi; /* click-select */ diff --git a/source/blender/editors/animation/anim_markers.c b/source/blender/editors/animation/anim_markers.c index 2450d0740f25..836a2ca948dd 100644 --- a/source/blender/editors/animation/anim_markers.c +++ b/source/blender/editors/animation/anim_markers.c @@ -492,7 +492,7 @@ void ED_markers_draw(const bContext *C, int flag) /* ------------------------ */ /* special poll() which checks if there are selected markers first */ -static int ed_markers_poll_selected_markers(bContext *C) +static bool ed_markers_poll_selected_markers(bContext *C) { ListBase *markers = ED_context_get_markers(C); @@ -504,7 +504,7 @@ static int ed_markers_poll_selected_markers(bContext *C) return ED_markers_get_first_selected(markers) != NULL; } -static int ed_markers_poll_selected_no_locked_markers(bContext *C) +static bool ed_markers_poll_selected_no_locked_markers(bContext *C) { ListBase *markers = ED_context_get_markers(C); ToolSettings *ts = CTX_data_tool_settings(C); @@ -522,7 +522,7 @@ static int ed_markers_poll_selected_no_locked_markers(bContext *C) /* special poll() which checks if there are any markers at all first */ -static int ed_markers_poll_markers_exist(bContext *C) +static bool ed_markers_poll_markers_exist(bContext *C) { ListBase *markers = ED_context_get_markers(C); ToolSettings *ts = CTX_data_tool_settings(C); @@ -1581,7 +1581,7 @@ void ED_operatortypes_marker(void) /* called in screen_ops.c:ED_keymap_screen() */ void ED_keymap_marker(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Markers", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Markers", 0, 0); wmKeyMapItem *kmi; WM_keymap_verify_item(keymap, "MARKER_OT_add", MKEY, KM_PRESS, 0, 0); diff --git a/source/blender/editors/animation/anim_ops.c b/source/blender/editors/animation/anim_ops.c index ea8ba76ffb6c..ce991f64d5d8 100644 --- a/source/blender/editors/animation/anim_ops.c +++ b/source/blender/editors/animation/anim_ops.c @@ -45,6 +45,7 @@ #include "BKE_global.h" #include "BKE_main.h" #include "BKE_sound.h" +#include "BKE_scene.h" #include "UI_view2d.h" @@ -64,7 +65,7 @@ /* ********************** frame change operator ***************************/ /* Check if the operator can be run from the current context */ -static int change_frame_poll(bContext *C) +static bool change_frame_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); @@ -98,8 +99,13 @@ static void change_frame_apply(bContext *C, wmOperator *op) float frame = RNA_float_get(op->ptr, "frame"); bool do_snap = RNA_boolean_get(op->ptr, "snap"); - if (do_snap && CTX_wm_space_seq(C)) { - frame = BKE_sequencer_find_next_prev_edit(scene, frame, SEQ_SIDE_BOTH, true, false, false); + if (do_snap) { + if (CTX_wm_space_seq(C)) { + frame = BKE_sequencer_find_next_prev_edit(scene, frame, SEQ_SIDE_BOTH, true, false, false); + } + else { + frame = BKE_scene_frame_snap_by_seconds(scene, 1.0, frame); + } } /* set the new frame number */ @@ -416,7 +422,7 @@ void ED_operatortypes_anim(void) void ED_keymap_anim(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Animation", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Animation", 0, 0); wmKeyMapItem *kmi; /* frame management */ diff --git a/source/blender/editors/animation/drivers.c b/source/blender/editors/animation/drivers.c index be9875ef95ac..3e4e3a551fe3 100644 --- a/source/blender/editors/animation/drivers.c +++ b/source/blender/editors/animation/drivers.c @@ -806,7 +806,7 @@ static const EnumPropertyItem *driver_mapping_type_itemsf(bContext *C, PointerRN /* Add Driver Button Operator ------------------------ */ -static int add_driver_button_poll(bContext *C) +static bool add_driver_button_poll(bContext *C) { PointerRNA ptr = {{NULL}}; PropertyRNA *prop = NULL; diff --git a/source/blender/editors/animation/keyframes_draw.c b/source/blender/editors/animation/keyframes_draw.c index 6e786873950f..9136bdec34aa 100644 --- a/source/blender/editors/animation/keyframes_draw.c +++ b/source/blender/editors/animation/keyframes_draw.c @@ -1088,4 +1088,3 @@ void mask_to_keylist(bDopeSheet *UNUSED(ads), MaskLayer *masklay, DLRBT_Tree *ke } } } - diff --git a/source/blender/editors/animation/keyframes_edit.c b/source/blender/editors/animation/keyframes_edit.c index 6b24008c4d85..1bbfa6cc9798 100644 --- a/source/blender/editors/animation/keyframes_edit.c +++ b/source/blender/editors/animation/keyframes_edit.c @@ -1471,4 +1471,3 @@ short bezt_selmap_flush(KeyframeEditData *ked, BezTriple *bezt) return 0; } - diff --git a/source/blender/editors/animation/keyframing.c b/source/blender/editors/animation/keyframing.c index 6386ad09e80a..f7cfec4d48a1 100644 --- a/source/blender/editors/animation/keyframing.c +++ b/source/blender/editors/animation/keyframing.c @@ -1312,7 +1312,7 @@ enum { * This is based on the standard ED_operator_areaactive callback, * except that it does special checks for a few spacetypes too... */ -static int modify_key_op_poll(bContext *C) +static bool modify_key_op_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); Scene *scene = CTX_data_scene(C); diff --git a/source/blender/editors/animation/keyingsets.c b/source/blender/editors/animation/keyingsets.c index a2a384832be3..5e4db3ca61c2 100644 --- a/source/blender/editors/animation/keyingsets.c +++ b/source/blender/editors/animation/keyingsets.c @@ -73,14 +73,14 @@ */ /* poll callback for adding default KeyingSet */ -static int keyingset_poll_default_add(bContext *C) +static bool keyingset_poll_default_add(bContext *C) { /* as long as there's an active Scene, it's fine */ return (CTX_data_scene(C) != NULL); } /* poll callback for editing active KeyingSet */ -static int keyingset_poll_active_edit(bContext *C) +static bool keyingset_poll_active_edit(bContext *C) { Scene *scene = CTX_data_scene(C); @@ -92,7 +92,7 @@ static int keyingset_poll_active_edit(bContext *C) } /* poll callback for editing active KeyingSet Path */ -static int keyingset_poll_activePath_edit(bContext *C) +static bool keyingset_poll_activePath_edit(bContext *C) { Scene *scene = CTX_data_scene(C); KeyingSet *ks; diff --git a/source/blender/editors/armature/armature_intern.h b/source/blender/editors/armature/armature_intern.h index 288d9f0f86b9..67b8b266269c 100644 --- a/source/blender/editors/armature/armature_intern.h +++ b/source/blender/editors/armature/armature_intern.h @@ -258,4 +258,3 @@ int bone_looper(struct Object *ob, struct Bone *bone, void *data, #endif /* __ARMATURE_INTERN_H__ */ - diff --git a/source/blender/editors/armature/armature_naming.c b/source/blender/editors/armature/armature_naming.c index 419160e02c0d..fb314fd4ac08 100644 --- a/source/blender/editors/armature/armature_naming.c +++ b/source/blender/editors/armature/armature_naming.c @@ -467,4 +467,3 @@ void ARMATURE_OT_autoside_names(wmOperatorType *ot) /* settings */ ot->prop = RNA_def_enum(ot->srna, "type", axis_items, 0, "Axis", "Axis tag names with"); } - diff --git a/source/blender/editors/armature/armature_ops.c b/source/blender/editors/armature/armature_ops.c index 31a22b41f547..d0b875457987 100644 --- a/source/blender/editors/armature/armature_ops.c +++ b/source/blender/editors/armature/armature_ops.c @@ -201,7 +201,7 @@ void ED_keymap_armature(wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* Armature ------------------------ */ - keymap = WM_keymap_find(keyconf, "Armature", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Armature", 0, 0); keymap->poll = ED_operator_editarmature; /* Armature -> Etch-A-Ton ------------------------ */ @@ -309,7 +309,7 @@ void ED_keymap_armature(wmKeyConfig *keyconf) /* Pose ------------------------ */ /* only set in posemode, by space_view3d listener */ - keymap = WM_keymap_find(keyconf, "Pose", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Pose", 0, 0); keymap->poll = ED_operator_posemode; /* set parent and add object are object-based operators, but we make them @@ -419,4 +419,3 @@ void ED_keymap_armature(wmKeyConfig *keyconf) WM_keymap_add_menu(keymap, "VIEW3D_MT_pose_specials", WKEY, KM_PRESS, 0, 0); WM_keymap_add_menu(keymap, "VIEW3D_MT_pose_propagate", PKEY, KM_PRESS, KM_ALT, 0); } - diff --git a/source/blender/editors/armature/armature_relations.c b/source/blender/editors/armature/armature_relations.c index acdda9980d99..c211f9154ef8 100644 --- a/source/blender/editors/armature/armature_relations.c +++ b/source/blender/editors/armature/armature_relations.c @@ -900,4 +900,3 @@ void ARMATURE_OT_parent_clear(wmOperatorType *ot) ot->prop = RNA_def_enum(ot->srna, "type", prop_editarm_clear_parent_types, 0, "ClearType", "What way to clear parenting"); } - diff --git a/source/blender/editors/armature/armature_select.c b/source/blender/editors/armature/armature_select.c index a4e916b8e633..eb7236715949 100644 --- a/source/blender/editors/armature/armature_select.c +++ b/source/blender/editors/armature/armature_select.c @@ -251,7 +251,7 @@ static int armature_select_linked_invoke(bContext *C, wmOperator *op, const wmEv return OPERATOR_FINISHED; } -static int armature_select_linked_poll(bContext *C) +static bool armature_select_linked_poll(bContext *C) { return (ED_operator_view3d_active(C) && ED_operator_editarmature(C)); } diff --git a/source/blender/editors/armature/editarmature_sketch.c b/source/blender/editors/armature/editarmature_sketch.c index 84eb780b56b9..691da4cbd2b9 100644 --- a/source/blender/editors/armature/editarmature_sketch.c +++ b/source/blender/editors/armature/editarmature_sketch.c @@ -2456,7 +2456,7 @@ static int sketch_draw_preview(bContext *C, wmOperator *op, const wmEvent *event /* ============================================== Poll Functions ============================================= */ -int ED_operator_sketch_mode_active_stroke(bContext *C) +bool ED_operator_sketch_mode_active_stroke(bContext *C) { ToolSettings *ts = CTX_data_tool_settings(C); SK_Sketch *sketch = contextSketch(C, 0); @@ -2472,7 +2472,7 @@ int ED_operator_sketch_mode_active_stroke(bContext *C) } } -static int ED_operator_sketch_mode_gesture(bContext *C) +static bool ED_operator_sketch_mode_gesture(bContext *C) { ToolSettings *ts = CTX_data_tool_settings(C); SK_Sketch *sketch = contextSketch(C, 0); @@ -2489,7 +2489,7 @@ static int ED_operator_sketch_mode_gesture(bContext *C) } } -int ED_operator_sketch_full_mode(bContext *C) +bool ED_operator_sketch_full_mode(bContext *C) { Object *obedit = CTX_data_edit_object(C); ToolSettings *ts = CTX_data_tool_settings(C); @@ -2506,7 +2506,7 @@ int ED_operator_sketch_full_mode(bContext *C) } } -int ED_operator_sketch_mode(const bContext *C) +bool ED_operator_sketch_mode(const bContext *C) { Object *obedit = CTX_data_edit_object(C); ToolSettings *ts = CTX_data_tool_settings(C); @@ -2634,7 +2634,7 @@ void SKETCH_OT_draw_stroke(wmOperatorType *ot) ot->modal = sketch_draw_stroke_modal; ot->cancel = sketch_draw_stroke_cancel; - ot->poll = (int (*)(bContext *))ED_operator_sketch_mode; + ot->poll = (bool (*)(bContext *))ED_operator_sketch_mode; RNA_def_boolean(ot->srna, "snap", 0, "Snap", ""); @@ -2661,4 +2661,3 @@ void SKETCH_OT_gesture(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_BLOCKING; // OPTYPE_UNDO } - diff --git a/source/blender/editors/armature/meshlaplacian.h b/source/blender/editors/armature/meshlaplacian.h index 202ac8e9b701..bd0d28885684 100644 --- a/source/blender/editors/armature/meshlaplacian.h +++ b/source/blender/editors/armature/meshlaplacian.h @@ -70,4 +70,3 @@ void rigid_deform_end(int cancel); /* ED_mesh_deform_bind_callback(...) defined in ED_armature.h */ #endif - diff --git a/source/blender/editors/armature/pose_edit.c b/source/blender/editors/armature/pose_edit.c index 999f846f6e5b..389a8423f232 100644 --- a/source/blender/editors/armature/pose_edit.c +++ b/source/blender/editors/armature/pose_edit.c @@ -277,7 +277,7 @@ void POSE_OT_paths_calculate(wmOperatorType *ot) /* --------- */ -static int pose_update_paths_poll(bContext *C) +static bool pose_update_paths_poll(bContext *C) { if (ED_operator_posemode_exclusive(C)) { Object *ob = CTX_data_active_object(C); @@ -760,7 +760,7 @@ void POSE_OT_rotation_mode_set(wmOperatorType *ot) /* ********************************************** */ -static int armature_layers_poll(bContext *C) +static bool armature_layers_poll(bContext *C) { /* Armature layers operators can be used in posemode OR editmode for armatures */ return ED_operator_posemode(C) || ED_operator_editarmature(C); @@ -793,7 +793,7 @@ static int pose_armature_layers_showall_exec(bContext *C, wmOperator *op) bArmature *arm = armature_layers_get_data(&ob); PointerRNA ptr; int maxLayers = (RNA_boolean_get(op->ptr, "all")) ? 32 : 16; - int layers[32] = {0}; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32] = {false}; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ int i; /* sanity checking */ @@ -844,7 +844,7 @@ static int armature_layers_invoke(bContext *C, wmOperator *op, const wmEvent *ev Object *ob = CTX_data_active_object(C); bArmature *arm = armature_layers_get_data(&ob); PointerRNA ptr; - int layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ /* sanity checking */ if (arm == NULL) @@ -865,7 +865,7 @@ static int armature_layers_exec(bContext *C, wmOperator *op) Object *ob = CTX_data_active_object(C); bArmature *arm = armature_layers_get_data(&ob); PointerRNA ptr; - int layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ if (arm == NULL) { return OPERATOR_CANCELLED; @@ -908,7 +908,7 @@ void ARMATURE_OT_armature_layers(wmOperatorType *ot) /* Present a popup to get the layers that should be used */ static int pose_bone_layers_invoke(bContext *C, wmOperator *op, const wmEvent *event) { - int layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ /* get layers that are active already */ CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones) @@ -934,7 +934,7 @@ static int pose_bone_layers_exec(bContext *C, wmOperator *op) { Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C)); PointerRNA ptr; - int layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ if (ob == NULL || ob->data == NULL) { return OPERATOR_CANCELLED; @@ -982,7 +982,7 @@ void POSE_OT_bone_layers(wmOperatorType *ot) /* Present a popup to get the layers that should be used */ static int armature_bone_layers_invoke(bContext *C, wmOperator *op, const wmEvent *event) { - int layers[32] = {0}; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32] = {0}; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ /* get layers that are active already */ CTX_DATA_BEGIN (C, EditBone *, ebone, selected_editable_bones) @@ -1011,7 +1011,7 @@ static int armature_bone_layers_exec(bContext *C, wmOperator *op) Object *ob = CTX_data_edit_object(C); bArmature *arm = (ob) ? ob->data : NULL; PointerRNA ptr; - int layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ + bool layers[32]; /* hardcoded for now - we can only have 32 armature layers, so this should be fine... */ /* get the values set in the operator properties */ RNA_boolean_get_array(op->ptr, "layers", layers); @@ -1215,4 +1215,3 @@ void POSE_OT_quaternions_flip(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/armature/pose_lib.c b/source/blender/editors/armature/pose_lib.c index 62c37e5d3faa..9bb1caee0672 100644 --- a/source/blender/editors/armature/pose_lib.c +++ b/source/blender/editors/armature/pose_lib.c @@ -173,7 +173,7 @@ static Object *get_poselib_object(bContext *C) } /* Poll callback for operators that require existing PoseLib data (with poses) to work */ -static int has_poselib_pose_data_poll(bContext *C) +static bool has_poselib_pose_data_poll(bContext *C) { Object *ob = get_poselib_object(C); return (ob && ob->poselib); @@ -182,7 +182,7 @@ static int has_poselib_pose_data_poll(bContext *C) /* Poll callback for operators that require existing PoseLib data (with poses) * as they need to do some editing work on those poses (i.e. not on lib-linked actions) */ -static int has_poselib_pose_data_for_editing_poll(bContext *C) +static bool has_poselib_pose_data_for_editing_poll(bContext *C) { Object *ob = get_poselib_object(C); return (ob && ob->poselib && !ID_IS_LINKED(ob->poselib)); @@ -378,7 +378,7 @@ void POSELIB_OT_action_sanitize(wmOperatorType *ot) /* ------------------------------------------ */ /* Poll callback for adding poses to a PoseLib */ -static int poselib_add_poll(bContext *C) +static bool poselib_add_poll(bContext *C) { /* There are 2 cases we need to be careful with: * 1) When this operator is invoked from a hotkey, there may be no PoseLib yet diff --git a/source/blender/editors/armature/pose_select.c b/source/blender/editors/armature/pose_select.c index 1389b26a1e1e..ecfaa41b0b59 100644 --- a/source/blender/editors/armature/pose_select.c +++ b/source/blender/editors/armature/pose_select.c @@ -320,7 +320,7 @@ static int pose_select_connected_invoke(bContext *C, wmOperator *op, const wmEve return OPERATOR_FINISHED; } -static int pose_select_linked_poll(bContext *C) +static bool pose_select_linked_poll(bContext *C) { return (ED_operator_view3d_active(C) && ED_operator_posemode(C)); } @@ -948,4 +948,3 @@ void POSE_OT_select_mirror(wmOperatorType *ot) RNA_def_boolean(ot->srna, "only_active", false, "Active Only", "Only operate on the active bone"); RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection"); } - diff --git a/source/blender/editors/armature/pose_transform.c b/source/blender/editors/armature/pose_transform.c index 43dfa2f13d7a..2d8f5dbecbe5 100644 --- a/source/blender/editors/armature/pose_transform.c +++ b/source/blender/editors/armature/pose_transform.c @@ -164,8 +164,8 @@ static int apply_armature_pose2bones_exec(bContext *C, wmOperator *op) curbone->roll2 += pchan->roll2; curbone->ease1 += pchan->ease1; curbone->ease2 += pchan->ease2; - curbone->scaleIn += pchan->scaleIn; - curbone->scaleOut += pchan->scaleOut; + curbone->scaleIn *= pchan->scaleIn; + curbone->scaleOut *= pchan->scaleOut; pchan->curveInX = pchan->curveOutX = 0.0f; pchan->curveInY = pchan->curveOutY = 0.0f; diff --git a/source/blender/editors/curve/curve_ops.c b/source/blender/editors/curve/curve_ops.c index 5d27e13ed17a..4a801d9de64f 100644 --- a/source/blender/editors/curve/curve_ops.c +++ b/source/blender/editors/curve/curve_ops.c @@ -169,7 +169,7 @@ void ED_keymap_curve(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "Font", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Font", 0, 0); keymap->poll = ED_operator_editfont; /* only set in editmode font, by space_view3d listener */ @@ -229,7 +229,7 @@ void ED_keymap_curve(wmKeyConfig *keyconf) RNA_boolean_set(kmi->ptr, "accent", true); /* accented characters */ /* only set in editmode curve, by space_view3d listener */ - keymap = WM_keymap_find(keyconf, "Curve", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Curve", 0, 0); keymap->poll = ED_operator_editsurfcurve; WM_keymap_add_menu(keymap, "INFO_MT_edit_curve_add", AKEY, KM_PRESS, KM_SHIFT, 0); diff --git a/source/blender/editors/curve/editcurve.c b/source/blender/editors/curve/editcurve.c index b0efc2ddc507..b046e1b6ae73 100644 --- a/source/blender/editors/curve/editcurve.c +++ b/source/blender/editors/curve/editcurve.c @@ -840,6 +840,7 @@ static void calc_shapeKeys(Object *obedit, ListBase *newnurbs) } nu = nu->next; + newnu = newnu->next; } if (apply_offset) { @@ -6225,7 +6226,7 @@ bool ED_curve_active_center(Curve *cu, float center[3]) /******************** Match texture space operator ***********************/ -static int match_texture_space_poll(bContext *C) +static bool match_texture_space_poll(bContext *C) { Object *object = CTX_data_active_object(C); diff --git a/source/blender/editors/gpencil/gpencil_brush.c b/source/blender/editors/gpencil/gpencil_brush.c index c35b64de991e..0f51f12793ab 100644 --- a/source/blender/editors/gpencil/gpencil_brush.c +++ b/source/blender/editors/gpencil/gpencil_brush.c @@ -1174,7 +1174,7 @@ static void gpsculpt_brush_exit(bContext *C, wmOperator *op) } /* poll callback for stroke sculpting operator(s) */ -static int gpsculpt_brush_poll(bContext *C) +static bool gpsculpt_brush_poll(bContext *C) { /* NOTE: this is a bit slower, but is the most accurate... */ return CTX_DATA_COUNT(C, editable_gpencil_strokes) != 0; diff --git a/source/blender/editors/gpencil/gpencil_convert.c b/source/blender/editors/gpencil/gpencil_convert.c index 67d3272a90d1..e0c2e116b8a5 100644 --- a/source/blender/editors/gpencil/gpencil_convert.c +++ b/source/blender/editors/gpencil/gpencil_convert.c @@ -1282,7 +1282,7 @@ static void gp_convert_set_end_frame(struct Main *UNUSED(main), struct Scene *UN } } -static int gp_convert_poll(bContext *C) +static bool gp_convert_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); bGPDlayer *gpl = NULL; @@ -1371,8 +1371,9 @@ static int gp_convert_layer_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static bool gp_convert_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) +static bool gp_convert_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop) { + PointerRNA *ptr = op->ptr; const char *prop_id = RNA_property_identifier(prop); const bool link_strokes = RNA_boolean_get(ptr, "use_link_strokes"); int timing_mode = RNA_enum_get(ptr, "timing_mode"); @@ -1435,18 +1436,6 @@ static bool gp_convert_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) return false; } -static void gp_convert_ui(bContext *C, wmOperator *op) -{ - uiLayout *layout = op->layout; - wmWindowManager *wm = CTX_wm_manager(C); - PointerRNA ptr; - - RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); - - /* Main auto-draw call */ - uiDefAutoButsRNA(layout, &ptr, gp_convert_draw_check_prop, '\0'); -} - void GPENCIL_OT_convert(wmOperatorType *ot) { PropertyRNA *prop; @@ -1460,7 +1449,7 @@ void GPENCIL_OT_convert(wmOperatorType *ot) ot->invoke = WM_menu_invoke; ot->exec = gp_convert_layer_exec; ot->poll = gp_convert_poll; - ot->ui = gp_convert_ui; + ot->poll_property = gp_convert_poll_property; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; diff --git a/source/blender/editors/gpencil/gpencil_data.c b/source/blender/editors/gpencil/gpencil_data.c index 9f437f28f0fd..c28fea0fc417 100644 --- a/source/blender/editors/gpencil/gpencil_data.c +++ b/source/blender/editors/gpencil/gpencil_data.c @@ -131,7 +131,7 @@ void GPENCIL_OT_data_add(wmOperatorType *ot) /* ******************* Unlink Data ************************ */ /* poll callback for adding data/layers - special */ -static int gp_data_unlink_poll(bContext *C) +static bool gp_data_unlink_poll(bContext *C) { bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL); @@ -420,7 +420,7 @@ void GPENCIL_OT_hide(wmOperatorType *ot) /* ********************** Show All Layers ***************************** */ /* poll callback for showing layers */ -static int gp_reveal_poll(bContext *C) +static bool gp_reveal_poll(bContext *C) { return ED_gpencil_data_get_active(C) != NULL; } @@ -1811,7 +1811,7 @@ void GPENCIL_OT_palettecolor_hide(wmOperatorType *ot) /* ********************** Show All Colors ***************************** */ /* poll callback for showing colors */ -static int gp_palettecolor_reveal_poll(bContext *C) +static bool gp_palettecolor_reveal_poll(bContext *C) { return ED_gpencil_data_get_active(C) != NULL; } diff --git a/source/blender/editors/gpencil/gpencil_edit.c b/source/blender/editors/gpencil/gpencil_edit.c index cdd8d5714003..936cf571b4ad 100644 --- a/source/blender/editors/gpencil/gpencil_edit.c +++ b/source/blender/editors/gpencil/gpencil_edit.c @@ -84,7 +84,7 @@ /* ************************************************ */ /* Stroke Edit Mode Management */ -static int gpencil_editmode_toggle_poll(bContext *C) +static bool gpencil_editmode_toggle_poll(bContext *C) { return ED_gpencil_data_get_active(C) != NULL; } @@ -129,7 +129,7 @@ void GPENCIL_OT_editmode_toggle(wmOperatorType *ot) /* Stroke Editing Operators */ /* poll callback for all stroke editing operators */ -static int gp_stroke_edit_poll(bContext *C) +static bool gp_stroke_edit_poll(bContext *C) { /* NOTE: this is a bit slower, but is the most accurate... */ return CTX_DATA_COUNT(C, editable_gpencil_strokes) != 0; @@ -515,7 +515,7 @@ void GPENCIL_OT_copy(wmOperatorType *ot) /* --------------------- */ /* Paste selected strokes */ -static int gp_strokes_paste_poll(bContext *C) +static bool gp_strokes_paste_poll(bContext *C) { /* 1) Must have GP datablock to paste to * - We don't need to have an active layer though, as that can easily get added @@ -782,7 +782,7 @@ void GPENCIL_OT_move_to_layer(wmOperatorType *ot) /* ********************* Add Blank Frame *************************** */ /* Basically the same as the drawing op */ -static int UNUSED_FUNCTION(gp_blank_frame_add_poll)(bContext *C) +static bool UNUSED_FUNCTION(gp_blank_frame_add_poll)(bContext *C) { if (ED_operator_regionactive(C)) { /* check if current context can support GPencil data */ @@ -862,7 +862,7 @@ void GPENCIL_OT_blank_frame_add(wmOperatorType *ot) /* ******************* Delete Active Frame ************************ */ -static int gp_actframe_delete_poll(bContext *C) +static bool gp_actframe_delete_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd); @@ -914,7 +914,7 @@ void GPENCIL_OT_active_frame_delete(wmOperatorType *ot) /* **************** Delete All Active Frames ****************** */ -static int gp_actframe_delete_all_poll(bContext *C) +static bool gp_actframe_delete_all_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); @@ -1368,7 +1368,7 @@ void GPENCIL_OT_dissolve(wmOperatorType *ot) /* NOTE: For now, we only allow these in the 3D view, as other editors do not * define a cursor or gridstep which can be used */ -static int gp_snap_poll(bContext *C) +static bool gp_snap_poll(bContext *C) { bGPdata *gpd = CTX_data_gpencil_data(C); ScrArea *sa = CTX_wm_area(C); @@ -2088,7 +2088,7 @@ typedef enum eGP_ReprojectModes { GP_REPROJECT_SURFACE, } eGP_ReprojectModes; -static int gp_strokes_reproject_poll(bContext *C) +static bool gp_strokes_reproject_poll(bContext *C) { /* 2 Requirements: * - 1) Editable GP data diff --git a/source/blender/editors/gpencil/gpencil_intern.h b/source/blender/editors/gpencil/gpencil_intern.h index 33af6cab9155..d7e60d2a0ce1 100644 --- a/source/blender/editors/gpencil/gpencil_intern.h +++ b/source/blender/editors/gpencil/gpencil_intern.h @@ -93,12 +93,12 @@ bool gp_point_xy_to_3d(GP_SpaceConversion *gsc, struct Scene *scene, const float /* Poll Callbacks ------------------------------------ */ /* gpencil_utils.c */ -int gp_add_poll(struct bContext *C); -int gp_active_layer_poll(struct bContext *C); -int gp_active_brush_poll(struct bContext *C); -int gp_active_palette_poll(struct bContext *C); -int gp_active_palettecolor_poll(struct bContext *C); -int gp_brush_crt_presets_poll(bContext *C); +bool gp_add_poll(struct bContext *C); +bool gp_active_layer_poll(struct bContext *C); +bool gp_active_brush_poll(struct bContext *C); +bool gp_active_palette_poll(struct bContext *C); +bool gp_active_palettecolor_poll(struct bContext *C); +bool gp_brush_crt_presets_poll(bContext *C); /* Copy/Paste Buffer --------------------------------- */ /* gpencil_edit.c */ diff --git a/source/blender/editors/gpencil/gpencil_interpolate.c b/source/blender/editors/gpencil/gpencil_interpolate.c index ff3f5b208580..e2d70803695f 100644 --- a/source/blender/editors/gpencil/gpencil_interpolate.c +++ b/source/blender/editors/gpencil/gpencil_interpolate.c @@ -85,7 +85,7 @@ /* Core/Shared Utilities */ /* Poll callback for interpolation operators */ -static int gpencil_view3d_poll(bContext *C) +static bool gpencil_view3d_poll(bContext *C) { bGPdata *gpd = CTX_data_gpencil_data(C); bGPDlayer *gpl = CTX_data_active_gpencil_layer(C); @@ -1032,7 +1032,7 @@ void GPENCIL_OT_interpolate_sequence(wmOperatorType *ot) /* ******************** Remove Breakdowns ************************ */ -static int gpencil_interpolate_reverse_poll(bContext *C) +static bool gpencil_interpolate_reverse_poll(bContext *C) { if (!gpencil_view3d_poll(C)) { return 0; diff --git a/source/blender/editors/gpencil/gpencil_ops.c b/source/blender/editors/gpencil/gpencil_ops.c index 84a106856b30..e209b7f46e72 100644 --- a/source/blender/editors/gpencil/gpencil_ops.c +++ b/source/blender/editors/gpencil/gpencil_ops.c @@ -55,7 +55,7 @@ /* Generic Drawing Keymap */ static void ed_keymap_gpencil_general(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Grease Pencil", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Grease Pencil", 0, 0); wmKeyMapItem *kmi; /* Draw --------------------------------------- */ @@ -114,7 +114,7 @@ static void ed_keymap_gpencil_general(wmKeyConfig *keyconf) /* ==================== */ /* Poll callback for stroke editing mode */ -static int gp_stroke_editmode_poll(bContext *C) +static bool gp_stroke_editmode_poll(bContext *C) { bGPdata *gpd = CTX_data_gpencil_data(C); return (gpd && (gpd->flag & GP_DATA_STROKE_EDITMODE)); @@ -123,7 +123,7 @@ static int gp_stroke_editmode_poll(bContext *C) /* Stroke Editing Keymap - Only when editmode is enabled */ static void ed_keymap_gpencil_editing(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Grease Pencil Stroke Edit Mode", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Grease Pencil Stroke Edit Mode", 0, 0); wmKeyMapItem *kmi; /* set poll callback - so that this keymap only gets enabled when stroke editmode is enabled */ diff --git a/source/blender/editors/gpencil/gpencil_paint.c b/source/blender/editors/gpencil/gpencil_paint.c index 2471ba76ae27..fd1ff8573170 100644 --- a/source/blender/editors/gpencil/gpencil_paint.c +++ b/source/blender/editors/gpencil/gpencil_paint.c @@ -195,7 +195,7 @@ static void gp_session_validatebuffer(tGPsdata *p); /* Context Wrangling... */ /* check if context is suitable for drawing */ -static int gpencil_draw_poll(bContext *C) +static bool gpencil_draw_poll(bContext *C) { if (ED_operator_regionactive(C)) { /* check if current context can support GPencil data */ diff --git a/source/blender/editors/gpencil/gpencil_select.c b/source/blender/editors/gpencil/gpencil_select.c index ac0b046e499d..dd556e992649 100644 --- a/source/blender/editors/gpencil/gpencil_select.c +++ b/source/blender/editors/gpencil/gpencil_select.c @@ -67,7 +67,7 @@ /* ********************************************** */ /* Polling callbacks */ -static int gpencil_select_poll(bContext *C) +static bool gpencil_select_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); diff --git a/source/blender/editors/gpencil/gpencil_utils.c b/source/blender/editors/gpencil/gpencil_utils.c index 0a35dd90f02a..e6f3b40024fa 100644 --- a/source/blender/editors/gpencil/gpencil_utils.c +++ b/source/blender/editors/gpencil/gpencil_utils.c @@ -260,14 +260,14 @@ bool ED_gpencil_has_keyframe_v3d(Scene *scene, Object *ob, int cfra) /* Poll Callbacks */ /* poll callback for adding data/layers - special */ -int gp_add_poll(bContext *C) +bool gp_add_poll(bContext *C) { /* the base line we have is that we have somewhere to add Grease Pencil data */ return ED_gpencil_data_get_pointers(C, NULL) != NULL; } /* poll callback for checking if there is an active layer */ -int gp_active_layer_poll(bContext *C) +bool gp_active_layer_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd); @@ -276,7 +276,7 @@ int gp_active_layer_poll(bContext *C) } /* poll callback for checking if there is an active brush */ -int gp_active_brush_poll(bContext *C) +bool gp_active_brush_poll(bContext *C) { ToolSettings *ts = CTX_data_tool_settings(C); bGPDbrush *brush = BKE_gpencil_brush_getactive(ts); @@ -285,7 +285,7 @@ int gp_active_brush_poll(bContext *C) } /* poll callback for checking if there is an active palette */ -int gp_active_palette_poll(bContext *C) +bool gp_active_palette_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); bGPDpalette *palette = BKE_gpencil_palette_getactive(gpd); @@ -294,7 +294,7 @@ int gp_active_palette_poll(bContext *C) } /* poll callback for checking if there is an active palette color */ -int gp_active_palettecolor_poll(bContext *C) +bool gp_active_palettecolor_poll(bContext *C) { bGPdata *gpd = ED_gpencil_data_get_active(C); bGPDpalette *palette = BKE_gpencil_palette_getactive(gpd); diff --git a/source/blender/editors/include/BIF_gl.h b/source/blender/editors/include/BIF_gl.h index 4ec1e7914992..ac896216e510 100644 --- a/source/blender/editors/include/BIF_gl.h +++ b/source/blender/editors/include/BIF_gl.h @@ -101,4 +101,3 @@ BLI_INLINE void glScale2fv(const float vec[2]) { glScalef(UNPACK2(vec), 0.0); } BLI_INLINE void glRotate3fv(const float angle, const float vec[3]) { glRotatef(angle, UNPACK3(vec)); } #endif /* #ifdef __BIF_GL_H__ */ - diff --git a/source/blender/editors/include/BIF_glutil.h b/source/blender/editors/include/BIF_glutil.h index d3d2c465d463..efd66dd79cf7 100644 --- a/source/blender/editors/include/BIF_glutil.h +++ b/source/blender/editors/include/BIF_glutil.h @@ -231,4 +231,3 @@ void glaDrawImBuf_glsl_ctx_clipping(const struct bContext *C, void glaDrawBorderCorners(const struct rcti *border, float zoomx, float zoomy); #endif /* __BIF_GLUTIL_H__ */ - diff --git a/source/blender/editors/include/ED_anim_api.h b/source/blender/editors/include/ED_anim_api.h index 258ead4c1d2e..28dc233e1c85 100644 --- a/source/blender/editors/include/ED_anim_api.h +++ b/source/blender/editors/include/ED_anim_api.h @@ -709,4 +709,3 @@ void ED_animedit_unlink_action(struct bContext *C, struct ID *id, /* ************************************************ */ #endif /* __ED_ANIM_API_H__ */ - diff --git a/source/blender/editors/include/ED_armature.h b/source/blender/editors/include/ED_armature.h index 1bc0c8fab648..d6e385ab5a64 100644 --- a/source/blender/editors/include/ED_armature.h +++ b/source/blender/editors/include/ED_armature.h @@ -208,9 +208,9 @@ struct Object *ED_pose_object_from_context(struct bContext *C); /* sketch */ -int ED_operator_sketch_mode_active_stroke(struct bContext *C); -int ED_operator_sketch_full_mode(struct bContext *C); -int ED_operator_sketch_mode(const struct bContext *C); +bool ED_operator_sketch_mode_active_stroke(struct bContext *C); +bool ED_operator_sketch_full_mode(struct bContext *C); +bool ED_operator_sketch_mode(const struct bContext *C); void BIF_convertSketch(struct bContext *C); void BIF_deleteSketch(struct bContext *C); diff --git a/source/blender/editors/include/ED_clip.h b/source/blender/editors/include/ED_clip.h index 91f8b39f7b94..4844d96e6e86 100644 --- a/source/blender/editors/include/ED_clip.h +++ b/source/blender/editors/include/ED_clip.h @@ -44,13 +44,13 @@ struct Scene; /* ** clip_editor.c ** */ /* common poll functions */ -int ED_space_clip_poll(struct bContext *C); +bool ED_space_clip_poll(struct bContext *C); -int ED_space_clip_view_clip_poll(struct bContext *C); +bool ED_space_clip_view_clip_poll(struct bContext *C); -int ED_space_clip_tracking_poll(struct bContext *C); -int ED_space_clip_maskedit_poll(struct bContext *C); -int ED_space_clip_maskedit_mask_poll(struct bContext *C); +bool ED_space_clip_tracking_poll(struct bContext *C); +bool ED_space_clip_maskedit_poll(struct bContext *C); +bool ED_space_clip_maskedit_mask_poll(struct bContext *C); void ED_space_clip_get_size(struct SpaceClip *sc, int *width, int *height); void ED_space_clip_get_size_fl(struct SpaceClip *sc, float size[2]); diff --git a/source/blender/editors/include/ED_datafiles.h b/source/blender/editors/include/ED_datafiles.h index 1559fc8f3020..7d509d1243a3 100644 --- a/source/blender/editors/include/ED_datafiles.h +++ b/source/blender/editors/include/ED_datafiles.h @@ -242,4 +242,3 @@ extern char datatoc_mc24_jpg[]; #endif /* __ED_DATAFILES_H__ */ - diff --git a/source/blender/editors/include/ED_fileselect.h b/source/blender/editors/include/ED_fileselect.h index bbd27df46ceb..e2c8ecf68122 100644 --- a/source/blender/editors/include/ED_fileselect.h +++ b/source/blender/editors/include/ED_fileselect.h @@ -145,4 +145,3 @@ char *ED_fsmenu_entry_get_name(struct FSMenuEntry *fsentry); void ED_fsmenu_entry_set_name(struct FSMenuEntry *fsentry, const char *name); #endif /* __ED_FILESELECT_H__ */ - diff --git a/source/blender/editors/include/ED_image.h b/source/blender/editors/include/ED_image.h index 845d61ec355e..e5631c4e1916 100644 --- a/source/blender/editors/include/ED_image.h +++ b/source/blender/editors/include/ED_image.h @@ -76,8 +76,8 @@ bool ED_space_image_show_uvedit(struct SpaceImage *sima, struct Object *obedit); bool ED_space_image_paint_curve(const struct bContext *C); bool ED_space_image_check_show_maskedit(struct Scene *scene, struct SpaceImage *sima); -int ED_space_image_maskedit_poll(struct bContext *C); -int ED_space_image_maskedit_mask_poll(struct bContext *C); +bool ED_space_image_maskedit_poll(struct bContext *C); +bool ED_space_image_maskedit_mask_poll(struct bContext *C); void ED_image_draw_info(struct Scene *scene, struct ARegion *ar, bool color_manage, bool use_default_view, int channels, int x, int y, const unsigned char cp[4], const float fp[4], const float linearcol[4], int *zp, float *zpf); @@ -85,4 +85,3 @@ void ED_image_draw_info(struct Scene *scene, struct ARegion *ar, bool color_mana bool ED_space_image_show_cache(struct SpaceImage *sima); #endif /* __ED_IMAGE_H__ */ - diff --git a/source/blender/editors/include/ED_keyframing.h b/source/blender/editors/include/ED_keyframing.h index b73c997060a6..06b8197de970 100644 --- a/source/blender/editors/include/ED_keyframing.h +++ b/source/blender/editors/include/ED_keyframing.h @@ -131,7 +131,7 @@ struct KeyingSetInfo; struct ExtensionRNA; /* Polling Callback for KeyingSets */ -typedef int (*cbKeyingSet_Poll)(struct KeyingSetInfo *ksi, struct bContext *C); +typedef bool (*cbKeyingSet_Poll)(struct KeyingSetInfo *ksi, struct bContext *C); /* Context Iterator Callback for KeyingSets */ typedef void (*cbKeyingSet_Iterator)(struct KeyingSetInfo *ksi, struct bContext *C, struct KeyingSet *ks); /* Property Specifier Callback for KeyingSets (called from iterators) */ diff --git a/source/blender/editors/include/ED_mesh.h b/source/blender/editors/include/ED_mesh.h index d3e3c7b45fa6..c2094b4215ce 100644 --- a/source/blender/editors/include/ED_mesh.h +++ b/source/blender/editors/include/ED_mesh.h @@ -198,7 +198,7 @@ void ED_operatormacros_mesh(void); void ED_keymap_mesh(struct wmKeyConfig *keyconf); /* editmesh_tools.c (could be moved) */ -void EMBM_project_snap_verts(struct bContext *C, struct ARegion *ar, struct BMEditMesh *em); +void EDBM_project_snap_verts(struct bContext *C, struct ARegion *ar, struct BMEditMesh *em); /* editface.c */ @@ -280,7 +280,7 @@ void ED_mesh_edges_remove(struct Mesh *mesh, struct ReportList *reports, int cou void ED_mesh_vertices_remove(struct Mesh *mesh, struct ReportList *reports, int count); void ED_mesh_calc_tessface(struct Mesh *mesh, bool free_mpoly); -void ED_mesh_update(struct Mesh *mesh, struct bContext *C, int calc_edges, int calc_tessface); +void ED_mesh_update(struct Mesh *mesh, struct bContext *C, bool calc_edges, bool calc_tessface); void ED_mesh_uv_texture_ensure(struct Mesh *me, const char *name); int ED_mesh_uv_texture_add(struct Mesh *me, const char *name, const bool active_set); diff --git a/source/blender/editors/include/ED_node.h b/source/blender/editors/include/ED_node.h index 4d203ebe4ef3..c2382f7f9b95 100644 --- a/source/blender/editors/include/ED_node.h +++ b/source/blender/editors/include/ED_node.h @@ -110,4 +110,3 @@ void ED_operatormacros_node(void); bool ED_space_node_color_sample(struct Main *bmain, struct SpaceNode *snode, struct ARegion *ar, int mval[2], float r_col[3]); #endif /* __ED_NODE_H__ */ - diff --git a/source/blender/editors/include/ED_object.h b/source/blender/editors/include/ED_object.h index a8536e6f71cd..d40c4f8dec9c 100644 --- a/source/blender/editors/include/ED_object.h +++ b/source/blender/editors/include/ED_object.h @@ -53,8 +53,10 @@ struct wmOperatorType; struct PointerRNA; struct PropertyRNA; struct EnumPropertyItem; +struct wmWindowManager; #include "DNA_object_enums.h" +#include "BLI_compiler_attrs.h" /* object_edit.c */ struct Object *ED_object_context(struct bContext *C); /* context.object */ diff --git a/source/blender/editors/include/ED_particle.h b/source/blender/editors/include/ED_particle.h index 395eddf3eddf..001118873320 100644 --- a/source/blender/editors/include/ED_particle.h +++ b/source/blender/editors/include/ED_particle.h @@ -57,7 +57,7 @@ void PE_update_object(struct Main *bmain, struct Scene *scene, struct Object *ob /* selection tools */ int PE_mouse_particles(struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle); -int PE_border_select(struct bContext *C, struct rcti *rect, bool select, bool extend); +int PE_border_select(struct bContext *C, const struct rcti *rect, bool select, bool extend); int PE_circle_select(struct bContext *C, int selecting, const int mval[2], float rad); int PE_lasso_select(struct bContext *C, const int mcords[][2], const short moves, bool extend, bool select); void PE_deselect_all_visible(struct PTCacheEdit *edit); @@ -66,4 +66,3 @@ void PE_deselect_all_visible(struct PTCacheEdit *edit); void ED_particle_undosys_type(struct UndoType *ut); #endif /* __ED_PARTICLE_H__ */ - diff --git a/source/blender/editors/include/ED_physics.h b/source/blender/editors/include/ED_physics.h index fed842c969e2..32444beb0fe7 100644 --- a/source/blender/editors/include/ED_physics.h +++ b/source/blender/editors/include/ED_physics.h @@ -40,9 +40,9 @@ struct Scene; struct Object; /* particle_edit.c */ -int PE_poll(struct bContext *C); -int PE_hair_poll(struct bContext *C); -int PE_poll_view3d(struct bContext *C); +bool PE_poll(struct bContext *C); +bool PE_hair_poll(struct bContext *C); +bool PE_poll_view3d(struct bContext *C); /* rigidbody_object.c */ bool ED_rigidbody_object_add(struct Main *bmain, struct Scene *scene, struct Object *ob, int type, struct ReportList *reports); @@ -57,4 +57,3 @@ void ED_operatortypes_physics(void); void ED_keymap_physics(struct wmKeyConfig *keyconf); #endif /* __ED_PHYSICS_H__ */ - diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h index eca5628eb236..b4d9a2629cfe 100644 --- a/source/blender/editors/include/ED_screen.h +++ b/source/blender/editors/include/ED_screen.h @@ -135,60 +135,60 @@ void ED_operatortypes_screen(void); void ED_keymap_screen(struct wmKeyConfig *keyconf); /* operators; context poll callbacks */ -int ED_operator_screenactive(struct bContext *C); -int ED_operator_screen_mainwinactive(struct bContext *C); -int ED_operator_areaactive(struct bContext *C); -int ED_operator_regionactive(struct bContext *C); - -int ED_operator_scene(struct bContext *C); -int ED_operator_scene_editable(struct bContext *C); -int ED_operator_objectmode(struct bContext *C); - -int ED_operator_view3d_active(struct bContext *C); -int ED_operator_region_view3d_active(struct bContext *C); -int ED_operator_animview_active(struct bContext *C); -int ED_operator_timeline_active(struct bContext *C); -int ED_operator_outliner_active(struct bContext *C); -int ED_operator_outliner_active_no_editobject(struct bContext *C); -int ED_operator_file_active(struct bContext *C); -int ED_operator_action_active(struct bContext *C); -int ED_operator_buttons_active(struct bContext *C); -int ED_operator_node_active(struct bContext *C); -int ED_operator_node_editable(struct bContext *C); -int ED_operator_graphedit_active(struct bContext *C); -int ED_operator_sequencer_active(struct bContext *C); -int ED_operator_sequencer_active_editable(struct bContext *C); -int ED_operator_image_active(struct bContext *C); -int ED_operator_nla_active(struct bContext *C); -int ED_operator_logic_active(struct bContext *C); -int ED_operator_info_active(struct bContext *C); -int ED_operator_console_active(struct bContext *C); - - -int ED_operator_object_active(struct bContext *C); -int ED_operator_object_active_editable(struct bContext *C); -int ED_operator_object_active_editable_mesh(struct bContext *C); -int ED_operator_object_active_editable_font(struct bContext *C); -int ED_operator_editmesh(struct bContext *C); -int ED_operator_editmesh_view3d(struct bContext *C); -int ED_operator_editmesh_region_view3d(struct bContext *C); -int ED_operator_editarmature(struct bContext *C); -int ED_operator_editcurve(struct bContext *C); -int ED_operator_editcurve_3d(struct bContext *C); -int ED_operator_editsurf(struct bContext *C); -int ED_operator_editsurfcurve(struct bContext *C); -int ED_operator_editsurfcurve_region_view3d(struct bContext *C); -int ED_operator_editfont(struct bContext *C); -int ED_operator_editlattice(struct bContext *C); -int ED_operator_editmball(struct bContext *C); -int ED_operator_uvedit(struct bContext *C); -int ED_operator_uvedit_space_image(struct bContext *C); -int ED_operator_uvmap(struct bContext *C); -int ED_operator_posemode_exclusive(struct bContext *C); -int ED_operator_posemode_context(struct bContext *C); -int ED_operator_posemode(struct bContext *C); -int ED_operator_posemode_local(struct bContext *C); -int ED_operator_mask(struct bContext *C); +bool ED_operator_screenactive(struct bContext *C); +bool ED_operator_screen_mainwinactive(struct bContext *C); +bool ED_operator_areaactive(struct bContext *C); +bool ED_operator_regionactive(struct bContext *C); + +bool ED_operator_scene(struct bContext *C); +bool ED_operator_scene_editable(struct bContext *C); +bool ED_operator_objectmode(struct bContext *C); + +bool ED_operator_view3d_active(struct bContext *C); +bool ED_operator_region_view3d_active(struct bContext *C); +bool ED_operator_animview_active(struct bContext *C); +bool ED_operator_timeline_active(struct bContext *C); +bool ED_operator_outliner_active(struct bContext *C); +bool ED_operator_outliner_active_no_editobject(struct bContext *C); +bool ED_operator_file_active(struct bContext *C); +bool ED_operator_action_active(struct bContext *C); +bool ED_operator_buttons_active(struct bContext *C); +bool ED_operator_node_active(struct bContext *C); +bool ED_operator_node_editable(struct bContext *C); +bool ED_operator_graphedit_active(struct bContext *C); +bool ED_operator_sequencer_active(struct bContext *C); +bool ED_operator_sequencer_active_editable(struct bContext *C); +bool ED_operator_image_active(struct bContext *C); +bool ED_operator_nla_active(struct bContext *C); +bool ED_operator_logic_active(struct bContext *C); +bool ED_operator_info_active(struct bContext *C); +bool ED_operator_console_active(struct bContext *C); + + +bool ED_operator_object_active(struct bContext *C); +bool ED_operator_object_active_editable(struct bContext *C); +bool ED_operator_object_active_editable_mesh(struct bContext *C); +bool ED_operator_object_active_editable_font(struct bContext *C); +bool ED_operator_editmesh(struct bContext *C); +bool ED_operator_editmesh_view3d(struct bContext *C); +bool ED_operator_editmesh_region_view3d(struct bContext *C); +bool ED_operator_editarmature(struct bContext *C); +bool ED_operator_editcurve(struct bContext *C); +bool ED_operator_editcurve_3d(struct bContext *C); +bool ED_operator_editsurf(struct bContext *C); +bool ED_operator_editsurfcurve(struct bContext *C); +bool ED_operator_editsurfcurve_region_view3d(struct bContext *C); +bool ED_operator_editfont(struct bContext *C); +bool ED_operator_editlattice(struct bContext *C); +bool ED_operator_editmball(struct bContext *C); +bool ED_operator_uvedit(struct bContext *C); +bool ED_operator_uvedit_space_image(struct bContext *C); +bool ED_operator_uvmap(struct bContext *C); +bool ED_operator_posemode_exclusive(struct bContext *C); +bool ED_operator_posemode_context(struct bContext *C); +bool ED_operator_posemode(struct bContext *C); +bool ED_operator_posemode_local(struct bContext *C); +bool ED_operator_mask(struct bContext *C); /* Cache display helpers */ @@ -207,4 +207,3 @@ void ED_region_cache_draw_cached_segments(const struct ARegion *ar, const int nu #define ED_KEYMAP_HEADER 64 #endif /* __ED_SCREEN_H__ */ - diff --git a/source/blender/editors/include/ED_sequencer.h b/source/blender/editors/include/ED_sequencer.h index 94885c2abe03..18446966c4f9 100644 --- a/source/blender/editors/include/ED_sequencer.h +++ b/source/blender/editors/include/ED_sequencer.h @@ -35,9 +35,9 @@ struct SpaceSeq; void ED_sequencer_select_sequence_single(struct Scene *scene, struct Sequence *seq, bool deselect_all); void ED_sequencer_deselect_all(struct Scene *scene); -int ED_space_sequencer_maskedit_mask_poll(struct bContext *C); +bool ED_space_sequencer_maskedit_mask_poll(struct bContext *C); bool ED_space_sequencer_check_show_maskedit(struct SpaceSeq *sseq, struct Scene *scene); -int ED_space_sequencer_maskedit_poll(struct bContext *C); +bool ED_space_sequencer_maskedit_poll(struct bContext *C); bool ED_space_sequencer_check_show_imbuf(struct SpaceSeq *sseq); bool ED_space_sequencer_check_show_strip(struct SpaceSeq *sseq); diff --git a/source/blender/editors/include/ED_sound.h b/source/blender/editors/include/ED_sound.h index 87ab9041305e..b4b424b0318f 100644 --- a/source/blender/editors/include/ED_sound.h +++ b/source/blender/editors/include/ED_sound.h @@ -34,4 +34,3 @@ void ED_operatortypes_sound(void); #endif /* __ED_SOUND_H__ */ - diff --git a/source/blender/editors/include/ED_transverts.h b/source/blender/editors/include/ED_transverts.h index 9005d55feff0..363bb31c3dc9 100644 --- a/source/blender/editors/include/ED_transverts.h +++ b/source/blender/editors/include/ED_transverts.h @@ -50,7 +50,7 @@ void ED_transverts_create_from_obedit(TransVertStore *tvs, struct Object *obedit void ED_transverts_update_obedit(TransVertStore *tvs, struct Object *obedit); void ED_transverts_free(TransVertStore *tvs); bool ED_transverts_check_obedit(Object *obedit); -int ED_transverts_poll(struct bContext *C); +bool ED_transverts_poll(struct bContext *C); /* currently only used for bmesh index values */ enum { diff --git a/source/blender/editors/include/ED_undo.h b/source/blender/editors/include/ED_undo.h index 084c97dba2a1..784ae33f3b00 100644 --- a/source/blender/editors/include/ED_undo.h +++ b/source/blender/editors/include/ED_undo.h @@ -61,4 +61,3 @@ void ED_undosys_type_free(void); struct MemFile *ED_undosys_stack_memfile_get_active(struct UndoStack *ustack); #endif /* __ED_UNDO_H__ */ - diff --git a/source/blender/editors/include/ED_util.h b/source/blender/editors/include/ED_util.h index 5a0512719261..741c586d41fc 100644 --- a/source/blender/editors/include/ED_util.h +++ b/source/blender/editors/include/ED_util.h @@ -56,4 +56,3 @@ void apply_keyb_grid(int shift, int ctrl, float *val, float fac1, float fac2, fl void unpack_menu(struct bContext *C, const char *opname, const char *id_name, const char *abs_name, const char *folder, struct PackedFile *pf); #endif /* __ED_UTIL_H__ */ - diff --git a/source/blender/editors/include/ED_uvedit.h b/source/blender/editors/include/ED_uvedit.h index e84106aec20e..e9398bbd94c5 100644 --- a/source/blender/editors/include/ED_uvedit.h +++ b/source/blender/editors/include/ED_uvedit.h @@ -136,4 +136,3 @@ void ED_uvedit_draw_main( void ED_uvedit_buttons_register(struct ARegionType *art); #endif /* __ED_UVEDIT_H__ */ - diff --git a/source/blender/editors/include/ED_view3d.h b/source/blender/editors/include/ED_view3d.h index 8cde96fc898d..82411ba7401d 100644 --- a/source/blender/editors/include/ED_view3d.h +++ b/source/blender/editors/include/ED_view3d.h @@ -92,7 +92,7 @@ typedef struct ViewDepths { } ViewDepths; float *ED_view3d_cursor3d_get(struct Scene *scene, struct View3D *v3d); -void ED_view3d_cursor3d_position(struct bContext *C, float fp[3], const int mval[2]); +void ED_view3d_cursor3d_position(struct bContext *C, const int mval[2], float cursor_co[3]); void ED_view3d_cursor3d_update(struct bContext *C, const int mval[2]); struct Camera *ED_view3d_camera_data_get(struct View3D *v3d, struct RegionView3D *rv3d); @@ -343,7 +343,7 @@ bool edge_inside_circle(const float cent[2], float radius, const float screen_co /* get 3d region from context, also if mouse is in header or toolbar */ struct RegionView3D *ED_view3d_context_rv3d(struct bContext *C); bool ED_view3d_context_user_region(struct bContext *C, struct View3D **r_v3d, struct ARegion **r_ar); -int ED_operator_rv3d_user_region_poll(struct bContext *C); +bool ED_operator_rv3d_user_region_poll(struct bContext *C); void ED_view3d_init_mats_rv3d(struct Object *ob, struct RegionView3D *rv3d); void ED_view3d_init_mats_rv3d_gl(struct Object *ob, struct RegionView3D *rv3d); @@ -354,7 +354,7 @@ void ED_view3d_check_mats_rv3d(struct RegionView3D *rv3d); # define ED_view3d_clear_mats_rv3d(rv3d) (void)(rv3d) # define ED_view3d_check_mats_rv3d(rv3d) (void)(rv3d) #endif -int ED_view3d_scene_layer_set(int lay, const int *values, int *active); +int ED_view3d_scene_layer_set(int lay, const bool *values, int *active); struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d); void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat); diff --git a/source/blender/editors/include/UI_icons.h b/source/blender/editors/include/UI_icons.h index 0c5631abe3be..24a44fe307c8 100644 --- a/source/blender/editors/include/UI_icons.h +++ b/source/blender/editors/include/UI_icons.h @@ -1033,4 +1033,3 @@ DEF_VICO(COLORSET_17_VEC) DEF_VICO(COLORSET_18_VEC) DEF_VICO(COLORSET_19_VEC) DEF_VICO(COLORSET_20_VEC) - diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h index 8aeb96a18c5d..b22cab296d15 100644 --- a/source/blender/editors/include/UI_interface.h +++ b/source/blender/editors/include/UI_interface.h @@ -379,6 +379,11 @@ typedef void (*uiMenuHandleFunc)(struct bContext *C, void *arg, int event); */ typedef bool (*uiMenuStepFunc)(struct bContext *C, int direction, void *arg1); + +/* interface_query.c */ +bool UI_block_is_empty(const uiBlock *block); + + /* interface_region_menu_popup.c */ /* Popup Menus * @@ -395,6 +400,7 @@ uiPopupMenu *UI_popup_menu_begin_ex( struct bContext *C, const char *title, const char *block_name, int icon) ATTR_NONNULL(); void UI_popup_menu_end(struct bContext *C, struct uiPopupMenu *head); +bool UI_popup_menu_end_or_cancel(struct bContext *C, struct uiPopupMenu *head); struct uiLayout *UI_popup_menu_layout(uiPopupMenu *head); void UI_popup_menu_reports(struct bContext *C, struct ReportList *reports) ATTR_NONNULL(); @@ -505,7 +511,7 @@ void UI_but_drag_set_path(uiBut *but, const char *path, const bool use_free); void UI_but_drag_set_name(uiBut *but, const char *name); void UI_but_drag_set_value(uiBut *but); void UI_but_drag_set_image( - uiBut *but, const char *path, int icon, struct ImBuf *ima, float scale, const bool use_free); + uiBut *but, const char *path, int icon, struct ImBuf *ima, float scale, const bool use_free); bool UI_but_active_drop_name(struct bContext *C); bool UI_but_active_drop_color(struct bContext *C); @@ -543,13 +549,14 @@ bool UI_but_online_manual_id_from_active( * - R: RNA * - O: operator */ -uiBut *uiDefBut(uiBlock *block, - int type, int retval, const char *str, - int x1, int y1, - short x2, short y2, - void *poin, - float min, float max, - float a1, float a2, const char *tip); +uiBut *uiDefBut( + uiBlock *block, + int type, int retval, const char *str, + int x1, int y1, + short x2, short y2, + void *poin, + float min, float max, + float a1, float a2, const char *tip); uiBut *uiDefButF(uiBlock *block, int type, int retval, const char *str, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefButBitF(uiBlock *block, int type, int bit, int retval, const char *str, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefButI(uiBlock *block, int type, int retval, const char *str, int x, int y, short width, short height, int *poin, float min, float max, float a1, float a2, const char *tip); @@ -563,13 +570,14 @@ uiBut *uiDefButR_prop(uiBlock *block, int type, int retval, const char *str, int uiBut *uiDefButO(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x, int y, short width, short height, const char *tip); uiBut *uiDefButO_ptr(uiBlock *block, int type, struct wmOperatorType *ot, int opcontext, const char *str, int x, int y, short width, short height, const char *tip); -uiBut *uiDefIconBut(uiBlock *block, - int type, int retval, int icon, - int x1, int y1, - short x2, short y2, - void *poin, - float min, float max, - float a1, float a2, const char *tip); +uiBut *uiDefIconBut( + uiBlock *block, + int type, int retval, int icon, + int x1, int y1, + short x2, short y2, + void *poin, + float min, float max, + float a1, float a2, const char *tip); uiBut *uiDefIconButF(uiBlock *block, int type, int retval, int icon, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefIconButBitF(uiBlock *block, int type, int bit, int retval, int icon, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefIconButI(uiBlock *block, int type, int retval, int icon, int x, int y, short width, short height, int *poin, float min, float max, float a1, float a2, const char *tip); @@ -583,13 +591,14 @@ uiBut *uiDefIconButR_prop(uiBlock *block, int type, int retval, int icon, int x, uiBut *uiDefIconButO(uiBlock *block, int type, const char *opname, int opcontext, int icon, int x, int y, short width, short height, const char *tip); uiBut *uiDefIconButO_ptr(uiBlock *block, int type, struct wmOperatorType *ot, int opcontext, int icon, int x, int y, short width, short height, const char *tip); -uiBut *uiDefIconTextBut(uiBlock *block, - int type, int retval, int icon, const char *str, - int x1, int y1, - short x2, short y2, - void *poin, - float min, float max, - float a1, float a2, const char *tip); +uiBut *uiDefIconTextBut( + uiBlock *block, + int type, int retval, int icon, const char *str, + int x1, int y1, + short x2, short y2, + void *poin, + float min, float max, + float a1, float a2, const char *tip); uiBut *uiDefIconTextButF(uiBlock *block, int type, int retval, int icon, const char *str, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefIconTextButBitF(uiBlock *block, int type, int bit, int retval, int icon, const char *str, int x, int y, short width, short height, float *poin, float min, float max, float a1, float a2, const char *tip); uiBut *uiDefIconTextButI(uiBlock *block, int type, int retval, int icon, const char *str, int x, int y, short width, short height, int *poin, float min, float max, float a1, float a2, const char *tip); @@ -688,12 +697,17 @@ uiBut *uiDefKeyevtButS(uiBlock *block, int retval, const char *str, int x, int y uiBut *uiDefHotKeyevtButS(uiBlock *block, int retval, const char *str, int x, int y, short width, short height, short *keypoin, short *modkeypoin, const char *tip); uiBut *uiDefSearchBut(uiBlock *block, void *arg, int retval, int icon, int maxlen, int x, int y, short width, short height, float a1, float a2, const char *tip); -uiBut *uiDefSearchButO_ptr(uiBlock *block, struct wmOperatorType *ot, struct IDProperty *properties, - void *arg, int retval, int icon, int maxlen, int x, int y, - short width, short height, float a1, float a2, const char *tip); +uiBut *uiDefSearchButO_ptr( + uiBlock *block, struct wmOperatorType *ot, struct IDProperty *properties, + void *arg, int retval, int icon, int maxlen, int x, int y, + short width, short height, float a1, float a2, const char *tip); uiBut *uiDefAutoButR(uiBlock *block, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, const char *name, int icon, int x1, int y1, int x2, int y2); -int uiDefAutoButsRNA(uiLayout *layout, struct PointerRNA *ptr, bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *), const char label_align); + +int uiDefAutoButsRNA( + uiLayout *layout, struct PointerRNA *ptr, + bool (*check_prop)(struct PointerRNA *ptr, struct PropertyRNA *prop, void *user_data), void *user_data, + const char label_align); /* Links * @@ -739,8 +753,9 @@ void UI_but_func_tooltip_set(uiBut *but, uiButToolTipFunc func, void *argN); void UI_but_tooltip_refresh(struct bContext *C, uiBut *but); void UI_but_tooltip_timer_remove(struct bContext *C, uiBut *but); -bool UI_textbutton_activate_rna(const struct bContext *C, struct ARegion *ar, - const void *rna_poin_data, const char *rna_prop_id); +bool UI_textbutton_activate_rna( + const struct bContext *C, struct ARegion *ar, + const void *rna_poin_data, const char *rna_prop_id); bool UI_textbutton_activate_but(const struct bContext *C, uiBut *but); void UI_but_focus_on_enter_event(struct wmWindow *win, uiBut *but); @@ -774,8 +789,9 @@ void UI_panels_end(const struct bContext *C, struct ARegion *ar, int *x, int *y) void UI_panels_draw(const struct bContext *C, struct ARegion *ar); struct Panel *UI_panel_find_by_type(struct ARegion *ar, struct PanelType *pt); -struct Panel *UI_panel_begin(struct ScrArea *sa, struct ARegion *ar, uiBlock *block, - struct PanelType *pt, struct Panel *pa, bool *r_open); +struct Panel *UI_panel_begin( + struct ScrArea *sa, struct ARegion *ar, uiBlock *block, + struct PanelType *pt, struct Panel *pa, bool *r_open); void UI_panel_end(uiBlock *block, int width, int height); void UI_panels_scale(struct ARegion *ar, float new_width); @@ -912,14 +928,15 @@ float uiLayoutGetScaleX(uiLayout *layout); float uiLayoutGetScaleY(uiLayout *layout); /* layout specifiers */ -uiLayout *uiLayoutRow(uiLayout *layout, int align); -uiLayout *uiLayoutColumn(uiLayout *layout, int align); -uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, int align); +uiLayout *uiLayoutRow(uiLayout *layout, bool align); +uiLayout *uiLayoutColumn(uiLayout *layout, bool align); +uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, bool align); uiLayout *uiLayoutBox(uiLayout *layout); -uiLayout *uiLayoutListBox(uiLayout *layout, struct uiList *ui_list, struct PointerRNA *ptr, struct PropertyRNA *prop, - struct PointerRNA *actptr, struct PropertyRNA *actprop); -uiLayout *uiLayoutAbsolute(uiLayout *layout, int align); -uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, int align); +uiLayout *uiLayoutListBox( + uiLayout *layout, struct uiList *ui_list, struct PointerRNA *ptr, struct PropertyRNA *prop, + struct PointerRNA *actptr, struct PropertyRNA *actprop); +uiLayout *uiLayoutAbsolute(uiLayout *layout, bool align); +uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, bool align); uiLayout *uiLayoutOverlap(uiLayout *layout); uiBlock *uiLayoutAbsoluteBlock(uiLayout *layout); uiLayout *uiLayoutRadial(uiLayout *layout); @@ -935,29 +952,36 @@ void uiTemplateIDBrowse( void uiTemplateIDPreview( uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int rows, int cols, int filter); -void uiTemplateAnyID(uiLayout *layout, struct PointerRNA *ptr, const char *propname, - const char *proptypename, const char *text); -void uiTemplatePathBuilder(uiLayout *layout, struct PointerRNA *ptr, const char *propname, - struct PointerRNA *root_ptr, const char *text); +void uiTemplateAnyID( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, + const char *proptypename, const char *text); +void uiTemplatePathBuilder( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, + struct PointerRNA *root_ptr, const char *text); uiLayout *uiTemplateModifier(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr); uiLayout *uiTemplateConstraint(uiLayout *layout, struct PointerRNA *ptr); -void uiTemplatePreview(uiLayout *layout, struct bContext *C, struct ID *id, int show_buttons, struct ID *parent, - struct MTex *slot, const char *preview_id); -void uiTemplateColorRamp(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int expand); -void uiTemplateIconView(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int show_labels, float icon_scale); +void uiTemplatePreview( + uiLayout *layout, struct bContext *C, struct ID *id, bool show_buttons, struct ID *parent, + struct MTex *slot, const char *preview_id); +void uiTemplateColorRamp(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool expand); +void uiTemplateIconView(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool show_labels, float icon_scale); void uiTemplateHistogram(uiLayout *layout, struct PointerRNA *ptr, const char *propname); void uiTemplateWaveform(uiLayout *layout, struct PointerRNA *ptr, const char *propname); void uiTemplateVectorscope(uiLayout *layout, struct PointerRNA *ptr, const char *propname); -void uiTemplateCurveMapping(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int type, - int levels, int brush, int neg_slope); -void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int value_slider, int lock, int lock_luminosity, int cubic); -void uiTemplatePalette(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int color); -void uiTemplateLayers(uiLayout *layout, struct PointerRNA *ptr, const char *propname, - PointerRNA *used_ptr, const char *used_propname, int active_layer); -void uiTemplateGameStates(uiLayout *layout, struct PointerRNA *ptr, const char *propname, - PointerRNA *used_ptr, const char *used_propname, int active_state); -void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, int compact, int multiview, int cubemap); -void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, int color_management); +void uiTemplateCurveMapping( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, int type, + bool levels, bool brush, bool neg_slope); +void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool value_slider, bool lock, bool lock_luminosity, bool cubic); +void uiTemplatePalette(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool color); +void uiTemplateCryptoPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname); +void uiTemplateLayers( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, + PointerRNA *used_ptr, const char *used_propname, int active_layer); +void uiTemplateGameStates( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, + PointerRNA *used_ptr, const char *used_propname, int active_state); +void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, bool compact, bool multiview, bool cubemap); +void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, bool color_management); void uiTemplateImageStereo3d(uiLayout *layout, struct PointerRNA *stereo3d_format_ptr); void uiTemplateImageViews(uiLayout *layout, struct PointerRNA *imaptr); void uiTemplateImageFormatViews(uiLayout *layout, PointerRNA *imfptr, PointerRNA *ptr); @@ -966,9 +990,9 @@ void uiTemplateImageInfo(uiLayout *layout, struct bContext *C, struct Image *ima void uiTemplateRunningJobs(uiLayout *layout, struct bContext *C); void UI_but_func_operator_search(uiBut *but); void uiTemplateOperatorSearch(uiLayout *layout); -void uiTemplateOperatorPropertyButs(const struct bContext *C, uiLayout *layout, struct wmOperator *op, - bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *), - const char label_align, const short flag); +void uiTemplateOperatorPropertyButs( + const struct bContext *C, uiLayout *layout, struct wmOperator *op, + const char label_align, const short flag); void uiTemplateHeader3D(uiLayout *layout, struct bContext *C); void uiTemplateEditModeSelection(uiLayout *layout, struct bContext *C); void uiTemplateReportsBanner(uiLayout *layout, struct bContext *C); @@ -979,18 +1003,19 @@ void uiTemplateCacheFile(uiLayout *layout, struct bContext *C, struct PointerRNA /* Default UIList class name, keep in sync with its declaration in bl_ui/__init__.py */ #define UI_UL_DEFAULT_CLASS_NAME "UI_UL_list" -void uiTemplateList(uiLayout *layout, struct bContext *C, const char *listtype_name, const char *list_id, - struct PointerRNA *dataptr, const char *propname, struct PointerRNA *active_dataptr, - const char *active_propname, const char *item_dyntip_propname, - int rows, int maxrows, int layout_type, int columns); +void uiTemplateList( + uiLayout *layout, struct bContext *C, const char *listtype_name, const char *list_id, + struct PointerRNA *dataptr, const char *propname, struct PointerRNA *active_dataptr, + const char *active_propname, const char *item_dyntip_propname, + int rows, int maxrows, int layout_type, int columns); void uiTemplateNodeLink(uiLayout *layout, struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *input); void uiTemplateNodeView(uiLayout *layout, struct bContext *C, struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *input); void uiTemplateTextureUser(uiLayout *layout, struct bContext *C); void uiTemplateTextureShow(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop); -void uiTemplateMovieClip(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, int compact); +void uiTemplateMovieClip(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, bool compact); void uiTemplateTrack(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname); -void uiTemplateMarker(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *userptr, PointerRNA *trackptr, int cmpact); +void uiTemplateMarker(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *userptr, PointerRNA *trackptr, bool compact); void uiTemplateMovieclipInformation(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr); void uiTemplateColorspaceSettings(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname); @@ -1026,8 +1051,10 @@ void uiItemR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int void uiItemFullR(uiLayout *layout, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, int value, int flag, const char *name, int icon); void uiItemEnumR_prop(uiLayout *layout, const char *name, int icon, struct PointerRNA *ptr, PropertyRNA *prop, int value); void uiItemEnumR(uiLayout *layout, const char *name, int icon, struct PointerRNA *ptr, const char *propname, int value); +void uiItemEnumR_string_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *value, const char *name, int icon); void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, const char *name, int icon); void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname); +void uiItemPointerR_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, struct PointerRNA *searchptr, PropertyRNA *searchprop, const char *name, int icon); void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, const char *name, int icon); void uiItemsFullEnumO( uiLayout *layout, const char *opname, const char *propname, @@ -1039,7 +1066,7 @@ void uiItemsFullEnumO_items( void uiItemL(uiLayout *layout, const char *name, int icon); /* label */ void uiItemLDrag(uiLayout *layout, struct PointerRNA *ptr, const char *name, int icon); /* label icon for dragging */ -void uiItemM(uiLayout *layout, struct bContext *C, const char *menuname, const char *name, int icon); /* menu */ +void uiItemM(uiLayout *layout, const char *menuname, const char *name, int icon); /* menu */ void uiItemV(uiLayout *layout, const char *name, int icon, int argval); /* value */ void uiItemS(uiLayout *layout); /* separator */ @@ -1059,7 +1086,7 @@ void ED_operatortypes_ui(void); void ED_keymap_ui(struct wmKeyConfig *keyconf); void UI_drop_color_copy(struct wmDrag *drag, struct wmDropBox *drop); -int UI_drop_color_poll(struct bContext *C, struct wmDrag *drag, const struct wmEvent *event); +bool UI_drop_color_poll(struct bContext *C, struct wmDrag *drag, const struct wmEvent *event); bool UI_context_copy_to_selected_list( struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, diff --git a/source/blender/editors/interface/CMakeLists.txt b/source/blender/editors/interface/CMakeLists.txt index 0adc315fd692..2c984d64266c 100644 --- a/source/blender/editors/interface/CMakeLists.txt +++ b/source/blender/editors/interface/CMakeLists.txt @@ -42,6 +42,7 @@ set(SRC interface.c interface_align.c interface_anim.c + interface_context_menu.c interface_draw.c interface_eyedropper.c interface_eyedropper_color.c @@ -54,13 +55,14 @@ set(SRC interface_layout.c interface_ops.c interface_panel.c - interface_regions.c + interface_query.c interface_region_color_picker.c interface_region_menu_pie.c interface_region_menu_popup.c interface_region_popup.c interface_region_search.c interface_region_tooltip.c + interface_regions.c interface_style.c interface_templates.c interface_utils.c diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c index 895190ab8856..82ae4de07aff 100644 --- a/source/blender/editors/interface/interface.c +++ b/source/blender/editors/interface/interface.c @@ -93,18 +93,6 @@ static void ui_but_free(const bContext *C, uiBut *but); -bool ui_block_is_menu(const uiBlock *block) -{ - return (((block->flag & UI_BLOCK_LOOP) != 0) && - /* non-menu popups use keep-open, so check this is off */ - ((block->flag & UI_BLOCK_KEEP_OPEN) == 0)); -} - -bool ui_block_is_pie_menu(const uiBlock *block) -{ - return ((block->flag & UI_BLOCK_RADIAL) != 0); -} - static bool ui_but_is_unit_radians_ex(UnitSettings *unit, const int unit_type) { return (unit->system_rotation == USER_UNIT_ROT_RADIANS && unit_type == PROP_UNIT_ROTATION); @@ -954,7 +942,6 @@ static void ui_menu_block_set_keyaccels(uiBlock *block) * but this could be supported */ void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const bool do_strip) { - if (do_strip && (but->flag & UI_BUT_HAS_SEP_CHAR)) { char *cpoin = strrchr(but->str, UI_SEP_CHAR); if (cpoin) { @@ -973,10 +960,11 @@ void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const bool do_str else { butstr_orig = BLI_strdup(but->str); } - BLI_snprintf(but->strdata, - sizeof(but->strdata), - "%s" UI_SEP_CHAR_S "%s", - butstr_orig, shortcut_str); + BLI_snprintf( + but->strdata, + sizeof(but->strdata), + "%s" UI_SEP_CHAR_S "%s", + butstr_orig, shortcut_str); MEM_freeN(butstr_orig); but->str = but->strdata; but->flag |= UI_BUT_HAS_SEP_CHAR; @@ -984,43 +972,68 @@ void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const bool do_str } } -static bool ui_but_event_operator_string( +/* -------------------------------------------------------------------- */ +/** \name Find Key Shortcut for Button + * + * - #ui_but_event_operator_string (and helpers) + * - #ui_but_event_property_operator_string + * \{ */ + +static bool ui_but_event_operator_string_from_operator( const bContext *C, uiBut *but, char *buf, const size_t buf_len) { - MenuType *mt; + BLI_assert(but->optype != NULL); bool found = false; + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - if (but->optype) { - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - - if (WM_key_event_operator_string( - C, but->optype->idname, but->opcontext, prop, true, - buf, buf_len)) - { - found = true; - } + if (WM_key_event_operator_string( + C, but->optype->idname, but->opcontext, prop, true, + buf, buf_len)) + { + found = true; } - else if ((mt = UI_but_menutype_get(but))) { - IDProperty *prop_menu; - IDProperty *prop_menu_name; + return found; +} - /* annoying, create a property */ - IDPropertyTemplate val = {0}; - prop_menu = IDP_New(IDP_GROUP, &val, __func__); /* dummy, name is unimportant */ - IDP_AddToGroup(prop_menu, (prop_menu_name = IDP_NewString("", "name", sizeof(mt->idname)))); +static bool ui_but_event_operator_string_from_menu( + const bContext *C, uiBut *but, + char *buf, const size_t buf_len) +{ + MenuType *mt = UI_but_menutype_get(but); + BLI_assert(mt != NULL); - IDP_AssignString(prop_menu_name, mt->idname, sizeof(mt->idname)); + bool found = false; + IDProperty *prop_menu; - if (WM_key_event_operator_string( - C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, true, - buf, buf_len)) - { - found = true; - } + /* annoying, create a property */ + IDPropertyTemplate val = {0}; + prop_menu = IDP_New(IDP_GROUP, &val, __func__); /* dummy, name is unimportant */ + IDP_AddToGroup(prop_menu, IDP_NewString(mt->idname, "name", sizeof(mt->idname))); + + if (WM_key_event_operator_string( + C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, true, + buf, buf_len)) + { + found = true; + } + + IDP_FreeProperty(prop_menu); + MEM_freeN(prop_menu); + return found; +} - IDP_FreeProperty(prop_menu); - MEM_freeN(prop_menu); +static bool ui_but_event_operator_string( + const bContext *C, uiBut *but, + char *buf, const size_t buf_len) +{ + bool found = false; + + if (but->optype != NULL) { + found = ui_but_event_operator_string_from_operator(C, but, buf, buf_len); + } + else if (UI_but_menutype_get(but) != NULL) { + found = ui_but_event_operator_string_from_menu(C, but, buf, buf_len); } return found; @@ -1142,6 +1155,8 @@ static bool ui_but_event_property_operator_string( return found; } +/** \} */ + /** * This goes in a seemingly weird pattern: * @@ -2131,8 +2146,9 @@ static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double va precision = float_precision; } - bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision, - unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad); + bUnit_AsString( + str, len_max, ui_get_but_scale_unit(but, value), precision, + unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad); } static float ui_get_but_step_unit(uiBut *but, float step_default) @@ -2349,8 +2365,9 @@ static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char /* ugly, use the draw string to get the value, * this could cause problems if it includes some text which resolves to a unit */ - bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr, - ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type)); + bUnit_ReplaceString( + str_unit_convert, sizeof(str_unit_convert), but->drawstr, + ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type)); return BPY_execute_string_as_number(C, str_unit_convert, true, r_value); } @@ -3403,12 +3420,14 @@ static void ui_def_but_rna__menu(bContext *UNUSED(C), uiLayout *layout, void *bu } else { if (item->icon) { - uiDefIconTextButI(block, UI_BTYPE_BUT_MENU, B_NOP, item->icon, item->name, 0, 0, - UI_UNIT_X * 5, UI_UNIT_Y, &handle->retvalue, item->value, 0.0, 0, -1, item->description); + uiDefIconTextButI( + block, UI_BTYPE_BUT_MENU, B_NOP, item->icon, item->name, 0, 0, + UI_UNIT_X * 5, UI_UNIT_Y, &handle->retvalue, item->value, 0.0, 0, -1, item->description); } else { - uiDefButI(block, UI_BTYPE_BUT_MENU, B_NOP, item->name, 0, 0, - UI_UNIT_X * 5, UI_UNIT_X, &handle->retvalue, item->value, 0.0, 0, -1, item->description); + uiDefButI( + block, UI_BTYPE_BUT_MENU, B_NOP, item->name, 0, 0, + UI_UNIT_X * 5, UI_UNIT_X, &handle->retvalue, item->value, 0.0, 0, -1, item->description); } } } @@ -4753,4 +4772,3 @@ void UI_exit(void) ui_resources_free(); ui_but_clipboard_free(); } - diff --git a/source/blender/editors/interface/interface_context_menu.c b/source/blender/editors/interface/interface_context_menu.c new file mode 100644 index 000000000000..54e755f6cc64 --- /dev/null +++ b/source/blender/editors/interface/interface_context_menu.c @@ -0,0 +1,635 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/editors/interface/interface_context_menu.c + * \ingroup edinterface + * + * Generic context popup menus. + */ + +#include "MEM_guardedalloc.h" + +#include "DNA_scene_types.h" +#include "DNA_screen_types.h" + +#include "BLI_path_util.h" +#include "BLI_string.h" +#include "BLI_utildefines.h" + +#include "BLT_translation.h" + +#include "BKE_addon.h" +#include "BKE_context.h" +#include "BKE_idprop.h" +#include "BKE_screen.h" + +#include "ED_screen.h" +#include "ED_keyframing.h" + +#include "UI_interface.h" + +#include "interface_intern.h" + +#include "RNA_access.h" + +#include "WM_api.h" +#include "WM_types.h" + +/* This hack is needed because we don't have a good way to re-reference keymap items once added: T42944 */ +#define USE_KEYMAP_ADD_HACK + +/* -------------------------------------------------------------------- */ +/** \name Button Context Menu + * \{ */ + +static void but_shortcut_name_func(bContext *C, void *arg1, int UNUSED(event)) +{ + uiBut *but = (uiBut *)arg1; + + if (but->optype) { + char shortcut_str[128]; + + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; + + /* complex code to change name of button */ + if (WM_key_event_operator_string( + C, but->optype->idname, but->opcontext, prop, true, + shortcut_str, sizeof(shortcut_str))) + { + ui_but_add_shortcut(but, shortcut_str, true); + } + else { + /* simply strip the shortcut */ + ui_but_add_shortcut(but, NULL, true); + } + } +} + +static uiBlock *menu_change_shortcut(bContext *C, ARegion *ar, void *arg) +{ + wmWindowManager *wm = CTX_wm_manager(C); + uiBlock *block; + uiBut *but = (uiBut *)arg; + wmKeyMap *km; + wmKeyMapItem *kmi; + PointerRNA ptr; + uiLayout *layout; + uiStyle *style = UI_style_get_dpi(); + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; + + kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, true, &km); + BLI_assert(kmi != NULL); + + RNA_pointer_create(&wm->id, &RNA_KeyMapItem, kmi, &ptr); + + block = UI_block_begin(C, ar, "_popup", UI_EMBOSS); + UI_block_func_handle_set(block, but_shortcut_name_func, but); + UI_block_flag_enable(block, UI_BLOCK_MOVEMOUSE_QUIT); + UI_block_direction_set(block, UI_DIR_CENTER_Y); + + layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, 200, 20, 0, style); + + uiItemR(layout, &ptr, "type", UI_ITEM_R_FULL_EVENT | UI_ITEM_R_IMMEDIATE, "", ICON_NONE); + + UI_block_bounds_set_popup(block, 6, -50, 26); + + return block; +} + +#ifdef USE_KEYMAP_ADD_HACK +static int g_kmi_id_hack; +#endif + +static uiBlock *menu_add_shortcut(bContext *C, ARegion *ar, void *arg) +{ + wmWindowManager *wm = CTX_wm_manager(C); + uiBlock *block; + uiBut *but = (uiBut *)arg; + wmKeyMap *km; + wmKeyMapItem *kmi; + PointerRNA ptr; + uiLayout *layout; + uiStyle *style = UI_style_get_dpi(); + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; + int kmi_id; + + /* XXX this guess_opname can potentially return a different keymap than being found on adding later... */ + km = WM_keymap_guess_opname(C, but->optype->idname); + kmi = WM_keymap_add_item(km, but->optype->idname, AKEY, KM_PRESS, 0, 0); + kmi_id = kmi->id; + + /* copy properties, prop can be NULL for reset */ + if (prop) + prop = IDP_CopyProperty(prop); + WM_keymap_properties_reset(kmi, prop); + + /* update and get pointers again */ + WM_keyconfig_update(wm); + + km = WM_keymap_guess_opname(C, but->optype->idname); + kmi = WM_keymap_item_find_id(km, kmi_id); + + RNA_pointer_create(&wm->id, &RNA_KeyMapItem, kmi, &ptr); + + block = UI_block_begin(C, ar, "_popup", UI_EMBOSS); + UI_block_func_handle_set(block, but_shortcut_name_func, but); + UI_block_direction_set(block, UI_DIR_CENTER_Y); + + layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, 200, 20, 0, style); + + uiItemR(layout, &ptr, "type", UI_ITEM_R_FULL_EVENT | UI_ITEM_R_IMMEDIATE, "", ICON_NONE); + + UI_block_bounds_set_popup(block, 6, -50, 26); + +#ifdef USE_KEYMAP_ADD_HACK + g_kmi_id_hack = kmi_id; +#endif + return block; +} + +static void menu_add_shortcut_cancel(struct bContext *C, void *arg1) +{ + uiBut *but = (uiBut *)arg1; + wmKeyMap *km; + wmKeyMapItem *kmi; +#ifndef USE_KEYMAP_ADD_HACK + IDProperty *prop; +#endif + int kmi_id; + +#ifdef USE_KEYMAP_ADD_HACK + km = WM_keymap_guess_opname(C, but->optype->idname); + kmi_id = g_kmi_id_hack; + UNUSED_VARS(but); +#else + prop = (but->opptr) ? but->opptr->data : NULL; + kmi_id = WM_key_event_operator_id(C, but->optype->idname, but->opcontext, prop, true, &km); +#endif + + kmi = WM_keymap_item_find_id(km, kmi_id); + WM_keymap_remove_item(km, kmi); +} + +static void popup_change_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) +{ + uiBut *but = (uiBut *)arg1; + UI_popup_block_invoke(C, menu_change_shortcut, but); +} + +static void remove_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) +{ + uiBut *but = (uiBut *)arg1; + wmKeyMap *km; + wmKeyMapItem *kmi; + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; + + kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, true, &km); + BLI_assert(kmi != NULL); + + WM_keymap_remove_item(km, kmi); + + but_shortcut_name_func(C, but, 0); +} + +static void popup_add_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) +{ + uiBut *but = (uiBut *)arg1; + UI_popup_block_ex(C, menu_add_shortcut, NULL, menu_add_shortcut_cancel, but, NULL); +} + +static void ui_but_menu_add_path_operators(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop) +{ + const PropertySubType subtype = RNA_property_subtype(prop); + wmOperatorType *ot = WM_operatortype_find("WM_OT_path_open", true); + char filepath[FILE_MAX]; + char dir[FILE_MAXDIR]; + char file[FILE_MAXFILE]; + PointerRNA props_ptr; + + BLI_assert(ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH)); + UNUSED_VARS_NDEBUG(subtype); + + RNA_property_string_get(ptr, prop, filepath); + BLI_split_dirfile(filepath, dir, file, sizeof(dir), sizeof(file)); + + if (file[0]) { + BLI_assert(subtype == PROP_FILEPATH); + uiItemFullO_ptr( + layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open File Externally"), + ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr); + RNA_string_set(&props_ptr, "filepath", filepath); + } + + uiItemFullO_ptr( + layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open Location Externally"), + ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr); + RNA_string_set(&props_ptr, "filepath", dir); +} + +bool ui_popup_context_menu_for_button(bContext *C, uiBut *but) +{ + /* having this menu for some buttons makes no sense */ + if (but->type == UI_BTYPE_IMAGE) { + return false; + } + + uiPopupMenu *pup; + uiLayout *layout; + + { + uiStringInfo label = {BUT_GET_LABEL, NULL}; + + /* highly unlikely getting the label ever fails */ + UI_but_string_info_get(C, but, &label, NULL); + + pup = UI_popup_menu_begin(C, label.strinfo ? label.strinfo : "", ICON_NONE); + layout = UI_popup_menu_layout(pup); + if (label.strinfo) { + MEM_freeN(label.strinfo); + } + uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_DEFAULT); + } + + if (but->rnapoin.data && but->rnaprop) { + PointerRNA *ptr = &but->rnapoin; + PropertyRNA *prop = but->rnaprop; + const PropertyType type = RNA_property_type(prop); + const PropertySubType subtype = RNA_property_subtype(prop); + bool is_anim = RNA_property_animateable(ptr, prop); + bool is_editable = RNA_property_editable(ptr, prop); + /*bool is_idprop = RNA_property_is_idprop(prop);*/ /* XXX does not work as expected, not strictly needed */ + bool is_set = RNA_property_is_set(ptr, prop); + + /* second slower test, saved people finding keyframe items in menus when its not possible */ + if (is_anim) + is_anim = RNA_property_path_from_ID_check(&but->rnapoin, but->rnaprop); + + /* determine if we can key a single component of an array */ + const bool is_array = RNA_property_array_length(&but->rnapoin, but->rnaprop) != 0; + const bool is_array_component = (is_array && but->rnaindex != -1); + + /* Keyframes */ + if (but->flag & UI_BUT_ANIMATED_KEY) { + /* Set the (button_pointer, button_prop) and pointer data for Python access to the hovered ui element. */ + uiLayoutSetContextFromBut(layout, but); + + /* replace/delete keyfraemes */ + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Keyframes"), + ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Single Keyframe"), + ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Keyframes"), + ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Single Keyframe"), + ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 0); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Keyframe"), + ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Keyframe"), + ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 1); + } + + /* keyframe settings */ + uiItemS(layout); + + + } + else if (but->flag & UI_BUT_DRIVEN) { + /* pass */ + } + else if (is_anim) { + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframes"), + ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Single Keyframe"), + ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframe"), + ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); + } + } + + if ((but->flag & UI_BUT_ANIMATED) && (but->rnapoin.type != &RNA_NlaStrip)) { + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Keyframes"), + ICON_KEY_DEHLT, "ANIM_OT_keyframe_clear_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Single Keyframes"), + ICON_NONE, "ANIM_OT_keyframe_clear_button", "all", 0); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Keyframes"), + ICON_KEY_DEHLT, "ANIM_OT_keyframe_clear_button", "all", 1); + } + } + + /* Drivers */ + if (but->flag & UI_BUT_DRIVEN) { + uiItemS(layout); + + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Drivers"), + ICON_X, "ANIM_OT_driver_button_remove", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Single Driver"), + ICON_NONE, "ANIM_OT_driver_button_remove", "all", 0); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Driver"), + ICON_X, "ANIM_OT_driver_button_remove", "all", 1); + } + + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Driver"), + ICON_NONE, "ANIM_OT_copy_driver_button"); + if (ANIM_driver_can_paste()) { + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"), + ICON_NONE, "ANIM_OT_paste_driver_button"); + } + } + else if (but->flag & (UI_BUT_ANIMATED_KEY | UI_BUT_ANIMATED)) { + /* pass */ + } + else if (is_anim) { + uiItemS(layout); + + if (is_array_component) { + uiItemMenuEnumO( + layout, C, "ANIM_OT_driver_button_add", "mapping_type", + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Drivers"), + ICON_DRIVER); + } + else { + uiItemMenuEnumO( + layout, C, "ANIM_OT_driver_button_add", "mapping_type", + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Driver"), + ICON_DRIVER); + } + + if (ANIM_driver_can_paste()) { + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"), + ICON_NONE, "ANIM_OT_paste_driver_button"); + } + } + + /* Keying Sets */ + /* TODO: check on modifyability of Keying Set when doing this */ + if (is_anim) { + uiItemS(layout); + + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add All to Keying Set"), + ICON_KEYINGSET, "ANIM_OT_keyingset_button_add", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Single to Keying Set"), + ICON_NONE, "ANIM_OT_keyingset_button_add", "all", 0); + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove from Keying Set"), + ICON_NONE, "ANIM_OT_keyingset_button_remove"); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add to Keying Set"), + ICON_KEYINGSET, "ANIM_OT_keyingset_button_add", "all", 1); + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove from Keying Set"), + ICON_NONE, "ANIM_OT_keyingset_button_remove"); + } + } + + uiItemS(layout); + + /* Property Operators */ + + /* Copy Property Value + * Paste Property Value */ + + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset All to Default Values"), + ICON_LOOP_BACK, "UI_OT_reset_default_button", "all", 1); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset Single to Default Value"), + ICON_NONE, "UI_OT_reset_default_button", "all", 0); + } + else { + uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset to Default Value"), + ICON_LOOP_BACK, "UI_OT_reset_default_button", "all", 1); + } + if (is_editable /*&& is_idprop*/ && is_set) { + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Unset"), + ICON_NONE, "UI_OT_unset_property_button"); + } + + if (is_array_component) { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy All To Selected"), + ICON_NONE, "UI_OT_copy_to_selected_button", "all", true); + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Single To Selected"), + ICON_NONE, "UI_OT_copy_to_selected_button", "all", false); + } + else { + uiItemBooleanO( + layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy To Selected"), + ICON_NONE, "UI_OT_copy_to_selected_button", "all", true); + } + + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Data Path"), + ICON_NONE, "UI_OT_copy_data_path_button"); + + uiItemS(layout); + + if (type == PROP_STRING && ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH)) { + ui_but_menu_add_path_operators(layout, ptr, prop); + uiItemS(layout); + } + } + + /* Operator buttons */ + if (but->optype) { + uiBlock *block = uiLayoutGetBlock(layout); + uiBut *but2; + IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; + int w = uiLayoutGetWidth(layout); + wmKeyMap *km; + /* We want to know if this op has a shortcut, be it hotkey or not. */ + wmKeyMapItem *kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, false, &km); + + /* We do have a shortcut, but only keyboard ones are editbale that way... */ + if (kmi) { + if (ISKEYBOARD(kmi->type)) { +#if 0 /* would rather use a block but, but gets weirdly positioned... */ + uiDefBlockBut( + block, menu_change_shortcut, but, "Change Shortcut", + 0, 0, uiLayoutGetWidth(layout), UI_UNIT_Y, ""); +#endif + + but2 = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_HAND, + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Change Shortcut"), + 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); + UI_but_func_set(but2, popup_change_shortcut_func, but, NULL); + + but2 = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_NONE, + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove Shortcut"), + 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); + UI_but_func_set(but2, remove_shortcut_func, but, NULL); + } + else { + but2 = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_HAND, IFACE_("Non-Keyboard Shortcut"), + 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, + TIP_("Only keyboard shortcuts can be edited that way, " + "please use User Preferences otherwise")); + UI_but_flag_enable(but2, UI_BUT_DISABLED); + } + } + /* only show 'add' if there's a suitable key map for it to go in */ + else if (WM_keymap_guess_opname(C, but->optype->idname)) { + but2 = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_HAND, + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Shortcut"), + 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); + UI_but_func_set(but2, popup_add_shortcut_func, but, NULL); + } + + /* Set the operator pointer for python access */ + uiLayoutSetContextFromBut(layout, but); + + uiItemS(layout); + } + + /* Show header tools for header buttons. */ + if (ui_block_is_popup_any(but->block) == false) { + ARegion *ar = CTX_wm_region(C); + if (ar && (ar->regiontype == RGN_TYPE_HEADER)) { + uiItemMenuF(layout, IFACE_("Header"), ICON_NONE, ED_screens_header_tools_menu_create, NULL); + uiItemS(layout); + } + } + + { /* Docs */ + char buf[512]; + + if (UI_but_online_manual_id(but, buf, sizeof(buf))) { + PointerRNA ptr_props; + uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Manual"), + ICON_URL, "WM_OT_doc_view_manual_ui_context"); + + uiItemFullO( + layout, "WM_OT_doc_view", + CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Python Reference"), + ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr_props); + RNA_string_set(&ptr_props, "doc_id", buf); + + /* XXX inactive option, not for public! */ +#if 0 + uiItemFullO( + layout, "WM_OT_doc_edit", "Submit Description", ICON_NONE, + NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr_props); + RNA_string_set(&ptr_props, "doc_id", buf); + RNA_string_set(&ptr_props, "doc_new", RNA_property_description(but->rnaprop)); +#endif + } + } + + if (but->optype) { + uiItemO(layout, NULL, + ICON_NONE, "UI_OT_copy_python_command_button"); + } + + /* perhaps we should move this into (G.debug & G_DEBUG) - campbell */ + if (U.flag & USER_DEVELOPER_UI) { + if (ui_block_is_menu(but->block) == false) { + uiItemFullO(layout, "UI_OT_editsource", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL); + } + } + + if (BKE_addon_find(&U.addons, "ui_translate")) { + uiItemFullO(layout, "UI_OT_edittranslation_init", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL); + } + + MenuType *mt = WM_menutype_find("WM_MT_button_context", true); + if (mt) { + UI_menutype_draw(C, mt, uiLayoutColumn(layout, false)); + } + + return UI_popup_menu_end_or_cancel(C, pup); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Panel Context Menu + * \{ */ + +/** + * menu to show when right clicking on the panel header + */ +void ui_popup_context_menu_for_panel(bContext *C, ARegion *ar, Panel *pa) +{ + bScreen *sc = CTX_wm_screen(C); + const bool has_panel_category = UI_panel_category_is_visible(ar); + const bool any_item_visible = has_panel_category; + PointerRNA ptr; + uiPopupMenu *pup; + uiLayout *layout; + + if (!any_item_visible) { + return; + } + + RNA_pointer_create(&sc->id, &RNA_Panel, pa, &ptr); + + pup = UI_popup_menu_begin(C, IFACE_("Panel"), ICON_NONE); + layout = UI_popup_menu_layout(pup); + + if (has_panel_category) { + char tmpstr[80]; + BLI_snprintf(tmpstr, sizeof(tmpstr), "%s" UI_SEP_CHAR_S "%s", IFACE_("Pin"), IFACE_("Shift+Left Mouse")); + uiItemR(layout, &ptr, "use_pin", 0, tmpstr, ICON_NONE); + + /* evil, force shortcut flag */ + { + uiBlock *block = uiLayoutGetBlock(layout); + uiBut *but = block->buttons.last; + but->flag |= UI_BUT_HAS_SEP_CHAR; + } + } + UI_popup_menu_end(C, pup); +} + +/** \} */ diff --git a/source/blender/editors/interface/interface_draw.c b/source/blender/editors/interface/interface_draw.c index 17dc97107566..50cd1c544c48 100644 --- a/source/blender/editors/interface/interface_draw.c +++ b/source/blender/editors/interface/interface_draw.c @@ -81,8 +81,10 @@ int UI_draw_roundbox_corner_get(void) void UI_draw_roundbox_gl_mode(int mode, float minx, float miny, float maxx, float maxy, float rad) { - float vec[7][2] = {{0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, - {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}}; + float vec[7][2] = { + {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, + {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}, + }; int a; /* mult */ @@ -159,8 +161,9 @@ void UI_draw_roundbox_shade_x( int mode, float minx, float miny, float maxx, float maxy, float rad, float shadetop, float shadedown) { - float vec[7][2] = {{0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, - {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}}; + float vec[7][2] = { + {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, + {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}}; const float div = maxy - miny; const float idiv = 1.0f / div; float coltop[3], coldown[3], color[4]; @@ -267,8 +270,9 @@ void UI_draw_roundbox_shade_y( int mode, float minx, float miny, float maxx, float maxy, float rad, float shadeLeft, float shadeRight) { - float vec[7][2] = {{0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, - {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}}; + float vec[7][2] = { + {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, + {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}}; const float div = maxx - minx; const float idiv = 1.0f / div; float colLeft[3], colRight[3], color[4]; @@ -1526,10 +1530,11 @@ void ui_draw_but_TRACKPREVIEW(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wc if (scopes->track_preview) IMB_freeImBuf(scopes->track_preview); - ImBuf *tmpibuf = BKE_tracking_sample_pattern(scopes->frame_width, scopes->frame_height, - scopes->track_search, scopes->track, - &scopes->undist_marker, true, scopes->use_track_mask, - width, height, scopes->track_pos); + ImBuf *tmpibuf = BKE_tracking_sample_pattern( + scopes->frame_width, scopes->frame_height, + scopes->track_search, scopes->track, + &scopes->undist_marker, true, scopes->use_track_mask, + width, height, scopes->track_pos); if (tmpibuf) { if (tmpibuf->rect_float) IMB_rect_from_float(tmpibuf); @@ -1556,8 +1561,9 @@ void ui_draw_but_TRACKPREVIEW(ARegion *ar, uiBut *but, uiWidgetColors *UNUSED(wc UI_draw_roundbox_gl_mode(GL_POLYGON, rect.xmin - 1, rect.ymin, rect.xmax + 1, rect.ymax + 1, 3.0f); } - glaDrawPixelsSafe(rect.xmin, rect.ymin + 1, drawibuf->x, drawibuf->y, - drawibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, drawibuf->rect); + glaDrawPixelsSafe( + rect.xmin, rect.ymin + 1, drawibuf->x, drawibuf->y, + drawibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, drawibuf->rect); /* draw cross for pixel position */ glTranslatef(rect.xmin + scopes->track_pos[0], rect.ymin + scopes->track_pos[1], 0.f); diff --git a/source/blender/editors/interface/interface_eyedropper.c b/source/blender/editors/interface/interface_eyedropper.c index 381d9f3cc422..67486f387602 100644 --- a/source/blender/editors/interface/interface_eyedropper.c +++ b/source/blender/editors/interface/interface_eyedropper.c @@ -82,6 +82,7 @@ wmKeyMap *eyedropper_modal_keymap(wmKeyConfig *keyconf) /* assign to operators */ WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_colorband"); WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_color"); + WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_color_crypto"); WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_id"); WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_depth"); WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_driver"); @@ -180,4 +181,3 @@ uiBut *eyedropper_get_property_button_under_mouse(bContext *C, const wmEvent *ev } /** \} */ - diff --git a/source/blender/editors/interface/interface_eyedropper_color.c b/source/blender/editors/interface/interface_eyedropper_color.c index 7ba4b15a88f2..5eb4359607a4 100644 --- a/source/blender/editors/interface/interface_eyedropper_color.c +++ b/source/blender/editors/interface/interface_eyedropper_color.c @@ -36,6 +36,7 @@ #include "DNA_screen_types.h" #include "BLI_math_vector.h" +#include "BLI_string.h" #include "BKE_context.h" #include "BKE_main.h" @@ -72,6 +73,8 @@ typedef struct Eyedropper { bool accum_start; /* has mouse been pressed */ float accum_col[3]; int accum_tot; + + bool accumulate; /* Color picking for cryptomatte, without accumulation. */ } Eyedropper; static bool eyedropper_init(bContext *C, wmOperator *op) @@ -80,6 +83,7 @@ static bool eyedropper_init(bContext *C, wmOperator *op) Eyedropper *eye; op->customdata = eye = MEM_callocN(sizeof(Eyedropper), "Eyedropper"); + eye->accumulate = !STREQ(op->type->idname, "UI_OT_eyedropper_color_crypto"); UI_context_active_but_prop_get(C, &eye->ptr, &eye->prop, &eye->index); @@ -207,29 +211,30 @@ static void eyedropper_color_set(bContext *C, Eyedropper *eye, const float col[3 RNA_property_update(C, &eye->ptr, eye->prop); } -/* set sample from accumulated values */ -static void eyedropper_color_set_accum(bContext *C, Eyedropper *eye) -{ - float col[3]; - mul_v3_v3fl(col, eye->accum_col, 1.0f / (float)eye->accum_tot); - eyedropper_color_set(C, eye, col); -} - -/* single point sample & set */ static void eyedropper_color_sample(bContext *C, Eyedropper *eye, int mx, int my) { + /* Accumulate color. */ float col[3]; eyedropper_color_sample_fl(C, mx, my, col); - eyedropper_color_set(C, eye, col); -} -static void eyedropper_color_sample_accum(bContext *C, Eyedropper *eye, int mx, int my) -{ - float col[3]; - eyedropper_color_sample_fl(C, mx, my, col); - /* delay linear conversion */ - add_v3_v3(eye->accum_col, col); - eye->accum_tot++; + if (eye->accumulate) { + add_v3_v3(eye->accum_col, col); + eye->accum_tot++; + } + else { + copy_v3_v3(eye->accum_col, col); + eye->accum_tot = 1; + } + + /* Apply to property. */ + float accum_col[3]; + if (eye->accum_tot > 1) { + mul_v3_v3fl(accum_col, eye->accum_col, 1.0f / (float)eye->accum_tot); + } + else { + copy_v3_v3(accum_col, eye->accum_col); + } + eyedropper_color_set(C, eye, accum_col); } static void eyedropper_cancel(bContext *C, wmOperator *op) @@ -254,29 +259,24 @@ static int eyedropper_modal(bContext *C, wmOperator *op, const wmEvent *event) if (eye->accum_tot == 0) { eyedropper_color_sample(C, eye, event->x, event->y); } - else { - eyedropper_color_set_accum(C, eye); - } eyedropper_exit(C, op); return OPERATOR_FINISHED; case EYE_MODAL_SAMPLE_BEGIN: /* enable accum and make first sample */ eye->accum_start = true; - eyedropper_color_sample_accum(C, eye, event->x, event->y); + eyedropper_color_sample(C, eye, event->x, event->y); break; case EYE_MODAL_SAMPLE_RESET: eye->accum_tot = 0; zero_v3(eye->accum_col); - eyedropper_color_sample_accum(C, eye, event->x, event->y); - eyedropper_color_set_accum(C, eye); + eyedropper_color_sample(C, eye, event->x, event->y); break; } } - else if (event->type == MOUSEMOVE) { + else if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) { if (eye->accum_start) { /* button is pressed so keep sampling */ - eyedropper_color_sample_accum(C, eye, event->x, event->y); - eyedropper_color_set_accum(C, eye); + eyedropper_color_sample(C, eye, event->x, event->y); } } @@ -297,7 +297,7 @@ static int eyedropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED( } else { eyedropper_exit(C, op); - return OPERATOR_CANCELLED; + return OPERATOR_PASS_THROUGH; } } @@ -315,26 +315,15 @@ static int eyedropper_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } else { - return OPERATOR_CANCELLED; + return OPERATOR_PASS_THROUGH; } } -static int eyedropper_poll(bContext *C) +static bool eyedropper_poll(bContext *C) { - PointerRNA ptr; - PropertyRNA *prop; - int index_dummy; - uiBut *but; - - /* Only color buttons */ - if ((CTX_wm_window(C) != NULL) && - (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) && - (but->type == UI_BTYPE_COLOR)) - { - return 1; - } - - return 0; + /* Actual test for active button happens later, since we don't + * know which one is active until mouse over. */ + return (CTX_wm_window(C) != NULL); } void UI_OT_eyedropper_color(wmOperatorType *ot) @@ -353,6 +342,22 @@ void UI_OT_eyedropper_color(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL; +} + +void UI_OT_eyedropper_color_crypto(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Cryptomatte Eyedropper"; + ot->idname = "UI_OT_eyedropper_color_crypto"; + ot->description = "Pick a color from Cryptomatte node Pick output image"; - /* properties */ + /* api callbacks */ + ot->invoke = eyedropper_invoke; + ot->modal = eyedropper_modal; + ot->cancel = eyedropper_cancel; + ot->exec = eyedropper_exec; + ot->poll = eyedropper_poll; + + /* flags */ + ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL; } diff --git a/source/blender/editors/interface/interface_eyedropper_colorband.c b/source/blender/editors/interface/interface_eyedropper_colorband.c index b13d552dbeb9..f414d524cd8e 100644 --- a/source/blender/editors/interface/interface_eyedropper_colorband.c +++ b/source/blender/editors/interface/interface_eyedropper_colorband.c @@ -289,7 +289,7 @@ static int eyedropper_colorband_exec(bContext *C, wmOperator *op) } } -static int eyedropper_colorband_poll(bContext *C) +static bool eyedropper_colorband_poll(bContext *C) { uiBut *but = UI_context_active_but_get(C); return (but && but->type == UI_BTYPE_COLORBAND); diff --git a/source/blender/editors/interface/interface_eyedropper_datablock.c b/source/blender/editors/interface/interface_eyedropper_datablock.c index 416022a9dd06..2bb575558fca 100644 --- a/source/blender/editors/interface/interface_eyedropper_datablock.c +++ b/source/blender/editors/interface/interface_eyedropper_datablock.c @@ -305,7 +305,7 @@ static int datadropper_exec(bContext *C, wmOperator *op) } } -static int datadropper_poll(bContext *C) +static bool datadropper_poll(bContext *C) { PointerRNA ptr; PropertyRNA *prop; diff --git a/source/blender/editors/interface/interface_eyedropper_depth.c b/source/blender/editors/interface/interface_eyedropper_depth.c index 8e2ca2e2b3ab..954259140c32 100644 --- a/source/blender/editors/interface/interface_eyedropper_depth.c +++ b/source/blender/editors/interface/interface_eyedropper_depth.c @@ -332,7 +332,7 @@ static int depthdropper_exec(bContext *C, wmOperator *op) } } -static int depthdropper_poll(bContext *C) +static bool depthdropper_poll(bContext *C) { PointerRNA ptr; PropertyRNA *prop; diff --git a/source/blender/editors/interface/interface_eyedropper_driver.c b/source/blender/editors/interface/interface_eyedropper_driver.c index 1b7407c87ddc..d6569bd840ca 100644 --- a/source/blender/editors/interface/interface_eyedropper_driver.c +++ b/source/blender/editors/interface/interface_eyedropper_driver.c @@ -203,7 +203,7 @@ static int driverdropper_exec(bContext *C, wmOperator *op) } } -static int driverdropper_poll(bContext *C) +static bool driverdropper_poll(bContext *C) { if (!CTX_wm_window(C)) return 0; else return 1; diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c index 5b5b69f81531..06b6099cec79 100644 --- a/source/blender/editors/interface/interface_handlers.c +++ b/source/blender/editors/interface/interface_handlers.c @@ -27,7 +27,6 @@ * \ingroup edinterface */ - #include #include #include @@ -50,15 +49,12 @@ #include "BLI_math.h" #include "BLI_listbase.h" #include "BLI_linklist.h" -#include "BLI_path_util.h" #include "BLI_string.h" #include "BLI_string_utf8.h" #include "BLI_string_cursor_utf8.h" #include "BLI_rect.h" #include "BLI_utildefines.h" -#include "BLT_translation.h" - #include "PIL_time.h" #include "BKE_colorband.h" @@ -66,7 +62,6 @@ #include "BKE_brush.h" #include "BKE_colortools.h" #include "BKE_context.h" -#include "BKE_idprop.h" #include "BKE_report.h" #include "BKE_screen.h" #include "BKE_tracking.h" @@ -75,7 +70,6 @@ #include "ED_screen.h" #include "ED_undo.h" -#include "ED_keyframing.h" #include "UI_interface.h" @@ -91,6 +85,7 @@ #ifdef WITH_INPUT_IME # include "wm_window.h" +# include "BLT_translation.h" # include "BLT_lang.h" #endif @@ -113,9 +108,6 @@ #define UI_MAX_PASSWORD_STR 128 -/* This hack is needed because we don't have a good way to re-reference keymap items once added: T42944 */ -#define USE_KEYMAP_ADD_HACK - /* proto */ static void ui_but_smart_controller_add(bContext *C, uiBut *from, uiBut *to); static void ui_but_link_add(bContext *C, uiBut *from, uiBut *to); @@ -479,36 +471,6 @@ void ui_pan_to_scroll(const wmEvent *event, int *type, int *val) } } -bool ui_but_is_editable(const uiBut *but) -{ - return !ELEM(but->type, - UI_BTYPE_LABEL, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, - UI_BTYPE_ROUNDBOX, UI_BTYPE_LISTBOX, UI_BTYPE_PROGRESS_BAR); -} - -bool ui_but_is_editable_as_text(const uiBut *but) -{ - return ELEM(but->type, - UI_BTYPE_TEXT, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER, - UI_BTYPE_SEARCH_MENU); - -} - -bool ui_but_is_toggle(const uiBut *but) -{ - return ELEM( - but->type, - UI_BTYPE_BUT_TOGGLE, - UI_BTYPE_TOGGLE, - UI_BTYPE_ICON_TOGGLE, - UI_BTYPE_ICON_TOGGLE_N, - UI_BTYPE_TOGGLE_N, - UI_BTYPE_CHECKBOX, - UI_BTYPE_CHECKBOX_N, - UI_BTYPE_ROW - ); -} - static uiBut *ui_but_prev(uiBut *but) { while (but->prev) { @@ -1352,8 +1314,10 @@ static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const if (but) { if (but->flag & UI_BUT_DRAG_LOCK) { - const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect), - BLI_rctf_cent_y(&but->rect)}; + const float but_cent_new[2] = { + BLI_rctf_cent_x(&but->rect), + BLI_rctf_cent_y(&but->rect), + }; /* check if this is a different button, chances are high the button wont move about :) */ if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) { @@ -1425,10 +1389,11 @@ static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void ui_apply_but_undo(but); } - WM_event_remove_ui_handler(&win->modalhandlers, - ui_handler_region_drag_toggle, - ui_handler_region_drag_toggle_remove, - drag_info, false); + WM_event_remove_ui_handler( + &win->modalhandlers, + ui_handler_region_drag_toggle, + ui_handler_region_drag_toggle_remove, + drag_info, false); ui_handler_region_drag_toggle_remove(C, drag_info); WM_event_add_mousemove(C); @@ -1643,7 +1608,7 @@ static void ui_selectcontext_apply( wmWindow *win = CTX_wm_window(C); if (!win->eventstate->shift) { const int len = RNA_property_array_length(&but->rnapoin, prop); - int *tmparray = MEM_callocN(sizeof(int) * len, __func__); + bool *tmparray = MEM_callocN(sizeof(bool) * len, __func__); tmparray[index] = true; @@ -3402,13 +3367,15 @@ static void ui_do_but_textedit( } break; case RIGHTARROWKEY: - ui_textedit_move(but, data, STRCUR_DIR_NEXT, - event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); + ui_textedit_move( + but, data, STRCUR_DIR_NEXT, + event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); retval = WM_UI_HANDLER_BREAK; break; case LEFTARROWKEY: - ui_textedit_move(but, data, STRCUR_DIR_PREV, - event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); + ui_textedit_move( + but, data, STRCUR_DIR_PREV, + event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); retval = WM_UI_HANDLER_BREAK; break; case WHEELDOWNMOUSE: @@ -3425,8 +3392,9 @@ static void ui_do_but_textedit( } ATTR_FALLTHROUGH; case ENDKEY: - ui_textedit_move(but, data, STRCUR_DIR_NEXT, - event->shift != 0, STRCUR_JUMP_ALL); + ui_textedit_move( + but, data, STRCUR_DIR_NEXT, + event->shift != 0, STRCUR_JUMP_ALL); retval = WM_UI_HANDLER_BREAK; break; case WHEELUPMOUSE: @@ -3443,8 +3411,9 @@ static void ui_do_but_textedit( } ATTR_FALLTHROUGH; case HOMEKEY: - ui_textedit_move(but, data, STRCUR_DIR_PREV, - event->shift != 0, STRCUR_JUMP_ALL); + ui_textedit_move( + but, data, STRCUR_DIR_PREV, + event->shift != 0, STRCUR_JUMP_ALL); retval = WM_UI_HANDLER_BREAK; break; case PADENTER: @@ -3453,14 +3422,16 @@ static void ui_do_but_textedit( retval = WM_UI_HANDLER_BREAK; break; case DELKEY: - changed = ui_textedit_delete(but, data, 1, - event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); + changed = ui_textedit_delete( + but, data, 1, + event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); retval = WM_UI_HANDLER_BREAK; break; case BACKSPACEKEY: - changed = ui_textedit_delete(but, data, 0, - event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); + changed = ui_textedit_delete( + but, data, 0, + event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE); retval = WM_UI_HANDLER_BREAK; break; @@ -3475,10 +3446,12 @@ static void ui_do_but_textedit( if (event->ctrl && !IS_EVENT_MOD(event, shift, alt, oskey)) #endif { - ui_textedit_move(but, data, STRCUR_DIR_PREV, - false, STRCUR_JUMP_ALL); - ui_textedit_move(but, data, STRCUR_DIR_NEXT, - true, STRCUR_JUMP_ALL); + ui_textedit_move( + but, data, STRCUR_DIR_PREV, + false, STRCUR_JUMP_ALL); + ui_textedit_move( + but, data, STRCUR_DIR_NEXT, + true, STRCUR_JUMP_ALL); retval = WM_UI_HANDLER_BREAK; } break; @@ -5240,12 +5213,12 @@ static int ui_do_but_COLOR( rgb_to_hsv_compat_v(col, hsv); if (event->type == WHEELDOWNMOUSE) - hsv[2] = CLAMPIS(hsv[2] - 0.05f, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] - 0.05f, 0.0f, 1.0f); else if (event->type == WHEELUPMOUSE) - hsv[2] = CLAMPIS(hsv[2] + 0.05f, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] + 0.05f, 0.0f, 1.0f); else { float fac = 0.005 * (event->y - event->prevy); - hsv[2] = CLAMPIS(hsv[2] + fac, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] + fac, 0.0f, 1.0f); } hsv_to_rgb_v(hsv, data->vec); @@ -5963,12 +5936,12 @@ static int ui_do_but_HSVCIRCLE( } /* XXX hardcoded keymap check.... */ else if (event->type == WHEELDOWNMOUSE) { - hsv[2] = CLAMPIS(hsv[2] - 0.05f, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] - 0.05f, 0.0f, 1.0f); ui_but_hsv_set(but); /* converts to rgb */ ui_numedit_apply(C, block, but, data); } else if (event->type == WHEELUPMOUSE) { - hsv[2] = CLAMPIS(hsv[2] + 0.05f, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] + 0.05f, 0.0f, 1.0f); ui_but_hsv_set(but); /* converts to rgb */ ui_numedit_apply(C, block, but, data); } @@ -6616,542 +6589,6 @@ static int ui_do_but_TRACKPREVIEW( return WM_UI_HANDLER_CONTINUE; } -static void but_shortcut_name_func(bContext *C, void *arg1, int UNUSED(event)) -{ - uiBut *but = (uiBut *)arg1; - - if (but->optype) { - char shortcut_str[128]; - - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - - /* complex code to change name of button */ - if (WM_key_event_operator_string( - C, but->optype->idname, but->opcontext, prop, true, - shortcut_str, sizeof(shortcut_str))) - { - ui_but_add_shortcut(but, shortcut_str, true); - } - else { - /* simply strip the shortcut */ - ui_but_add_shortcut(but, NULL, true); - } - } -} - -static uiBlock *menu_change_shortcut(bContext *C, ARegion *ar, void *arg) -{ - wmWindowManager *wm = CTX_wm_manager(C); - uiBlock *block; - uiBut *but = (uiBut *)arg; - wmKeyMap *km; - wmKeyMapItem *kmi; - PointerRNA ptr; - uiLayout *layout; - uiStyle *style = UI_style_get_dpi(); - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - - kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, true, &km); - BLI_assert(kmi != NULL); - - RNA_pointer_create(&wm->id, &RNA_KeyMapItem, kmi, &ptr); - - block = UI_block_begin(C, ar, "_popup", UI_EMBOSS); - UI_block_func_handle_set(block, but_shortcut_name_func, but); - UI_block_flag_enable(block, UI_BLOCK_MOVEMOUSE_QUIT); - UI_block_direction_set(block, UI_DIR_CENTER_Y); - - layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, 200, 20, 0, style); - - uiItemR(layout, &ptr, "type", UI_ITEM_R_FULL_EVENT | UI_ITEM_R_IMMEDIATE, "", ICON_NONE); - - UI_block_bounds_set_popup(block, 6, -50, 26); - - return block; -} - -#ifdef USE_KEYMAP_ADD_HACK -static int g_kmi_id_hack; -#endif - -static uiBlock *menu_add_shortcut(bContext *C, ARegion *ar, void *arg) -{ - wmWindowManager *wm = CTX_wm_manager(C); - uiBlock *block; - uiBut *but = (uiBut *)arg; - wmKeyMap *km; - wmKeyMapItem *kmi; - PointerRNA ptr; - uiLayout *layout; - uiStyle *style = UI_style_get_dpi(); - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - int kmi_id; - - /* XXX this guess_opname can potentially return a different keymap than being found on adding later... */ - km = WM_keymap_guess_opname(C, but->optype->idname); - kmi = WM_keymap_add_item(km, but->optype->idname, AKEY, KM_PRESS, 0, 0); - kmi_id = kmi->id; - - /* copy properties, prop can be NULL for reset */ - if (prop) - prop = IDP_CopyProperty(prop); - WM_keymap_properties_reset(kmi, prop); - - /* update and get pointers again */ - WM_keyconfig_update(wm); - - km = WM_keymap_guess_opname(C, but->optype->idname); - kmi = WM_keymap_item_find_id(km, kmi_id); - - RNA_pointer_create(&wm->id, &RNA_KeyMapItem, kmi, &ptr); - - block = UI_block_begin(C, ar, "_popup", UI_EMBOSS); - UI_block_func_handle_set(block, but_shortcut_name_func, but); - UI_block_direction_set(block, UI_DIR_CENTER_Y); - - layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, 200, 20, 0, style); - - uiItemR(layout, &ptr, "type", UI_ITEM_R_FULL_EVENT | UI_ITEM_R_IMMEDIATE, "", ICON_NONE); - - UI_block_bounds_set_popup(block, 6, -50, 26); - -#ifdef USE_KEYMAP_ADD_HACK - g_kmi_id_hack = kmi_id; -#endif - return block; -} - -static void menu_add_shortcut_cancel(struct bContext *C, void *arg1) -{ - uiBut *but = (uiBut *)arg1; - wmKeyMap *km; - wmKeyMapItem *kmi; -#ifndef USE_KEYMAP_ADD_HACK - IDProperty *prop; -#endif - int kmi_id; - -#ifdef USE_KEYMAP_ADD_HACK - km = WM_keymap_guess_opname(C, but->optype->idname); - kmi_id = g_kmi_id_hack; - UNUSED_VARS(but); -#else - prop = (but->opptr) ? but->opptr->data : NULL; - kmi_id = WM_key_event_operator_id(C, but->optype->idname, but->opcontext, prop, true, &km); -#endif - - kmi = WM_keymap_item_find_id(km, kmi_id); - WM_keymap_remove_item(km, kmi); -} - -static void popup_change_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) -{ - uiBut *but = (uiBut *)arg1; - UI_popup_block_invoke(C, menu_change_shortcut, but); -} - -static void remove_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) -{ - uiBut *but = (uiBut *)arg1; - wmKeyMap *km; - wmKeyMapItem *kmi; - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - - kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, true, &km); - BLI_assert(kmi != NULL); - - WM_keymap_remove_item(km, kmi); - - but_shortcut_name_func(C, but, 0); -} - -static void popup_add_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2)) -{ - uiBut *but = (uiBut *)arg1; - UI_popup_block_ex(C, menu_add_shortcut, NULL, menu_add_shortcut_cancel, but, NULL); -} - -/** - * menu to chow when right clicking on the panel header - */ -void ui_panel_menu(bContext *C, ARegion *ar, Panel *pa) -{ - bScreen *sc = CTX_wm_screen(C); - const bool has_panel_category = UI_panel_category_is_visible(ar); - const bool any_item_visible = has_panel_category; - PointerRNA ptr; - uiPopupMenu *pup; - uiLayout *layout; - - if (!any_item_visible) { - return; - } - - RNA_pointer_create(&sc->id, &RNA_Panel, pa, &ptr); - - pup = UI_popup_menu_begin(C, IFACE_("Panel"), ICON_NONE); - layout = UI_popup_menu_layout(pup); - - if (has_panel_category) { - char tmpstr[80]; - BLI_snprintf(tmpstr, sizeof(tmpstr), "%s" UI_SEP_CHAR_S "%s", IFACE_("Pin"), IFACE_("Shift+Left Mouse")); - uiItemR(layout, &ptr, "use_pin", 0, tmpstr, ICON_NONE); - - /* evil, force shortcut flag */ - { - uiBlock *block = uiLayoutGetBlock(layout); - uiBut *but = block->buttons.last; - but->flag |= UI_BUT_HAS_SEP_CHAR; - } - } - UI_popup_menu_end(C, pup); -} - -static void ui_but_menu_add_path_operators(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop) -{ - const PropertySubType subtype = RNA_property_subtype(prop); - wmOperatorType *ot = WM_operatortype_find("WM_OT_path_open", true); - char filepath[FILE_MAX]; - char dir[FILE_MAXDIR]; - char file[FILE_MAXFILE]; - PointerRNA props_ptr; - - BLI_assert(ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH)); - UNUSED_VARS_NDEBUG(subtype); - - RNA_property_string_get(ptr, prop, filepath); - BLI_split_dirfile(filepath, dir, file, sizeof(dir), sizeof(file)); - - if (file[0]) { - BLI_assert(subtype == PROP_FILEPATH); - uiItemFullO_ptr( - layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open File Externally"), - ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr); - RNA_string_set(&props_ptr, "filepath", filepath); - } - - uiItemFullO_ptr( - layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open Location Externally"), - ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr); - RNA_string_set(&props_ptr, "filepath", dir); -} - -static bool ui_but_menu(bContext *C, uiBut *but) -{ - uiPopupMenu *pup; - uiLayout *layout; - MenuType *mt = WM_menutype_find("WM_MT_button_context", true); - bool is_array, is_array_component; - uiStringInfo label = {BUT_GET_LABEL, NULL}; - -/* if ((but->rnapoin.data && but->rnaprop) == 0 && but->optype == NULL)*/ -/* return 0;*/ - - /* having this menu for some buttons makes no sense */ - if (but->type == UI_BTYPE_IMAGE) { - return false; - } - - /* highly unlikely getting the label ever fails */ - UI_but_string_info_get(C, but, &label, NULL); - - pup = UI_popup_menu_begin(C, label.strinfo ? label.strinfo : "", ICON_NONE); - layout = UI_popup_menu_layout(pup); - if (label.strinfo) - MEM_freeN(label.strinfo); - - uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_DEFAULT); - - if (but->rnapoin.data && but->rnaprop) { - PointerRNA *ptr = &but->rnapoin; - PropertyRNA *prop = but->rnaprop; - const PropertyType type = RNA_property_type(prop); - const PropertySubType subtype = RNA_property_subtype(prop); - bool is_anim = RNA_property_animateable(ptr, prop); - bool is_editable = RNA_property_editable(ptr, prop); - /*bool is_idprop = RNA_property_is_idprop(prop);*/ /* XXX does not work as expected, not strictly needed */ - bool is_set = RNA_property_is_set(ptr, prop); - - /* Set the (button_pointer, button_prop) and pointer data for Python access to the hovered ui element. */ - uiLayoutSetContextFromBut(layout, but); - - /* second slower test, saved people finding keyframe items in menus when its not possible */ - if (is_anim) - is_anim = RNA_property_path_from_ID_check(&but->rnapoin, but->rnaprop); - - /* determine if we can key a single component of an array */ - is_array = RNA_property_array_length(&but->rnapoin, but->rnaprop) != 0; - is_array_component = (is_array && but->rnaindex != -1); - - /* Keyframes */ - if (but->flag & UI_BUT_ANIMATED_KEY) { - /* replace/delete keyfraemes */ - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Keyframes"), - ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Single Keyframe"), - ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Keyframes"), - ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Single Keyframe"), - ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 0); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Replace Keyframe"), - ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Keyframe"), - ICON_NONE, "ANIM_OT_keyframe_delete_button", "all", 1); - } - - /* keyframe settings */ - uiItemS(layout); - - - } - else if (but->flag & UI_BUT_DRIVEN) { - /* pass */ - } - else if (is_anim) { - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframes"), - ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Single Keyframe"), - ICON_NONE, "ANIM_OT_keyframe_insert_button", "all", 0); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Insert Keyframe"), - ICON_KEY_HLT, "ANIM_OT_keyframe_insert_button", "all", 1); - } - } - - if ((but->flag & UI_BUT_ANIMATED) && (but->rnapoin.type != &RNA_NlaStrip)) { - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Keyframes"), - ICON_KEY_DEHLT, "ANIM_OT_keyframe_clear_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Single Keyframes"), - ICON_NONE, "ANIM_OT_keyframe_clear_button", "all", 0); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Clear Keyframes"), - ICON_KEY_DEHLT, "ANIM_OT_keyframe_clear_button", "all", 1); - } - } - - /* Drivers */ - if (but->flag & UI_BUT_DRIVEN) { - uiItemS(layout); - - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Drivers"), - ICON_X, "ANIM_OT_driver_button_remove", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Single Driver"), - ICON_NONE, "ANIM_OT_driver_button_remove", "all", 0); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Delete Driver"), - ICON_X, "ANIM_OT_driver_button_remove", "all", 1); - } - - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Driver"), - ICON_NONE, "ANIM_OT_copy_driver_button"); - if (ANIM_driver_can_paste()) { - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"), - ICON_NONE, "ANIM_OT_paste_driver_button"); - } - } - else if (but->flag & (UI_BUT_ANIMATED_KEY | UI_BUT_ANIMATED)) { - /* pass */ - } - else if (is_anim) { - uiItemS(layout); - - if (is_array_component) { - uiItemMenuEnumO(layout, C, "ANIM_OT_driver_button_add", "mapping_type", - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Drivers"), - ICON_DRIVER); - } - else { - uiItemMenuEnumO(layout, C, "ANIM_OT_driver_button_add", "mapping_type", - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Driver"), - ICON_DRIVER); - } - - if (ANIM_driver_can_paste()) { - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Paste Driver"), - ICON_NONE, "ANIM_OT_paste_driver_button"); - } - } - - /* Keying Sets */ - /* TODO: check on modifyability of Keying Set when doing this */ - if (is_anim) { - uiItemS(layout); - - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add All to Keying Set"), - ICON_KEYINGSET, "ANIM_OT_keyingset_button_add", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Single to Keying Set"), - ICON_NONE, "ANIM_OT_keyingset_button_add", "all", 0); - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove from Keying Set"), - ICON_NONE, "ANIM_OT_keyingset_button_remove"); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add to Keying Set"), - ICON_KEYINGSET, "ANIM_OT_keyingset_button_add", "all", 1); - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove from Keying Set"), - ICON_NONE, "ANIM_OT_keyingset_button_remove"); - } - } - - uiItemS(layout); - - /* Property Operators */ - - /* Copy Property Value - * Paste Property Value */ - - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset All to Default Values"), - ICON_LOOP_BACK, "UI_OT_reset_default_button", "all", 1); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset Single to Default Value"), - ICON_NONE, "UI_OT_reset_default_button", "all", 0); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Reset to Default Value"), - ICON_LOOP_BACK, "UI_OT_reset_default_button", "all", 1); - } - if (is_editable /*&& is_idprop*/ && is_set) { - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Unset"), - ICON_NONE, "UI_OT_unset_property_button"); - } - - if (is_array_component) { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy All To Selected"), - ICON_NONE, "UI_OT_copy_to_selected_button", "all", true); - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Single To Selected"), - ICON_NONE, "UI_OT_copy_to_selected_button", "all", false); - } - else { - uiItemBooleanO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy To Selected"), - ICON_NONE, "UI_OT_copy_to_selected_button", "all", true); - } - - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy Data Path"), - ICON_NONE, "UI_OT_copy_data_path_button"); - - uiItemS(layout); - - if (type == PROP_STRING && ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH)) { - ui_but_menu_add_path_operators(layout, ptr, prop); - uiItemS(layout); - } - } - - /* Operator buttons */ - if (but->optype) { - uiBlock *block = uiLayoutGetBlock(layout); - uiBut *but2; - IDProperty *prop = (but->opptr) ? but->opptr->data : NULL; - int w = uiLayoutGetWidth(layout); - wmKeyMap *km; - /* We want to know if this op has a shortcut, be it hotkey or not. */ - wmKeyMapItem *kmi = WM_key_event_operator(C, but->optype->idname, but->opcontext, prop, false, &km); - - /* We do have a shortcut, but only keyboard ones are editbale that way... */ - if (kmi) { - if (ISKEYBOARD(kmi->type)) { -#if 0 /* would rather use a block but, but gets weirdly positioned... */ - uiDefBlockBut(block, menu_change_shortcut, but, "Change Shortcut", - 0, 0, uiLayoutGetWidth(layout), UI_UNIT_Y, ""); -#endif - - but2 = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_HAND, - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Change Shortcut"), - 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - UI_but_func_set(but2, popup_change_shortcut_func, but, NULL); - - but2 = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_NONE, - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Remove Shortcut"), - 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - UI_but_func_set(but2, remove_shortcut_func, but, NULL); - } - else { - but2 = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_HAND, IFACE_("Non-Keyboard Shortcut"), - 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, - TIP_("Only keyboard shortcuts can be edited that way, " - "please use User Preferences otherwise")); - UI_but_flag_enable(but2, UI_BUT_DISABLED); - } - } - /* only show 'add' if there's a suitable key map for it to go in */ - else if (WM_keymap_guess_opname(C, but->optype->idname)) { - but2 = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_HAND, - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Add Shortcut"), - 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - UI_but_func_set(but2, popup_add_shortcut_func, but, NULL); - } - - /* Set the operator pointer for python access */ - uiLayoutSetContextFromBut(layout, but); - - uiItemS(layout); - } - - /* Show header tools for header buttons. */ - if (ui_block_is_menu(but->block) == false) { - ARegion *ar = CTX_wm_region(C); - if (ar && (ar->regiontype == RGN_TYPE_HEADER)) { - uiItemMenuF(layout, IFACE_("Header"), ICON_NONE, ED_screens_header_tools_menu_create, NULL); - uiItemS(layout); - } - } - - { /* Docs */ - char buf[512]; - - if (UI_but_online_manual_id(but, buf, sizeof(buf))) { - PointerRNA ptr_props; - uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Manual"), - ICON_URL, "WM_OT_doc_view_manual_ui_context"); - - uiItemFullO( - layout, "WM_OT_doc_view", - CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Python Reference"), - ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr_props); - RNA_string_set(&ptr_props, "doc_id", buf); - - /* XXX inactive option, not for public! */ -#if 0 - uiItemFullO( - layout, "WM_OT_doc_edit", "Submit Description", ICON_NONE, - NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr_props); - RNA_string_set(&ptr_props, "doc_id", buf); - RNA_string_set(&ptr_props, "doc_new", RNA_property_description(but->rnaprop)); -#endif - } - } - - if (but->optype) { - uiItemO(layout, NULL, - ICON_NONE, "UI_OT_copy_python_command_button"); - } - - /* perhaps we should move this into (G.debug & G_DEBUG) - campbell */ - if (ui_block_is_menu(but->block) == false) { - uiItemFullO(layout, "UI_OT_editsource", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL); - } - uiItemFullO(layout, "UI_OT_edittranslation_init", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL); - - mt = WM_menutype_find("WM_MT_button_context", true); - if (mt) { - UI_menutype_draw(C, mt, uiLayoutColumn(layout, false)); - } - - UI_popup_menu_end(C, pup); - - return true; -} - static int ui_do_button(bContext *C, uiBlock *block, uiBut *but, const wmEvent *event) { uiHandleButtonData *data; @@ -7195,7 +6632,7 @@ static int ui_do_button(bContext *C, uiBlock *block, uiBut *but, const wmEvent * (event->val == KM_PRESS)) { /* RMB has two options now */ - if (ui_but_menu(C, but)) { + if (ui_popup_context_menu_for_button(C, but)) { return WM_UI_HANDLER_BREAK; } } @@ -7790,10 +7227,7 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s /* highlight has timers for tooltips and auto open */ if (state == BUTTON_STATE_HIGHLIGHT) { - /* for list-items (that are not drawn with regular emboss), don't change selection based on hovering */ - if (((but->flag & UI_BUT_LIST_ITEM) == 0) && (but->dragflag & UI_EMBOSS_NONE)) { - but->flag &= ~UI_SELECT; - } + but->flag &= ~UI_SELECT; button_tooltip_timer_reset(C, but); @@ -9627,6 +9061,11 @@ static int ui_handle_menu_event( retval = ui_handle_menu_button(C, event, menu); } + /* Don't handle double click events, rehandle as regular press/release. */ + if (retval == WM_UI_HANDLER_CONTINUE && event->val == KM_DBL_CLICK) { + return retval; + } + /* if we set a menu return value, ensure we continue passing this on to * lower menus and buttons, so always set continue then, and if we are * inside the region otherwise, ensure we swallow the event */ @@ -10207,6 +9646,7 @@ static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *UNUSE { ARegion *ar; uiBut *but; + int retval = WM_UI_HANDLER_CONTINUE; ar = CTX_wm_menu(C); if (!ar) @@ -10250,29 +9690,32 @@ static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *UNUSE if ((but_other->flag & UI_BUT_DISABLED) == 0) { ui_handle_button_activate(C, ar, but_other, BUTTON_ACTIVATE_OVER); button_activate_state(C, but_other, BUTTON_STATE_MENU_OPEN); + retval = WM_UI_HANDLER_BREAK; } } else if (data->state == BUTTON_STATE_MENU_OPEN) { - int retval; - /* handle events for menus and their buttons recursively, * this will handle events from the top to the bottom menu */ - if (data->menu) + if (data->menu) { retval = ui_handle_menus_recursive(C, event, data->menu, 0, false, false, false); + } /* handle events for the activated button */ if ((data->menu && (retval == WM_UI_HANDLER_CONTINUE)) || (event->type == TIMER)) { - if (data->menu && data->menu->menuretval) + if (data->menu && data->menu->menuretval) { ui_handle_button_return_submenu(C, event, but); - else - ui_handle_button_event(C, event, but); + retval = WM_UI_HANDLER_BREAK; + } + else { + retval = ui_handle_button_event(C, event, but); + } } } else { /* handle events for the activated button */ - ui_handle_button_event(C, event, but); + retval = ui_handle_button_event(C, event, but); } } @@ -10283,6 +9726,14 @@ static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *UNUSE /* delayed apply callbacks */ ui_apply_but_funcs_after(C); + /* Don't handle double-click events, + * these will be converted into regular clicks which we handle. */ + if (retval == WM_UI_HANDLER_CONTINUE) { + if (event->val == KM_DBL_CLICK) { + return WM_UI_HANDLER_CONTINUE; + } + } + /* we block all events, this is modal interaction */ return WM_UI_HANDLER_BREAK; } @@ -10333,8 +9784,9 @@ static int ui_popup_handler(bContext *C, const wmEvent *event, void *userdata) #ifdef USE_DRAG_TOGGLE { - WM_event_free_ui_handler_all(C, &win->modalhandlers, - ui_handler_region_drag_toggle, ui_handler_region_drag_toggle_remove); + WM_event_free_ui_handler_all( + C, &win->modalhandlers, + ui_handler_region_drag_toggle, ui_handler_region_drag_toggle_remove); } #endif diff --git a/source/blender/editors/interface/interface_icons.c b/source/blender/editors/interface/interface_icons.c index 0315bf736f0d..eed7f2ec0f20 100644 --- a/source/blender/editors/interface/interface_icons.c +++ b/source/blender/editors/interface/interface_icons.c @@ -612,7 +612,7 @@ static void init_iconfile_list(struct ListBase *list) if ((dir[i].type & S_IFREG)) { const char *filename = dir[i].relname; - if (BLI_testextensie(filename, ".png")) { + if (BLI_path_extension_check(filename, ".png")) { /* loading all icons on file start is overkill & slows startup * its possible they change size after blender load anyway. */ #if 0 @@ -1407,4 +1407,3 @@ void UI_icon_draw_preview_aspect_size(float x, float y, int icon_id, float aspec { icon_draw_size(x, y, icon_id, aspect, alpha, NULL, ICON_SIZE_PREVIEW, size, false, true); } - diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h index cd39c0d38a93..75f2efdf3aa8 100644 --- a/source/blender/editors/interface/interface_intern.h +++ b/source/blender/editors/interface/interface_intern.h @@ -453,8 +453,6 @@ extern void ui_linkline_remove(uiLinkLine *line, uiBut *but); void ui_fontscale(short *points, float aspect); -extern bool ui_block_is_menu(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; -extern bool ui_block_is_pie_menu(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; extern void ui_block_to_window_fl(const struct ARegion *ar, uiBlock *block, float *x, float *y); extern void ui_block_to_window(const struct ARegion *ar, uiBlock *block, int *x, int *y); extern void ui_block_to_window_rctf(const struct ARegion *ar, uiBlock *block, rctf *rct_dst, const rctf *rct_src); @@ -677,16 +675,12 @@ extern void ui_but_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut extern uiBut *ui_but_find_select_in_enum(uiBut *but, int direction); extern uiBut *ui_but_find_active_in_region(struct ARegion *ar); extern uiBut *ui_but_find_mouse_over(struct ARegion *ar, const struct wmEvent *event); -bool ui_but_is_editable(const uiBut *but); -bool ui_but_is_editable_as_text(const uiBut *but); -bool ui_but_is_toggle(const uiBut *but); void ui_but_pie_dir_visual(RadialDirection dir, float vec[2]); void ui_but_pie_dir(RadialDirection dir, float vec[2]); float ui_block_calc_pie_segment(struct uiBlock *block, const float event_xy[2]); void ui_but_add_shortcut(uiBut *but, const char *key_str, const bool do_strip); void ui_but_clipboard_free(void); -void ui_panel_menu(struct bContext *C, ARegion *ar, Panel *pa); uiBut *ui_but_find_old(uiBlock *block_old, const uiBut *but_new); uiBut *ui_but_find_new(uiBlock *block_old, const uiBut *but_new); @@ -700,8 +694,8 @@ void ui_draw_anti_tria(float x1, float y1, float x2, float y2, float x3, float y void ui_draw_anti_roundbox(int mode, float minx, float miny, float maxx, float maxy, float rad, bool use_alpha); void ui_draw_menu_back(struct uiStyle *style, uiBlock *block, rcti *rect); void ui_draw_pie_center(uiBlock *block); -uiWidgetColors *ui_tooltip_get_theme(void); -void ui_draw_tooltip_background(uiStyle *UNUSED(style), uiBlock *block, rcti *rect); +struct uiWidgetColors *ui_tooltip_get_theme(void); +void ui_draw_tooltip_background(struct uiStyle *UNUSED(style), uiBlock *block, rcti *rect); void ui_draw_search_back(struct uiStyle *style, uiBlock *block, rcti *rect); bool ui_link_bezier_points(const rcti *rect, float coord_array[][2], int resol); void ui_draw_link_bezier(const rcti *rect); @@ -751,12 +745,26 @@ bool ui_but_anim_expression_set(uiBut *but, const char *str); bool ui_but_anim_expression_create(uiBut *but, const char *str); void ui_but_anim_autokey(struct bContext *C, uiBut *but, struct Scene *scene, float cfra); +/* interface_query.c */ +bool ui_but_is_editable(const uiBut *but); +bool ui_but_is_editable_as_text(const uiBut *but); +bool ui_but_is_toggle(const uiBut *but); + +extern bool ui_block_is_menu(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; +extern bool ui_block_is_pie_menu(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; +extern bool ui_block_is_popup_any(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; + +/* interface_context_menu.c */ +bool ui_popup_context_menu_for_button(struct bContext *C, uiBut *but); +void ui_popup_context_menu_for_panel(struct bContext *C, struct ARegion *ar, struct Panel *pa); + /* interface_eyedropper.c */ struct wmKeyMap *eyedropper_modal_keymap(struct wmKeyConfig *keyconf); struct wmKeyMap *eyedropper_colorband_modal_keymap(struct wmKeyConfig *keyconf); /* interface_eyedropper_color.c */ void UI_OT_eyedropper_color(struct wmOperatorType *ot); +void UI_OT_eyedropper_color_crypto(struct wmOperatorType *ot); /* interface_eyedropper_colorband.c */ void UI_OT_eyedropper_colorband(struct wmOperatorType *ot); diff --git a/source/blender/editors/interface/interface_layout.c b/source/blender/editors/interface/interface_layout.c index c9145b7d2474..edd568e4feae 100644 --- a/source/blender/editors/interface/interface_layout.c +++ b/source/blender/editors/interface/interface_layout.c @@ -351,7 +351,7 @@ static int ui_layout_local_dir(uiLayout *layout) } } -static uiLayout *ui_item_local_sublayout(uiLayout *test, uiLayout *layout, int align) +static uiLayout *ui_item_local_sublayout(uiLayout *test, uiLayout *layout, bool align) { uiLayout *sub; @@ -521,7 +521,7 @@ static void ui_item_array( uiDefAutoButR(block, ptr, prop, -1, "", ICON_NONE, 0, 0, w, UI_UNIT_Y); } else { - int *boolarr = NULL; + bool *boolarr = NULL; /* even if 'expand' is fale, expanding anyway */ @@ -536,7 +536,7 @@ static void ui_item_array( /* show checkboxes for rna on a non-emboss block (menu for eg) */ if (type == PROP_BOOLEAN && ELEM(layout->root->block->dt, UI_EMBOSS_NONE, UI_EMBOSS_PULLDOWN)) { - boolarr = MEM_callocN(sizeof(int) * len, __func__); + boolarr = MEM_callocN(sizeof(bool) * len, __func__); RNA_property_boolean_get_array(ptr, prop, boolarr); } @@ -678,7 +678,8 @@ static uiBut *ui_item_with_label(uiLayout *layout, uiBlock *block, const char *n PropertySubType subtype; int labelw; - sub = uiLayoutRow(layout, layout->align); + /* Always align item with label since text is already given enough space not to overlap. */ + sub = uiLayoutRow(layout, true); UI_block_layout_set_current(block, sub); if (name[0]) { @@ -700,8 +701,9 @@ static uiBut *ui_item_with_label(uiLayout *layout, uiBlock *block, const char *n but = uiDefAutoButR(block, ptr, prop, index, "", icon, x, y, w - UI_UNIT_X, h); /* BUTTONS_OT_file_browse calls UI_context_active_but_prop_get_filebrowser */ - uiDefIconButO(block, UI_BTYPE_BUT, subtype == PROP_DIRPATH ? "BUTTONS_OT_directory_browse" : "BUTTONS_OT_file_browse", - WM_OP_INVOKE_DEFAULT, ICON_FILESEL, x, y, UI_UNIT_X, h, NULL); + uiDefIconButO( + block, UI_BTYPE_BUT, subtype == PROP_DIRPATH ? "BUTTONS_OT_directory_browse" : "BUTTONS_OT_file_browse", + WM_OP_INVOKE_DEFAULT, ICON_FILESEL, x, y, UI_UNIT_X, h, NULL); } else if (flag & UI_ITEM_R_EVENT) { but = uiDefButR_prop(block, UI_BTYPE_KEY_EVENT, 0, name, x, y, w, h, ptr, prop, index, 0, 0, -1, -1, NULL); @@ -1085,8 +1087,9 @@ void uiItemsFullEnumO_items( } else { /* Do not use uiItemL here, as our root layout is a menu one, it will add a fake blank icon! */ - but = uiDefBut(block, UI_BTYPE_LABEL, 0, item->name, 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, NULL, - 0.0, 0.0, 0, 0, ""); + but = uiDefBut( + block, UI_BTYPE_LABEL, 0, item->name, 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, NULL, + 0.0, 0.0, 0, 0, ""); } ui_but_tip_from_enum_item(but, item); } @@ -1436,6 +1439,10 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index } } + if ((type == PROP_ENUM) && (RNA_property_flag(prop) & PROP_ENUM_FLAG)) { + flag |= UI_ITEM_R_EXPAND; + } + slider = (flag & UI_ITEM_R_SLIDER) != 0; toggle = (flag & UI_ITEM_R_TOGGLE) != 0; expand = (flag & UI_ITEM_R_EXPAND) != 0; @@ -1461,8 +1468,9 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index uiDefButR_prop(block, UI_BTYPE_ROW, 0, name, 0, 0, w, h, ptr, prop, -1, 0, value, -1, -1, NULL); } /* expanded enum */ - else if (type == PROP_ENUM && (expand || RNA_property_flag(prop) & PROP_ENUM_FLAG)) + else if (type == PROP_ENUM && expand) { ui_item_enum_expand(layout, block, ptr, prop, name, h, icon_only); + } /* property with separate label */ else if (type == PROP_ENUM || type == PROP_STRING || type == PROP_POINTER) { but = ui_item_with_label(layout, block, name, icon, ptr, prop, index, 0, 0, w, h, flag); @@ -1486,7 +1494,7 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index } /* Mark non-embossed textfields inside a listbox. */ - if (but && (block->flag & UI_BLOCK_LIST_ITEM) && (but->dt & UI_EMBOSS_NONE)) { + if (but && (block->flag & UI_BLOCK_LIST_ITEM) && (but->type == UI_BTYPE_TEXT) && (but->dt & UI_EMBOSS_NONE)) { UI_but_flag_enable(but, UI_BUT_LIST_ITEM); } @@ -1538,22 +1546,26 @@ void uiItemEnumR(uiLayout *layout, const char *name, int icon, struct PointerRNA uiItemFullR(layout, ptr, prop, RNA_ENUM_VALUE, value, 0, name, icon); } -void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, const char *name, int icon) + +void uiItemEnumR_string_prop( + uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, + const char *value, const char *name, int icon) { - PropertyRNA *prop = RNA_struct_find_property(ptr, propname); const EnumPropertyItem *item; int ivalue, a; bool free; - if (!prop || RNA_property_type(prop) != PROP_ENUM) { + if (UNLIKELY(RNA_property_type(prop) != PROP_ENUM)) { + const char *propname = RNA_property_identifier(prop); ui_item_disabled(layout, propname); - RNA_warning("enum property not found: %s.%s", RNA_struct_identifier(ptr->type), propname); + RNA_warning("not an enum property: %s.%s", RNA_struct_identifier(ptr->type), propname); return; } RNA_property_enum_items(layout->root->block->evil_C, ptr, prop, &item, NULL, &free); if (!RNA_enum_value_from_id(item, value, &ivalue)) { + const char *propname = RNA_property_identifier(prop); if (free) { MEM_freeN((void *)item); } @@ -1577,6 +1589,19 @@ void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *pr } } +void uiItemEnumR_string( + uiLayout *layout, struct PointerRNA *ptr, const char *propname, + const char *value, const char *name, int icon) +{ + PropertyRNA *prop = RNA_struct_find_property(ptr, propname); + if (UNLIKELY(prop == NULL)) { + ui_item_disabled(layout, propname); + RNA_warning("enum property not found: %s.%s", RNA_struct_identifier(ptr->type), propname); + return; + } + uiItemEnumR_string_prop(layout, ptr, prop, value, name, icon); +} + void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname) { PropertyRNA *prop; @@ -1792,9 +1817,12 @@ void ui_but_add_search(uiBut *but, PointerRNA *ptr, PropertyRNA *prop, PointerRN } } -void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, const char *name, int icon) +void uiItemPointerR_prop( + uiLayout *layout, + PointerRNA *ptr, PropertyRNA *prop, + PointerRNA *searchptr, PropertyRNA *searchprop, + const char *name, int icon) { - PropertyRNA *prop, *searchprop; PropertyType type; uiBut *but; uiBlock *block; @@ -1802,32 +1830,15 @@ void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propna int w, h; char namestr[UI_MAX_NAME_STR]; - /* validate arguments */ - prop = RNA_struct_find_property(ptr, propname); - - if (!prop) { - RNA_warning("property not found: %s.%s", - RNA_struct_identifier(ptr->type), propname); - return; - } - type = RNA_property_type(prop); if (!ELEM(type, PROP_POINTER, PROP_STRING, PROP_ENUM)) { - RNA_warning("Property %s must be a pointer, string or enum", propname); - return; - } - - searchprop = RNA_struct_find_property(searchptr, searchpropname); - - - if (!searchprop) { - RNA_warning("search collection property not found: %s.%s", - RNA_struct_identifier(searchptr->type), searchpropname); + RNA_warning("Property %s.%s must be a pointer, string or enum", + RNA_struct_identifier(ptr->type), RNA_property_identifier(prop)); return; } - else if (RNA_property_type(searchprop) != PROP_COLLECTION) { + if (RNA_property_type(searchprop) != PROP_COLLECTION) { RNA_warning("search collection property is not a collection type: %s.%s", - RNA_struct_identifier(searchptr->type), searchpropname); + RNA_struct_identifier(searchptr->type), RNA_property_identifier(searchprop)); return; } @@ -1855,6 +1866,31 @@ void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propna ui_but_add_search(but, ptr, prop, searchptr, searchprop); } +void uiItemPointerR( + uiLayout *layout, + PointerRNA *ptr, const char *propname, + PointerRNA *searchptr, const char *searchpropname, + const char *name, int icon) +{ + PropertyRNA *prop, *searchprop; + + /* validate arguments */ + prop = RNA_struct_find_property(ptr, propname); + if (!prop) { + RNA_warning("property not found: %s.%s", + RNA_struct_identifier(ptr->type), propname); + return; + } + searchprop = RNA_struct_find_property(searchptr, searchpropname); + if (!searchprop) { + RNA_warning("search collection property not found: %s.%s", + RNA_struct_identifier(searchptr->type), searchpropname); + return; + } + + uiItemPointerR_prop(layout, ptr, prop, searchptr, searchprop, name, icon); +} + /* menu item */ static void ui_item_menutype_func(bContext *C, uiLayout *layout, void *arg_mt) { @@ -1922,7 +1958,7 @@ static uiBut *ui_item_menu( return but; } -void uiItemM(uiLayout *layout, bContext *UNUSED(C), const char *menuname, const char *name, int icon) +void uiItemM(uiLayout *layout, const char *menuname, const char *name, int icon) { MenuType *mt; @@ -2086,8 +2122,9 @@ void uiItemMenuEnumO_ptr( BLI_strncpy(lvl->propname, propname, sizeof(lvl->propname)); lvl->opcontext = layout->root->opcontext; - but = ui_item_menu(layout, name, icon, menu_item_enum_opname_menu, NULL, lvl, - RNA_struct_ui_description(ot->srna), true); + but = ui_item_menu( + layout, name, icon, menu_item_enum_opname_menu, NULL, lvl, + RNA_struct_ui_description(ot->srna), true); /* add hotkey here, lower UI code can't detect it */ if ((layout->root->block->flag & UI_BLOCK_LOOP) && @@ -2859,7 +2896,7 @@ static void ui_litem_layout_overlap(uiLayout *litem) } /* layout create functions */ -uiLayout *uiLayoutRow(uiLayout *layout, int align) +uiLayout *uiLayoutRow(uiLayout *layout, bool align) { uiLayout *litem; @@ -2880,7 +2917,7 @@ uiLayout *uiLayoutRow(uiLayout *layout, int align) return litem; } -uiLayout *uiLayoutColumn(uiLayout *layout, int align) +uiLayout *uiLayoutColumn(uiLayout *layout, bool align) { uiLayout *litem; @@ -2901,7 +2938,7 @@ uiLayout *uiLayoutColumn(uiLayout *layout, int align) return litem; } -uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, int align) +uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, bool align) { uiLayoutItemFlow *flow; @@ -3023,7 +3060,7 @@ uiLayout *uiLayoutListBox( return (uiLayout *)box; } -uiLayout *uiLayoutAbsolute(uiLayout *layout, int align) +uiLayout *uiLayoutAbsolute(uiLayout *layout, bool align) { uiLayout *litem; @@ -3070,7 +3107,7 @@ uiLayout *uiLayoutOverlap(uiLayout *layout) return litem; } -uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, int align) +uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, bool align) { uiLayoutItemSplit *split; diff --git a/source/blender/editors/interface/interface_ops.c b/source/blender/editors/interface/interface_ops.c index 4f5e7a673673..d941f429339c 100644 --- a/source/blender/editors/interface/interface_ops.c +++ b/source/blender/editors/interface/interface_ops.c @@ -92,7 +92,7 @@ static void UI_OT_reset_default_theme(wmOperatorType *ot) /* Copy Data Path Operator ------------------------ */ -static int copy_data_path_button_poll(bContext *C) +static bool copy_data_path_button_poll(bContext *C) { PointerRNA ptr; PropertyRNA *prop; @@ -171,7 +171,7 @@ static void UI_OT_copy_data_path_button(wmOperatorType *ot) RNA_def_property_flag(prop, PROP_SKIP_SAVE); } -static int copy_python_command_button_poll(bContext *C) +static bool copy_python_command_button_poll(bContext *C) { uiBut *but = UI_context_active_but_get(C); @@ -242,7 +242,7 @@ static int operator_button_property_finish(bContext *C, PointerRNA *ptr, Propert } } -static int reset_default_button_poll(bContext *C) +static bool reset_default_button_poll(bContext *C) { PointerRNA ptr; PropertyRNA *prop; @@ -549,7 +549,7 @@ static bool copy_to_selected_button(bContext *C, bool all, bool poll) return success; } -static int copy_to_selected_button_poll(bContext *C) +static bool copy_to_selected_button_poll(bContext *C) { return copy_to_selected_button(C, false, true); } @@ -589,7 +589,7 @@ static void UI_OT_copy_to_selected_button(wmOperatorType *ot) * when there are too many to display... */ -static int reports_to_text_poll(bContext *C) +static bool reports_to_text_poll(bContext *C) { return CTX_wm_reports(C) != NULL; } @@ -730,11 +730,14 @@ void UI_editsource_active_but_test(uiBut *but) static int editsource_text_edit( bContext *C, wmOperator *op, - char filepath[FILE_MAX], int line) + const char filepath[FILE_MAX], const int line) { struct Main *bmain = CTX_data_main(C); Text *text; + /* Developers may wish to copy-paste to an external editor. */ + printf("%s:%d\n", filepath, line); + for (text = bmain->text.first; text; text = text->id.next) { if (text->name && BLI_path_cmp(text->name, filepath) == 0) { break; @@ -806,9 +809,10 @@ static int editsource_exec(bContext *C, wmOperator *op) if (but_store) { if (but_store->py_dbg_ln != -1) { - ret = editsource_text_edit(C, op, - but_store->py_dbg_fn, - but_store->py_dbg_ln); + ret = editsource_text_edit( + C, op, + but_store->py_dbg_fn, + but_store->py_dbg_ln); } else { BKE_report(op->reports, RPT_ERROR, "Active button is not from a script, cannot edit source"); @@ -916,14 +920,18 @@ static int edittranslation_exec(bContext *C, wmOperator *op) uiStringInfo rna_ctxt = {BUT_GET_RNA_LABEL_CONTEXT, NULL}; if (!BLI_is_dir(root)) { - BKE_report(op->reports, RPT_ERROR, "Please set your User Preferences' 'Translation Branches " - "Directory' path to a valid directory"); + BKE_report( + op->reports, RPT_ERROR, + "Please set your User Preferences' 'Translation Branches " + "Directory' path to a valid directory"); return OPERATOR_CANCELLED; } ot = WM_operatortype_find(EDTSRC_I18N_OP_NAME, 0); if (ot == NULL) { - BKE_reportf(op->reports, RPT_ERROR, "Could not find operator '%s'! Please enable ui_translate add-on " - "in the User Preferences", EDTSRC_I18N_OP_NAME); + BKE_reportf( + op->reports, RPT_ERROR, + "Could not find operator '%s'! Please enable ui_translate add-on " + "in the User Preferences", EDTSRC_I18N_OP_NAME); return OPERATOR_CANCELLED; } /* Try to find a valid po file for current language... */ @@ -934,8 +942,9 @@ static int edittranslation_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } - UI_but_string_info_get(C, but, &but_label, &rna_label, &enum_label, &but_tip, &rna_tip, &enum_tip, - &rna_struct, &rna_prop, &rna_enum, &rna_ctxt, NULL); + UI_but_string_info_get( + C, but, &but_label, &rna_label, &enum_label, &but_tip, &rna_tip, &enum_tip, + &rna_struct, &rna_prop, &rna_enum, &rna_ctxt, NULL); WM_operator_properties_create_ptr(&ptr, ot); RNA_string_set(&ptr, "lang", uilng); @@ -1015,7 +1024,7 @@ static void UI_OT_reloadtranslation(wmOperatorType *ot) ot->exec = reloadtranslation_exec; } -int UI_drop_color_poll(struct bContext *C, wmDrag *drag, const wmEvent *UNUSED(event)) +bool UI_drop_color_poll(struct bContext *C, wmDrag *drag, const wmEvent *UNUSED(event)) { /* should only return true for regions that include buttons, for now * return true always */ @@ -1129,6 +1138,7 @@ void ED_operatortypes_ui(void) /* external */ WM_operatortype_append(UI_OT_eyedropper_color); + WM_operatortype_append(UI_OT_eyedropper_color_crypto); WM_operatortype_append(UI_OT_eyedropper_colorband); WM_operatortype_append(UI_OT_eyedropper_colorband_point); WM_operatortype_append(UI_OT_eyedropper_id); @@ -1141,7 +1151,7 @@ void ED_operatortypes_ui(void) */ void ED_keymap_ui(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "User Interface", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "User Interface", 0, 0); wmKeyMapItem *kmi; /* eyedroppers - notice they all have the same shortcut, but pass the event diff --git a/source/blender/editors/interface/interface_panel.c b/source/blender/editors/interface/interface_panel.c index 2c57c8025428..744f6b3c4d0c 100644 --- a/source/blender/editors/interface/interface_panel.c +++ b/source/blender/editors/interface/interface_panel.c @@ -620,9 +620,10 @@ void ui_draw_aligned_panel(uiStyle *style, uiBlock *block, const rcti *rect, con #endif { glEnable(GL_BLEND); - UI_icon_draw_aspect(headrect.xmax - ((PNL_ICON * 2.2f) / block->aspect), headrect.ymin + (5.0f / block->aspect), - (panel->flag & PNL_PIN) ? ICON_PINNED : ICON_UNPINNED, - (block->aspect / UI_DPI_FAC), 1.0f); + UI_icon_draw_aspect( + headrect.xmax - ((PNL_ICON * 2.2f) / block->aspect), headrect.ymin + (5.0f / block->aspect), + (panel->flag & PNL_PIN) ? ICON_PINNED : ICON_UNPINNED, + (block->aspect / UI_DPI_FAC), 1.0f); glDisable(GL_BLEND); } @@ -1755,18 +1756,21 @@ void UI_panel_category_draw_all(ARegion *ar, const char *category_id_active) #endif { glColor3ubv(is_active ? theme_col_tab_active : theme_col_tab_inactive); - ui_panel_category_draw_tab(GL_POLYGON, rct->xmin, rct->ymin, rct->xmax, rct->ymax, - tab_curve_radius - px, roundboxtype, true, true, NULL); + ui_panel_category_draw_tab( + GL_POLYGON, rct->xmin, rct->ymin, rct->xmax, rct->ymax, + tab_curve_radius - px, roundboxtype, true, true, NULL); /* tab outline */ glColor3ubv(theme_col_tab_outline); - ui_panel_category_draw_tab(GL_LINE_STRIP, rct->xmin - px, rct->ymin - px, rct->xmax - px, rct->ymax + px, - tab_curve_radius, roundboxtype, true, true, NULL); + ui_panel_category_draw_tab( + GL_LINE_STRIP, rct->xmin - px, rct->ymin - px, rct->xmax - px, rct->ymax + px, + tab_curve_radius, roundboxtype, true, true, NULL); /* tab highlight (3d look) */ glColor3ubv(is_active ? theme_col_tab_highlight : theme_col_tab_highlight_inactive); - ui_panel_category_draw_tab(GL_LINE_STRIP, rct->xmin, rct->ymin, rct->xmax, rct->ymax, - tab_curve_radius, roundboxtype, true, false, - is_active ? theme_col_back : theme_col_tab_inactive); + ui_panel_category_draw_tab( + GL_LINE_STRIP, rct->xmin, rct->ymin, rct->xmax, rct->ymax, + tab_curve_radius, roundboxtype, true, false, + is_active ? theme_col_back : theme_col_tab_inactive); } /* tab blackline */ @@ -1779,8 +1783,9 @@ void UI_panel_category_draw_all(ARegion *ar, const char *category_id_active) } if (do_scaletabs) { - category_draw_len = BLF_width_to_strlen(fontid, category_id_draw, category_draw_len, - category_width, NULL); + category_draw_len = BLF_width_to_strlen( + fontid, category_id_draw, category_draw_len, + category_width, NULL); } BLF_position(fontid, rct->xmax - text_v_ofs, rct->ymin + tab_v_pad_text, 0.0f); @@ -1992,7 +1997,7 @@ int ui_handler_panel_region(bContext *C, const wmEvent *event, ARegion *ar, cons } else if (event->type == RIGHTMOUSE) { if (mouse_state == PANEL_MOUSE_INSIDE_HEADER) { - ui_panel_menu(C, ar, block->panel); + ui_popup_context_menu_for_panel(C, ar, block->panel); retval = WM_UI_HANDLER_BREAK; break; } @@ -2148,4 +2153,3 @@ static void panel_activate_state(const bContext *C, Panel *pa, uiHandlePanelStat ED_region_tag_redraw(ar); } - diff --git a/source/blender/editors/interface/interface_query.c b/source/blender/editors/interface/interface_query.c new file mode 100644 index 000000000000..1ad4a7d7f31c --- /dev/null +++ b/source/blender/editors/interface/interface_query.c @@ -0,0 +1,107 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/editors/interface/interface_query.c + * \ingroup edinterface + * + * Utilities to inspect the interface, extract information. + */ + +#include "BLI_utildefines.h" + +#include "DNA_screen_types.h" + +#include "UI_interface.h" + +#include "interface_intern.h" + +/* -------------------------------------------------------------------- */ +/** \name Button (uiBut) + * \{ */ + +bool ui_but_is_editable(const uiBut *but) +{ + return !ELEM( + but->type, + UI_BTYPE_LABEL, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, + UI_BTYPE_ROUNDBOX, UI_BTYPE_LISTBOX, UI_BTYPE_PROGRESS_BAR); +} + +bool ui_but_is_editable_as_text(const uiBut *but) +{ + return ELEM( + but->type, + UI_BTYPE_TEXT, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER, + UI_BTYPE_SEARCH_MENU); + +} + +bool ui_but_is_toggle(const uiBut *but) +{ + return ELEM( + but->type, + UI_BTYPE_BUT_TOGGLE, + UI_BTYPE_TOGGLE, + UI_BTYPE_ICON_TOGGLE, + UI_BTYPE_ICON_TOGGLE_N, + UI_BTYPE_TOGGLE_N, + UI_BTYPE_CHECKBOX, + UI_BTYPE_CHECKBOX_N, + UI_BTYPE_ROW + ); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Block (uiBlock) + * \{ */ + +bool ui_block_is_menu(const uiBlock *block) +{ + return (((block->flag & UI_BLOCK_LOOP) != 0) && + /* non-menu popups use keep-open, so check this is off */ + ((block->flag & UI_BLOCK_KEEP_OPEN) == 0)); +} + +bool ui_block_is_pie_menu(const uiBlock *block) +{ + return ((block->flag & UI_BLOCK_RADIAL) != 0); +} + +bool ui_block_is_popup_any(const uiBlock *block) +{ + return ( + ui_block_is_menu(block) || + ui_block_is_pie_menu(block) + ); +} + +bool UI_block_is_empty(const uiBlock *block) +{ + for (const uiBut *but = block->buttons.first; but; but = but->next) { + if (!ELEM(but->type, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE)) { + return false; + } + } + return true; +} + +/** \} */ diff --git a/source/blender/editors/interface/interface_region_color_picker.c b/source/blender/editors/interface/interface_region_color_picker.c index 4309e913d9ee..00462b456eab 100644 --- a/source/blender/editors/interface/interface_region_color_picker.c +++ b/source/blender/editors/interface/interface_region_color_picker.c @@ -585,7 +585,7 @@ static int ui_colorpicker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *blo ui_rgb_to_color_picker_compat_v(rgb, hsv); - hsv[2] = CLAMPIS(hsv[2] + add, 0.0f, 1.0f); + hsv[2] = clamp_f(hsv[2] + add, 0.0f, 1.0f); ui_color_picker_to_rgb_v(hsv, rgb); if (use_display_colorspace) diff --git a/source/blender/editors/interface/interface_region_menu_popup.c b/source/blender/editors/interface/interface_region_menu_popup.c index 9aec955413f5..fa7113f195ed 100644 --- a/source/blender/editors/interface/interface_region_menu_popup.c +++ b/source/blender/editors/interface/interface_region_menu_popup.c @@ -454,6 +454,21 @@ void UI_popup_menu_end(bContext *C, uiPopupMenu *pup) MEM_freeN(pup); } +bool UI_popup_menu_end_or_cancel(bContext *C, uiPopupMenu *pup) +{ + if (!UI_block_is_empty(pup->block)) { + UI_popup_menu_end(C, pup); + return true; + } + else { + UI_block_layout_resolve(pup->block, NULL, NULL); + MEM_freeN(pup->block->handle); + UI_block_free(C, pup->block); + MEM_freeN(pup); + return false; + } +} + uiLayout *UI_popup_menu_layout(uiPopupMenu *pup) { return pup->layout; diff --git a/source/blender/editors/interface/interface_region_search.c b/source/blender/editors/interface/interface_region_search.c index c9d313a4bab6..8d4389c73e64 100644 --- a/source/blender/editors/interface/interface_region_search.c +++ b/source/blender/editors/interface/interface_region_search.c @@ -418,8 +418,9 @@ static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar) ui_searchbox_butrect(&rect, data, a); /* widget itself */ - ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], - (a == data->active) ? UI_ACTIVE : 0); + ui_draw_preview_item( + &data->fstyle, &rect, data->items.names[a], data->items.icons[a], + (a == data->active) ? UI_ACTIVE : 0); } /* indicate more */ @@ -443,8 +444,9 @@ static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar) ui_searchbox_butrect(&rect, data, a); /* widget itself */ - ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], - (a == data->active) ? UI_ACTIVE : 0, data->use_sep); + ui_draw_menu_item( + &data->fstyle, &rect, data->items.names[a], data->items.icons[a], + (a == data->active) ? UI_ACTIVE : 0, data->use_sep); } /* indicate more */ @@ -718,8 +720,9 @@ static void ui_searchbox_region_draw_cb__operator(const bContext *UNUSED(C), ARe } rect_pre.xmax += 4; /* sneaky, avoid showing ugly margin */ - ui_draw_menu_item(&data->fstyle, &rect_pre, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, text_pre), - data->items.icons[a], state, false); + ui_draw_menu_item( + &data->fstyle, &rect_pre, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, text_pre), + data->items.icons[a], state, false); ui_draw_menu_item(&data->fstyle, &rect_post, data->items.names[a], 0, state, data->use_sep); } diff --git a/source/blender/editors/interface/interface_style.c b/source/blender/editors/interface/interface_style.c index e5f1a69d3b3f..c7ecc37b0bf2 100644 --- a/source/blender/editors/interface/interface_style.c +++ b/source/blender/editors/interface/interface_style.c @@ -521,6 +521,40 @@ void uiStyleInit(void) BLF_size(blf_mono_font, 12 * U.pixelsize, 72); + /* Set default flags based on UI preferences (not render fonts) */ + { + int flag_disable = BLF_MONOCHROME | + BLF_HINTING_NONE | + BLF_HINTING_SLIGHT | + BLF_HINTING_FULL; + int flag_enable = 0; + + if (U.text_render & USER_TEXT_HINTING_NONE) { + flag_enable |= BLF_HINTING_NONE; + } + else if (U.text_render & USER_TEXT_HINTING_SLIGHT) { + flag_enable |= BLF_HINTING_SLIGHT; + } + else if (U.text_render & USER_TEXT_HINTING_FULL) { + flag_enable |= BLF_HINTING_FULL; + } + + if (U.text_render & USER_TEXT_DISABLE_AA) { + flag_enable |= BLF_MONOCHROME; + } + + for (font = U.uifonts.first; font; font = font->next) { + if (font->blf_id != -1) { + BLF_disable(font->blf_id, flag_disable); + BLF_enable(font->blf_id, flag_enable); + } + } + if (blf_mono_font != -1) { + BLF_disable(blf_mono_font, flag_disable); + BLF_enable(blf_mono_font, flag_enable); + } + } + /** * Second for rendering else we get threading problems, * @@ -539,4 +573,3 @@ void UI_fontstyle_set(const uiFontStyle *fs) BLF_size(font->blf_id, fs->points * U.pixelsize, U.dpi); } - diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c index 574e1463857f..9d05819dd6a0 100644 --- a/source/blender/editors/interface/interface_templates.c +++ b/source/blender/editors/interface/interface_templates.c @@ -276,8 +276,9 @@ static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem) /* fake button, it holds space for search items */ uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 26, w, h, NULL, 0, 0, 0, 0, NULL); - but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, w, UI_UNIT_Y, - template_ui.prv_rows, template_ui.prv_cols, ""); + but = uiDefSearchBut( + block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, w, UI_UNIT_Y, + template_ui.prv_rows, template_ui.prv_cols, ""); UI_but_func_search_set( but, ui_searchbox_create_generic, id_search_cb_p, &template_ui, id_search_call_cb, idptr.data); @@ -394,8 +395,9 @@ static void template_id_cb(bContext *C, void *arg_litem, void *arg_event) break; case UI_ID_ALONE: if (id) { - const bool do_scene_obj = (GS(id->name) == ID_OB) && - (template_ui->ptr.type == &RNA_SceneObjects); + const bool do_scene_obj = ( + (GS(id->name) == ID_OB) && + (template_ui->ptr.type == &RNA_SceneObjects)); /* make copy */ if (do_scene_obj) { @@ -497,10 +499,12 @@ static void template_ID( if (flag & UI_ID_PREVIEWS) { template_ui->preview = true; - but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, - TIP_(template_id_browse_tip(type))); - ui_def_but_icon(but, id ? ui_id_icon_get(C, id, true) : RNA_struct_ui_icon(type), - UI_HAS_ICON | UI_BUT_ICON_PREVIEW); + but = uiDefBlockButN( + block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, + TIP_(template_id_browse_tip(type))); + ui_def_but_icon( + but, id ? ui_id_icon_get(C, id, true) : RNA_struct_ui_icon(type), + UI_HAS_ICON | UI_BUT_ICON_PREVIEW); if ((idfrom && idfrom->lib) || !editable) UI_but_flag_enable(but, UI_BUT_DISABLED); @@ -508,8 +512,9 @@ static void template_ID( uiLayoutRow(layout, true); } else if (flag & UI_ID_BROWSE) { - but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y, - TIP_(template_id_browse_tip(type))); + but = uiDefBlockButN( + block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y, + TIP_(template_id_browse_tip(type))); ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON); /* default dragging of icon for id browse buttons */ UI_but_drag_set_id(but, id); @@ -526,20 +531,23 @@ static void template_ID( //text_idbutton(id, name); name[0] = '\0'; - but = uiDefButR(block, UI_BTYPE_TEXT, 0, name, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y, - &idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type)); + but = uiDefButR( + block, UI_BTYPE_TEXT, 0, name, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y, + &idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type)); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_RENAME)); if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT); if (id->lib) { if (id->tag & LIB_TAG_INDIRECT) { - but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_INDIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y, - NULL, 0, 0, 0, 0, TIP_("Indirect library data-block, cannot change")); + but = uiDefIconBut( + block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_INDIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y, + NULL, 0, 0, 0, 0, TIP_("Indirect library data-block, cannot change")); UI_but_flag_enable(but, UI_BUT_DISABLED); } else { - but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_DIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y, - NULL, 0, 0, 0, 0, TIP_("Direct linked library data-block, click to make local")); + but = uiDefIconBut( + block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_DIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y, + NULL, 0, 0, 0, 0, TIP_("Direct linked library data-block, click to make local")); if (!id_make_local(CTX_data_main(C), id, true /* test */, false) || (idfrom && idfrom->lib)) UI_but_flag_enable(but, UI_BUT_DISABLED); } @@ -553,9 +561,10 @@ static void template_ID( numstr_len = BLI_snprintf(numstr, sizeof(numstr), "%d", id->us); - but = uiDefBut(block, UI_BTYPE_BUT, 0, numstr, 0, 0, - numstr_len * 0.2f * UI_UNIT_X + UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, - TIP_("Display number of users of this data (click to make a single-user copy)")); + but = uiDefBut( + block, UI_BTYPE_BUT, 0, numstr, 0, 0, + numstr_len * 0.2f * UI_UNIT_X + UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, + TIP_("Display number of users of this data (click to make a single-user copy)")); but->flag |= UI_BUT_UNDO; UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ALONE)); @@ -581,41 +590,47 @@ static void template_ID( int w = id ? UI_UNIT_X : (flag & UI_ID_OPEN) ? UI_UNIT_X * 3 : UI_UNIT_X * 6; /* i18n markup, does nothing! */ - BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_DEFAULT, - BLT_I18NCONTEXT_ID_SCENE, - BLT_I18NCONTEXT_ID_OBJECT, - BLT_I18NCONTEXT_ID_MESH, - BLT_I18NCONTEXT_ID_CURVE, - BLT_I18NCONTEXT_ID_METABALL, - BLT_I18NCONTEXT_ID_MATERIAL, - BLT_I18NCONTEXT_ID_TEXTURE, - BLT_I18NCONTEXT_ID_IMAGE, - BLT_I18NCONTEXT_ID_LATTICE, - BLT_I18NCONTEXT_ID_LAMP, - BLT_I18NCONTEXT_ID_CAMERA, - BLT_I18NCONTEXT_ID_WORLD, - BLT_I18NCONTEXT_ID_SCREEN, - BLT_I18NCONTEXT_ID_TEXT, + BLT_I18N_MSGID_MULTI_CTXT( + "New", + BLT_I18NCONTEXT_DEFAULT, + BLT_I18NCONTEXT_ID_SCENE, + BLT_I18NCONTEXT_ID_OBJECT, + BLT_I18NCONTEXT_ID_MESH, + BLT_I18NCONTEXT_ID_CURVE, + BLT_I18NCONTEXT_ID_METABALL, + BLT_I18NCONTEXT_ID_MATERIAL, + BLT_I18NCONTEXT_ID_TEXTURE, + BLT_I18NCONTEXT_ID_IMAGE, + BLT_I18NCONTEXT_ID_LATTICE, + BLT_I18NCONTEXT_ID_LAMP, + BLT_I18NCONTEXT_ID_CAMERA, + BLT_I18NCONTEXT_ID_WORLD, + BLT_I18NCONTEXT_ID_SCREEN, + BLT_I18NCONTEXT_ID_TEXT, ); - BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_ID_SPEAKER, - BLT_I18NCONTEXT_ID_SOUND, - BLT_I18NCONTEXT_ID_ARMATURE, - BLT_I18NCONTEXT_ID_ACTION, - BLT_I18NCONTEXT_ID_NODETREE, - BLT_I18NCONTEXT_ID_BRUSH, - BLT_I18NCONTEXT_ID_PARTICLESETTINGS, - BLT_I18NCONTEXT_ID_GPENCIL, - BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE, + BLT_I18N_MSGID_MULTI_CTXT( + "New", + BLT_I18NCONTEXT_ID_SPEAKER, + BLT_I18NCONTEXT_ID_SOUND, + BLT_I18NCONTEXT_ID_ARMATURE, + BLT_I18NCONTEXT_ID_ACTION, + BLT_I18NCONTEXT_ID_NODETREE, + BLT_I18NCONTEXT_ID_BRUSH, + BLT_I18NCONTEXT_ID_PARTICLESETTINGS, + BLT_I18NCONTEXT_ID_GPENCIL, + BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE, ); if (newop) { - but = uiDefIconTextButO(block, UI_BTYPE_BUT, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, - (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), 0, 0, w, UI_UNIT_Y, NULL); + but = uiDefIconTextButO( + block, UI_BTYPE_BUT, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, + (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), 0, 0, w, UI_UNIT_Y, NULL); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ADD_NEW)); } else { - but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), - 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL); + but = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), + 0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ADD_NEW)); } @@ -626,8 +641,9 @@ static void template_ID( /* Due to space limit in UI - skip the "open" icon for packed data, and allow to unpack. * Only for images, sound and fonts */ if (id && BKE_pack_check(id)) { - but = uiDefIconButO(block, UI_BTYPE_BUT, "FILE_OT_unpack_item", WM_OP_INVOKE_REGION_WIN, ICON_PACKAGE, 0, 0, - UI_UNIT_X, UI_UNIT_Y, TIP_("Packed File, click to unpack")); + but = uiDefIconButO( + block, UI_BTYPE_BUT, "FILE_OT_unpack_item", WM_OP_INVOKE_REGION_WIN, ICON_PACKAGE, 0, 0, + UI_UNIT_X, UI_UNIT_Y, TIP_("Packed File, click to unpack")); UI_but_operator_ptr_get(but); RNA_string_set(but->opptr, "id_name", id->name + 2); @@ -638,13 +654,15 @@ static void template_ID( int w = id ? UI_UNIT_X : (flag & UI_ID_ADD_NEW) ? UI_UNIT_X * 3 : UI_UNIT_X * 6; if (openop) { - but = uiDefIconTextButO(block, UI_BTYPE_BUT, openop, WM_OP_INVOKE_DEFAULT, ICON_FILESEL, (id) ? "" : IFACE_("Open"), - 0, 0, w, UI_UNIT_Y, NULL); + but = uiDefIconTextButO( + block, UI_BTYPE_BUT, openop, WM_OP_INVOKE_DEFAULT, ICON_FILESEL, (id) ? "" : IFACE_("Open"), + 0, 0, w, UI_UNIT_Y, NULL); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_OPEN)); } else { - but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILESEL, (id) ? "" : IFACE_("Open"), 0, 0, w, UI_UNIT_Y, - NULL, 0, 0, 0, 0, NULL); + but = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_FILESEL, (id) ? "" : IFACE_("Open"), 0, 0, w, UI_UNIT_Y, + NULL, 0, 0, 0, 0, NULL); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_OPEN)); } @@ -665,9 +683,10 @@ static void template_ID( } else { if ((RNA_property_flag(template_ui->prop) & PROP_NEVER_UNLINK) == 0) { - but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, - TIP_("Unlink data-block " - "(Shift + Click to set users to zero, data will then not be saved)")); + but = uiDefIconBut( + block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, + TIP_("Unlink data-block " + "(Shift + Click to set users to zero, data will then not be saved)")); UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_DELETE)); if (RNA_property_flag(template_ui->prop) & PROP_NEVER_NULL) { @@ -743,8 +762,9 @@ void uiTemplateID( uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int filter) { - ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, - UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0, filter); + ui_template_id( + layout, C, ptr, propname, newop, openop, unlinkop, + UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0, filter); } void uiTemplateIDBrowse( @@ -758,8 +778,9 @@ void uiTemplateIDPreview( uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int rows, int cols, int filter) { - ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, - UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols, filter); + ui_template_id( + layout, C, ptr, propname, newop, openop, unlinkop, + UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols, filter); } /************************ ID Chooser Template ***************************/ @@ -832,8 +853,9 @@ void uiTemplateAnyID( * - propname: property identifier for property that path gets stored to * - root_ptr: struct that path gets built from */ -void uiTemplatePathBuilder(uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *UNUSED(root_ptr), - const char *text) +void uiTemplatePathBuilder( + uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *UNUSED(root_ptr), + const char *text) { PropertyRNA *propPath; uiLayout *row; @@ -938,8 +960,9 @@ static uiLayout *draw_modifier( BLI_snprintf(str, sizeof(str), IFACE_("%s parent deform"), md->name); uiDefBut(block, UI_BTYPE_LABEL, 0, str, 0, 0, 185, UI_UNIT_Y, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Modifier name")); - but = uiDefBut(block, UI_BTYPE_BUT, 0, IFACE_("Make Real"), 0, 0, 80, 16, NULL, 0.0, 0.0, 0.0, 0.0, - TIP_("Convert virtual modifier to a real modifier")); + but = uiDefBut( + block, UI_BTYPE_BUT, 0, IFACE_("Make Real"), 0, 0, 80, 16, NULL, 0.0, 0.0, 0.0, 0.0, + TIP_("Convert virtual modifier to a real modifier")); UI_but_func_set(but, modifiers_convertToReal, ob, md); } else { @@ -995,9 +1018,10 @@ static uiLayout *draw_modifier( if (ELEM(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) { /* add disabled pre-tessellated button, so users could have * message for this modifiers */ - but = uiDefIconButBitI(block, UI_BTYPE_TOGGLE, eModifierMode_ApplyOnSpline, 0, ICON_SURFACE_DATA, 0, 0, - UI_UNIT_X - 2, UI_UNIT_Y, &md->mode, 0.0, 0.0, 0.0, 0.0, - TIP_("This modifier can only be applied on splines' points")); + but = uiDefIconButBitI( + block, UI_BTYPE_TOGGLE, eModifierMode_ApplyOnSpline, 0, ICON_SURFACE_DATA, 0, 0, + UI_UNIT_X - 2, UI_UNIT_Y, &md->mode, 0.0, 0.0, 0.0, 0.0, + TIP_("This modifier can only be applied on splines' points")); UI_but_flag_enable(but, UI_BUT_DISABLED); } else if (mti->type != eModifierTypeType_Constructive) { @@ -1373,7 +1397,7 @@ static void do_preview_buttons(bContext *C, void *arg, int event) } void uiTemplatePreview( - uiLayout *layout, bContext *C, ID *id, int show_buttons, ID *parent, MTex *slot, + uiLayout *layout, bContext *C, ID *id, bool show_buttons, ID *parent, MTex *slot, const char *preview_id) { uiLayout *row, *col; @@ -1452,8 +1476,9 @@ void uiTemplatePreview( UI_but_func_drawextra_set(block, ED_preview_draw, pparent, slot); UI_block_func_handle_set(block, do_preview_buttons, NULL); - uiDefIconButS(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &ui_preview->height, - UI_UNIT_Y, UI_UNIT_Y * 50.0f, 0.0f, 0.0f, ""); + uiDefIconButS( + block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &ui_preview->height, + UI_UNIT_Y, UI_UNIT_Y * 50.0f, 0.0f, 0.0f, ""); /* add buttons */ if (pid && show_buttons) { @@ -1601,17 +1626,20 @@ static void colorband_buttons_layout( UI_block_align_begin(block); row = uiLayoutRow(split, false); - bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, "", 0, 0, 2.0f * unit, UI_UNIT_Y, NULL, - 0, 0, 0, 0, TIP_("Add a new color stop to the colorband")); + bt = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, "", 0, 0, 2.0f * unit, UI_UNIT_Y, NULL, + 0, 0, 0, 0, TIP_("Add a new color stop to the colorband")); UI_but_funcN_set(bt, colorband_add_cb, MEM_dupallocN(cb), coba); - bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMOUT, "", xs + 2.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y, - NULL, 0, 0, 0, 0, TIP_("Delete the active position")); + bt = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_ZOOMOUT, "", xs + 2.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y, + NULL, 0, 0, 0, 0, TIP_("Delete the active position")); UI_but_funcN_set(bt, colorband_del_cb, MEM_dupallocN(cb), coba); - bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y, - NULL, 0, 0, 0, 0, TIP_("Flip the color ramp")); + bt = uiDefIconTextBut( + block, UI_BTYPE_BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y, + NULL, 0, 0, 0, 0, TIP_("Flip the color ramp")); UI_but_funcN_set(bt, colorband_flip_cb, MEM_dupallocN(cb), coba); bt = uiDefIconButO(block, UI_BTYPE_BUT, "UI_OT_eyedropper_colorband", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, xs + 6.0f * unit, ys + UI_UNIT_Y, UI_UNIT_X, UI_UNIT_Y, NULL); @@ -1683,7 +1711,7 @@ static void colorband_buttons_layout( } } -void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname, int expand) +void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname, bool expand) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); PointerRNA cptr; @@ -1783,7 +1811,7 @@ static uiBlock *ui_icon_view_menu_cb(bContext *C, ARegion *ar, void *arg_litem) /** * \param icon_scale: Scale of the icon, 1x == button height. */ -void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname, int show_labels, float icon_scale) +void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname, bool show_labels, float icon_scale) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); IconViewMenuArgs *cb_args; @@ -2012,8 +2040,9 @@ static uiBlock *curvemap_clipping_func(bContext *C, ARegion *ar, void *cumap_v) /* use this for a fake extra empy space around the buttons */ uiDefBut(block, UI_BTYPE_LABEL, 0, "", -4, 16, width + 8, 6 * UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - bt = uiDefButBitI(block, UI_BTYPE_TOGGLE, CUMA_DO_CLIP, 1, IFACE_("Use Clipping"), - 0, 5 * UI_UNIT_Y, width, UI_UNIT_Y, &cumap->flag, 0.0, 0.0, 10, 0, ""); + bt = uiDefButBitI( + block, UI_BTYPE_TOGGLE, CUMA_DO_CLIP, 1, IFACE_("Use Clipping"), + 0, 5 * UI_UNIT_Y, width, UI_UNIT_Y, &cumap->flag, 0.0, 0.0, 10, 0, ""); UI_but_func_set(bt, curvemap_buttons_setclip, cumap, NULL); UI_block_align_begin(block); @@ -2176,8 +2205,8 @@ static void curvemap_buttons_reset(bContext *C, void *cb_v, void *cumap_v) /* still unsure how this call evolves... we use labeltype for defining what curve-channels to show */ static void curvemap_buttons_layout( - uiLayout *layout, PointerRNA *ptr, char labeltype, int levels, - int brush, int neg_slope, RNAUpdateCb *cb) + uiLayout *layout, PointerRNA *ptr, char labeltype, bool levels, + bool brush, bool neg_slope, RNAUpdateCb *cb) { CurveMapping *cumap = ptr->data; CurveMap *cm = &cumap->cm[cumap->cur]; @@ -2272,11 +2301,13 @@ static void curvemap_buttons_layout( if (brush) bt = uiDefIconBlockBut(block, curvemap_brush_tools_func, cumap, 0, ICON_MODIFIER, 0, 0, dx, dx, TIP_("Tools")); else if (neg_slope) - bt = uiDefIconBlockBut(block, curvemap_tools_negslope_func, cumap, 0, ICON_MODIFIER, - 0, 0, dx, dx, TIP_("Tools")); + bt = uiDefIconBlockBut( + block, curvemap_tools_negslope_func, cumap, 0, ICON_MODIFIER, + 0, 0, dx, dx, TIP_("Tools")); else - bt = uiDefIconBlockBut(block, curvemap_tools_posslope_func, cumap, 0, ICON_MODIFIER, - 0, 0, dx, dx, TIP_("Tools")); + bt = uiDefIconBlockBut( + block, curvemap_tools_posslope_func, cumap, 0, ICON_MODIFIER, + 0, 0, dx, dx, TIP_("Tools")); UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL); @@ -2340,7 +2371,7 @@ static void curvemap_buttons_layout( void uiTemplateCurveMapping( uiLayout *layout, PointerRNA *ptr, const char *propname, int type, - int levels, int brush, int neg_slope) + bool levels, bool brush, bool neg_slope) { RNAUpdateCb *cb; PropertyRNA *prop = RNA_struct_find_property(ptr, propname); @@ -2384,8 +2415,8 @@ void uiTemplateCurveMapping( /* This template now follows User Preference for type - name is not correct anymore... */ void uiTemplateColorPicker( - uiLayout *layout, PointerRNA *ptr, const char *propname, int value_slider, - int lock, int lock_luminosity, int cubic) + uiLayout *layout, PointerRNA *ptr, const char *propname, bool value_slider, + bool lock, bool lock_luminosity, bool cubic) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); uiBlock *block = uiLayoutGetBlock(layout); @@ -2406,24 +2437,28 @@ void uiTemplateColorPicker( switch (U.color_picker_type) { case USER_CP_SQUARE_SV: - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, - -1, 0.0, 0.0, UI_GRAD_SV, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, + -1, 0.0, 0.0, UI_GRAD_SV, 0, ""); break; case USER_CP_SQUARE_HS: - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, - -1, 0.0, 0.0, UI_GRAD_HS, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, + -1, 0.0, 0.0, UI_GRAD_HS, 0, ""); break; case USER_CP_SQUARE_HV: - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, - -1, 0.0, 0.0, UI_GRAD_HV, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, + -1, 0.0, 0.0, UI_GRAD_HV, 0, ""); break; /* user default */ case USER_CP_CIRCLE_HSV: case USER_CP_CIRCLE_HSL: default: - but = uiDefButR_prop(block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, - -1, 0.0, 0.0, 0, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop, + -1, 0.0, 0.0, 0, 0, ""); break; } @@ -2449,31 +2484,36 @@ void uiTemplateColorPicker( switch (U.color_picker_type) { case USER_CP_CIRCLE_HSL: uiItemS(row); - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop, - -1, softmin, softmax, UI_GRAD_L_ALT, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop, + -1, softmin, softmax, UI_GRAD_L_ALT, 0, ""); break; case USER_CP_SQUARE_SV: uiItemS(col); - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, - -1, softmin, softmax, UI_GRAD_SV + 3, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, + -1, softmin, softmax, UI_GRAD_SV + 3, 0, ""); break; case USER_CP_SQUARE_HS: uiItemS(col); - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, - -1, softmin, softmax, UI_GRAD_HS + 3, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, + -1, softmin, softmax, UI_GRAD_HS + 3, 0, ""); break; case USER_CP_SQUARE_HV: uiItemS(col); - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, - -1, softmin, softmax, UI_GRAD_HV + 3, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop, + -1, softmin, softmax, UI_GRAD_HV + 3, 0, ""); break; /* user default */ case USER_CP_CIRCLE_HSV: default: uiItemS(row); - but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop, - -1, softmin, softmax, UI_GRAD_V_ALT, 0, ""); + but = uiDefButR_prop( + block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop, + -1, softmin, softmax, UI_GRAD_V_ALT, 0, ""); break; } @@ -2481,7 +2521,7 @@ void uiTemplateColorPicker( } } -void uiTemplatePalette(uiLayout *layout, PointerRNA *ptr, const char *propname, int UNUSED(colors)) +void uiTemplatePalette(uiLayout *layout, PointerRNA *ptr, const char *propname, bool UNUSED(colors)) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); PointerRNA cptr; @@ -2524,13 +2564,32 @@ void uiTemplatePalette(uiLayout *layout, PointerRNA *ptr, const char *propname, } RNA_pointer_create(&palette->id, &RNA_PaletteColor, color, &color_ptr); - uiDefButR(block, UI_BTYPE_COLOR, 0, "", 0, 0, UI_UNIT_X, UI_UNIT_Y, &color_ptr, "color", -1, 0.0, 1.0, - UI_PALETTE_COLOR, col_id, ""); + uiDefButR( + block, UI_BTYPE_COLOR, 0, "", 0, 0, UI_UNIT_X, UI_UNIT_Y, &color_ptr, "color", -1, 0.0, 1.0, + UI_PALETTE_COLOR, col_id, ""); row_cols++; col_id++; } } +void uiTemplateCryptoPicker(uiLayout *layout, PointerRNA *ptr, const char *propname) +{ + PropertyRNA *prop = RNA_struct_find_property(ptr, propname); + uiBlock *block; + uiBut *but; + + if (!prop) { + RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname); + return; + } + + block = uiLayoutGetBlock(layout); + + but = uiDefIconTextButO(block, UI_BTYPE_BUT, "UI_OT_eyedropper_color_crypto", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, RNA_property_ui_name(prop), 0, 0, UI_UNIT_X, UI_UNIT_Y, RNA_property_ui_description(prop)); + but->rnapoin = *ptr; + but->rnaprop = prop; + but->rnaindex = -1; +} /********************* Layer Buttons Template ************************/ @@ -2689,8 +2748,9 @@ void uiTemplateGameStates( else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state)) icon = ICON_LAYER_USED; - but = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop, - state, 0, 0, -1, -1, sca_state_name_get(ob, state)); + but = uiDefIconButR_prop( + block, UI_BTYPE_ICON_TOGGLE, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop, + state, 0, 0, -1, -1, sca_state_name_get(ob, state)); UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state)); but->type = UI_BTYPE_TOGGLE; } @@ -2757,8 +2817,9 @@ static int cmpstringp(const void *p1, const void *p2) return BLI_strcasecmp(((StringCmp *) p1)->name, ((StringCmp *) p2)->name); } -static void uilist_filter_items_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct PointerRNA *dataptr, - const char *propname) +static void uilist_filter_items_default( + struct uiList *ui_list, struct bContext *UNUSED(C), struct PointerRNA *dataptr, + const char *propname) { uiListDyn *dyn_data = ui_list->dyn_data; PropertyRNA *prop = RNA_struct_find_property(dataptr, propname); @@ -3200,9 +3261,10 @@ void uiTemplateList( /* list item behind label & other buttons */ sub = uiLayoutRow(overlap, false); - but = uiDefButR_prop(subblock, UI_BTYPE_LISTROW, 0, "", 0, 0, UI_UNIT_X * 10, UI_UNIT_Y, - active_dataptr, activeprop, 0, 0, org_i, 0, 0, - TIP_("Double click to rename")); + but = uiDefButR_prop( + subblock, UI_BTYPE_LISTROW, 0, "", 0, 0, UI_UNIT_X * 10, UI_UNIT_Y, + active_dataptr, activeprop, 0, 0, org_i, 0, 0, + TIP_("Double click to rename")); if ((dyntip_data = uilist_item_use_dynamic_tooltip(itemptr, item_dyntip_propname))) { UI_but_func_tooltip_set(but, uilist_item_tooltip_func, dyntip_data); } @@ -3258,8 +3320,9 @@ void uiTemplateList( /* next/prev button */ BLI_snprintf(numstr, sizeof(numstr), "%d :", dyn_data->items_shown); - but = uiDefIconTextButR_prop(block, UI_BTYPE_NUM, 0, 0, numstr, 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, - active_dataptr, activeprop, 0, 0, 0, 0, 0, ""); + but = uiDefIconTextButR_prop( + block, UI_BTYPE_NUM, 0, 0, numstr, 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, + active_dataptr, activeprop, 0, 0, 0, 0, 0, ""); if (dyn_data->items_shown == 0) UI_but_flag_enable(but, UI_BUT_DISABLED); break; @@ -3486,13 +3549,24 @@ static void ui_layout_operator_buts__reset_cb(bContext *UNUSED(C), void *op_pt, } #endif +struct uiTemplateOperatorPropertyPollParam { + const bContext *C; + wmOperator *op; +}; + +static bool ui_layout_operator_buts_poll_property( + struct PointerRNA *UNUSED(ptr), struct PropertyRNA *prop, void *user_data) +{ + struct uiTemplateOperatorPropertyPollParam *params = user_data; + return params->op->type->poll_property(params->C, params->op, prop); +} + /** * Draw Operator property buttons for redoing execution with different settings. * This function does not initialize the layout, functions can be called on the layout before and after. */ void uiTemplateOperatorPropertyButs( const bContext *C, uiLayout *layout, wmOperator *op, - bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *), const char label_align, const short flag) { if (!op->properties) { @@ -3526,7 +3600,7 @@ void uiTemplateOperatorPropertyButs( uiLayoutGetBlock(layout)->ui_operator = op; row = uiLayoutRow(layout, true); - uiItemM(row, (bContext *)C, "WM_MT_operator_presets", NULL, ICON_NONE); + uiItemM(row, "WM_MT_operator_presets", NULL, ICON_NONE); wmOperatorType *ot = WM_operatortype_find("WM_OT_operator_preset_add", false); uiItemFullO_ptr(row, ot, "", ICON_ZOOMIN, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr); @@ -3548,11 +3622,16 @@ void uiTemplateOperatorPropertyButs( wmWindowManager *wm = CTX_wm_manager(C); PointerRNA ptr; int empty; + struct uiTemplateOperatorPropertyPollParam user_data = {.C = C, .op = op}; RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); /* main draw call */ - empty = uiDefAutoButsRNA(layout, &ptr, check_prop, label_align) == 0; + empty = uiDefAutoButsRNA( + layout, &ptr, + op->type->poll_property ? ui_layout_operator_buts_poll_property : NULL, + op->type->poll_property ? &user_data : NULL, + label_align) == 0; if (empty && (flag & UI_TEMPLATE_OP_PROPS_SHOW_EMPTY)) { uiItemL(layout, IFACE_("No Properties"), ICON_NONE); @@ -3800,9 +3879,6 @@ void uiTemplateRunningJobs(uiLayout *layout, bContext *C) NULL, 0.0f, 0.0f, 0, 0, TIP_("Stop this job")); } - if (WM_jobs_test(wm, screen, WM_JOB_TYPE_SCREENCAST)) - uiDefIconTextBut(block, UI_BTYPE_BUT, B_STOPCAST, ICON_CANCEL, IFACE_("Capture"), 0, 0, UI_UNIT_X * 4.25f, UI_UNIT_Y, - NULL, 0.0f, 0.0f, 0, 0, TIP_("Stop screencast")); if (screen->animtimer) uiDefIconTextBut(block, UI_BTYPE_BUT, B_STOPANIM, ICON_CANCEL, IFACE_("Anim Player"), 0, 0, UI_UNIT_X * 5.0f, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0, TIP_("Stop animation playback")); diff --git a/source/blender/editors/interface/interface_utils.c b/source/blender/editors/interface/interface_utils.c index 28aecc140359..2059fc1c849b 100644 --- a/source/blender/editors/interface/interface_utils.c +++ b/source/blender/editors/interface/interface_utils.c @@ -159,7 +159,7 @@ uiBut *uiDefAutoButR(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int ind */ int uiDefAutoButsRNA( uiLayout *layout, PointerRNA *ptr, - bool (*check_prop)(PointerRNA *, PropertyRNA *), + bool (*check_prop)(PointerRNA *ptr, PropertyRNA *prop, void *user_data), void *user_data, const char label_align) { uiLayout *split, *col; @@ -172,8 +172,9 @@ int uiDefAutoButsRNA( RNA_STRUCT_BEGIN (ptr, prop) { flag = RNA_property_flag(prop); - if (flag & PROP_HIDDEN || (check_prop && check_prop(ptr, prop) == 0)) + if (flag & PROP_HIDDEN || (check_prop && check_prop(ptr, prop, user_data) == 0)) { continue; + } if (label_align != '\0') { PropertyType type = RNA_property_type(prop); @@ -316,8 +317,9 @@ int UI_calc_float_precision(int prec, double value) bool UI_but_online_manual_id(const uiBut *but, char *r_str, size_t maxlength) { if (but->rnapoin.id.data && but->rnapoin.data && but->rnaprop) { - BLI_snprintf(r_str, maxlength, "%s.%s", RNA_struct_identifier(but->rnapoin.type), - RNA_property_identifier(but->rnaprop)); + BLI_snprintf( + r_str, maxlength, "%s.%s", RNA_struct_identifier(but->rnapoin.type), + RNA_property_identifier(but->rnaprop)); return true; } else if (but->optype) { diff --git a/source/blender/editors/interface/interface_widgets.c b/source/blender/editors/interface/interface_widgets.c index e3230d39ae28..a7de70629d10 100644 --- a/source/blender/editors/interface/interface_widgets.c +++ b/source/blender/editors/interface/interface_widgets.c @@ -358,13 +358,16 @@ static void round_box__edges(uiWidgetBase *wt, int roundboxalign, const rcti *re float facxi = (maxxi != minxi) ? 1.0f / (maxxi - minxi) : 0.0f; /* for uv, can divide by zero */ float facyi = (maxyi != minyi) ? 1.0f / (maxyi - minyi) : 0.0f; int a, tot = 0, minsize; - const int hnum = ((roundboxalign & (UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT)) == (UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT) || - (roundboxalign & (UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT)) == (UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT)) ? 1 : 2; - const int vnum = ((roundboxalign & (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT)) == (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT) || - (roundboxalign & (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) == (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) ? 1 : 2; + const int hnum = ( + (roundboxalign & (UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT)) == (UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT) || + (roundboxalign & (UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT)) == (UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT)) ? 1 : 2; + const int vnum = ( + (roundboxalign & (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT)) == (UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT) || + (roundboxalign & (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) == (UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT)) ? 1 : 2; - minsize = min_ii(BLI_rcti_size_x(rect) * hnum, - BLI_rcti_size_y(rect) * vnum); + minsize = min_ii( + BLI_rcti_size_x(rect) * hnum, + BLI_rcti_size_y(rect) * vnum); if (2.0f * rad > minsize) rad = 0.5f * minsize; @@ -769,10 +772,12 @@ static void widgetbase_draw(uiWidgetBase *wtb, uiWidgetColors *wcol) float triangle_strip[WIDGET_SIZE_MAX * 2 + 2][2]; /* + 2 because the last pair is wrapped */ float triangle_strip_emboss[WIDGET_SIZE_MAX * 2][2]; /* only for emboss */ - const unsigned char tcol[4] = {wcol->outline[0], - wcol->outline[1], - wcol->outline[2], - wcol->outline[3] / WIDGET_AA_JITTER}; + const unsigned char tcol[4] = { + wcol->outline[0], + wcol->outline[1], + wcol->outline[2], + wcol->outline[3] / WIDGET_AA_JITTER, + }; unsigned char emboss[4]; widget_verts_to_triangle_strip(wtb, wtb->totvert, triangle_strip); @@ -810,10 +815,12 @@ static void widgetbase_draw(uiWidgetBase *wtb, uiWidgetColors *wcol) /* decoration */ if (wtb->tria1.tot || wtb->tria2.tot) { - const unsigned char tcol[4] = {wcol->item[0], - wcol->item[1], - wcol->item[2], - (unsigned char)((float)wcol->item[3] / WIDGET_AA_JITTER)}; + const unsigned char tcol[4] = { + wcol->item[0], + wcol->item[1], + wcol->item[2], + (unsigned char)((float)wcol->item[3] / WIDGET_AA_JITTER), + }; glColor4ubv(tcol); /* for each AA step */ @@ -1033,8 +1040,8 @@ float UI_text_clip_middle_ex( strwidth = BLF_width(fstyle->uifont_id, str, max_len); if ((okwidth > 0.0f) && (strwidth > okwidth)) { - /* utf8 ellipsis '...', some compilers complain */ - const char sep[] = {0xe2, 0x80, 0xa6, 0x0}; + /* utf8 ellipsis '..', some compilers complain */ + const char sep[] = {0xe2, 0x80, 0xA5, 0x0}; const int sep_len = sizeof(sep) - 1; const float sep_strwidth = BLF_width(fstyle->uifont_id, sep, sep_len + 1); float parts_strwidth; @@ -1272,8 +1279,9 @@ static void ui_text_clip_right_label(uiFontStyle *fstyle, uiBut *but, const rcti /* once the label's gone, chop off the least significant digits */ if (but->strwidth > okwidth) { float strwidth; - drawstr_len = BLF_width_to_strlen(fstyle->uifont_id, but->drawstr + but->ofs, - drawstr_len - but->ofs, okwidth, &strwidth) + but->ofs; + drawstr_len = BLF_width_to_strlen( + fstyle->uifont_id, but->drawstr + but->ofs, + drawstr_len - but->ofs, okwidth, &strwidth) + but->ofs; but->strwidth = strwidth; but->drawstr[drawstr_len] = 0; } @@ -1299,8 +1307,9 @@ static void widget_draw_text_ime_underline( ofs_x = 0; } - width = BLF_width(fstyle->uifont_id, drawstr + but->ofs, - ime_data->composite_len + but->pos - but->ofs); + width = BLF_width( + fstyle->uifont_id, drawstr + but->ofs, + ime_data->composite_len + but->pos - but->ofs); glColor4ubv((unsigned char *)wcol->text); UI_draw_text_underline(rect->xmin + ofs_x, rect->ymin + 6 * U.pixelsize, min_ii(width, rect_x - 2) - ofs_x, 1); @@ -1317,8 +1326,9 @@ static void widget_draw_text_ime_underline( ofs_x = 0; } - width = BLF_width(fstyle->uifont_id, drawstr + but->ofs, - sel_end + sel_start - but->ofs); + width = BLF_width( + fstyle->uifont_id, drawstr + but->ofs, + sel_end + sel_start - but->ofs); UI_draw_text_underline(rect->xmin + ofs_x, rect->ymin + 6 * U.pixelsize, min_ii(width, rect_x - 2) - ofs_x, 2); } @@ -1371,9 +1381,10 @@ static void widget_draw_text(uiFontStyle *fstyle, uiWidgetColors *wcol, uiBut *b if (ime_data && ime_data->composite_len) { /* insert composite string into cursor pos */ - BLI_snprintf((char *)drawstr, UI_MAX_DRAW_STR, "%s%s%s", - but->editstr, ime_data->str_composite, - but->editstr + but->pos); + BLI_snprintf( + (char *)drawstr, UI_MAX_DRAW_STR, "%s%s%s", + but->editstr, ime_data->str_composite, + but->editstr + but->pos); } else #endif @@ -1504,8 +1515,9 @@ static void widget_draw_text(uiFontStyle *fstyle, uiWidgetColors *wcol, uiBut *b /* for underline drawing */ float font_xofs, font_yofs; - UI_fontstyle_draw_ex(fstyle, rect, drawstr + but->ofs, - drawstr_left_len - but->ofs, &font_xofs, &font_yofs); + UI_fontstyle_draw_ex( + fstyle, rect, drawstr + but->ofs, + drawstr_left_len - but->ofs, &font_xofs, &font_yofs); if (but->menu_key != '\0') { char fixedbuf[128]; @@ -2275,8 +2287,9 @@ static void ui_hsv_cursor(float x, float y) glPopMatrix(); } -void ui_hsvcircle_vals_from_pos(float *val_rad, float *val_dist, const rcti *rect, - const float mx, const float my) +void ui_hsvcircle_vals_from_pos( + float *val_rad, float *val_dist, const rcti *rect, + const float mx, const float my) { /* duplication of code... well, simple is better now */ const float centx = BLI_rcti_cent_x_fl(rect); @@ -2305,7 +2318,7 @@ void ui_hsvcircle_pos_from_vals(uiBut *but, const rcti *rect, float *hsv, float else radius_t = hsv[1]; - radius = CLAMPIS(radius_t, 0.0f, 1.0f) * radius; + radius = clamp_f(radius_t, 0.0f, 1.0f) * radius; *xpos = centx + cosf(-ang) * radius; *ypos = centy + sinf(-ang) * radius; } diff --git a/source/blender/editors/interface/resources.c b/source/blender/editors/interface/resources.c index 4864133c9059..77c36bf47f38 100644 --- a/source/blender/editors/interface/resources.c +++ b/source/blender/editors/interface/resources.c @@ -2325,10 +2325,6 @@ void init_userdef_do_versions(Main *bmain) if (U.dbl_click_time == 0) { U.dbl_click_time = 350; } - if (U.scrcastfps == 0) { - U.scrcastfps = 10; - U.scrcastwait = 50; - } if (U.v2d_min_gridsize == 0) { U.v2d_min_gridsize = 35; } @@ -2758,7 +2754,7 @@ void init_userdef_do_versions(Main *bmain) U.flag &= ~( USER_FLAG_DEPRECATED_1 | USER_FLAG_DEPRECATED_2 | USER_FLAG_DEPRECATED_3 | USER_FLAG_DEPRECATED_6 | USER_FLAG_DEPRECATED_7 | - USER_FLAG_DEPRECATED_9 | USER_FLAG_DEPRECATED_10); + USER_FLAG_DEPRECATED_9 | USER_DEVELOPER_UI); U.uiflag &= ~( USER_UIFLAG_DEPRECATED_7); U.transopts &= ~( @@ -2792,11 +2788,7 @@ void init_userdef_do_versions(Main *bmain) /* Not versioning, just avoid errors. */ #ifndef WITH_CYCLES - bAddon *addon = BLI_findstring(&U.addons, "cycles", offsetof(bAddon, module)); - if (addon) { - BLI_remlink(&U.addons, addon); - BKE_addon_free(addon); - } + BKE_addon_remove_safe(&U.addons, "cycles"); #endif /* funny name, but it is GE stuff, moves userdef stuff to engine */ diff --git a/source/blender/editors/interface/view2d.c b/source/blender/editors/interface/view2d.c index eb7b8968bee3..299001d4e451 100644 --- a/source/blender/editors/interface/view2d.c +++ b/source/blender/editors/interface/view2d.c @@ -1638,9 +1638,10 @@ View2DScrollers *UI_view2d_scrollers_calc( scrollers->yclamp = yclamp; scrollers->yunits = yunits; - scrollers->grid = UI_view2d_grid_calc(CTX_data_scene(C), v2d, - xunits, xclamp, yunits, yclamp, - BLI_rcti_size_x(&hor), BLI_rcti_size_y(&vert)); + scrollers->grid = UI_view2d_grid_calc( + CTX_data_scene(C), v2d, + xunits, xclamp, yunits, yclamp, + BLI_rcti_size_x(&hor), BLI_rcti_size_y(&vert)); } /* return scrollers */ @@ -2008,12 +2009,14 @@ void UI_view2d_listview_visible_cells( /* using 'cur' rect coordinates, call the cell-getting function to get the cells for this */ if (v2d) { /* min */ - UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, - v2d->cur.xmin, v2d->cur.ymin, column_min, row_min); + UI_view2d_listview_view_to_cell( + v2d, columnwidth, rowheight, startx, starty, + v2d->cur.xmin, v2d->cur.ymin, column_min, row_min); /* max*/ - UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, - v2d->cur.xmax, v2d->cur.ymax, column_max, row_max); + UI_view2d_listview_view_to_cell( + v2d, columnwidth, rowheight, startx, starty, + v2d->cur.xmax, v2d->cur.ymax, column_max, row_max); } } @@ -2423,13 +2426,15 @@ void UI_view2d_text_cache_draw(ARegion *ar) } if (v2s->rect.xmin >= v2s->rect.xmax) - BLF_draw_default((float)(v2s->mval[0] + xofs), (float)(v2s->mval[1] + yofs), 0.0, - v2s->str, BLF_DRAW_STR_DUMMY_MAX); + BLF_draw_default( + (float)(v2s->mval[0] + xofs), (float)(v2s->mval[1] + yofs), 0.0, + v2s->str, BLF_DRAW_STR_DUMMY_MAX); else { BLF_clipping_default(v2s->rect.xmin - 4, v2s->rect.ymin - 4, v2s->rect.xmax + 4, v2s->rect.ymax + 4); BLF_enable_default(BLF_CLIPPING); - BLF_draw_default(v2s->rect.xmin + xofs, v2s->rect.ymin + yofs, 0.0f, - v2s->str, BLF_DRAW_STR_DUMMY_MAX); + BLF_draw_default( + v2s->rect.xmin + xofs, v2s->rect.ymin + yofs, 0.0f, + v2s->str, BLF_DRAW_STR_DUMMY_MAX); BLF_disable_default(BLF_CLIPPING); } } @@ -2448,5 +2453,3 @@ void UI_view2d_text_cache_draw(ARegion *ar) /* ******************************************************** */ - - diff --git a/source/blender/editors/interface/view2d_ops.c b/source/blender/editors/interface/view2d_ops.c index 35558bd5af1e..b9ea5d960573 100644 --- a/source/blender/editors/interface/view2d_ops.c +++ b/source/blender/editors/interface/view2d_ops.c @@ -53,7 +53,7 @@ #include "PIL_time.h" /* USER_ZOOM_CONT */ -static int view2d_poll(bContext *C) +static bool view2d_poll(bContext *C) { ARegion *ar = CTX_wm_region(C); @@ -128,7 +128,7 @@ static int view_pan_init(bContext *C, wmOperator *op) } #ifdef WITH_INPUT_NDOF -static int view_pan_poll(bContext *C) +static bool view_pan_poll(bContext *C) { ARegion *ar = CTX_wm_region(C); View2D *v2d; @@ -187,9 +187,10 @@ static void view_pan_apply(bContext *C, wmOperator *op) { v2dViewPanData *vpd = op->customdata; - view_pan_apply_ex(C, vpd, - RNA_int_get(op->ptr, "deltax"), - RNA_int_get(op->ptr, "deltay")); + view_pan_apply_ex( + C, vpd, + RNA_int_get(op->ptr, "deltax"), + RNA_int_get(op->ptr, "deltay")); } @@ -609,7 +610,7 @@ static int view_zoomdrag_init(bContext *C, wmOperator *op) } /* check if step-zoom can be applied */ -static int view_zoom_poll(bContext *C) +static bool view_zoom_poll(bContext *C) { ARegion *ar = CTX_wm_region(C); View2D *v2d; @@ -733,9 +734,10 @@ static void view_zoomstep_apply_ex( static void view_zoomstep_apply(bContext *C, wmOperator *op) { v2dViewZoomData *vzd = op->customdata; - view_zoomstep_apply_ex(C, vzd, true, - RNA_float_get(op->ptr, "zoomfacx"), - RNA_float_get(op->ptr, "zoomfacy")); + view_zoomstep_apply_ex( + C, vzd, true, + RNA_float_get(op->ptr, "zoomfacx"), + RNA_float_get(op->ptr, "zoomfacy")); } /* --------------- Individual Operators ------------------- */ @@ -788,9 +790,10 @@ static int view_zoomin_invoke(bContext *C, wmOperator *op, const wmEvent *event) ARegion *ar = CTX_wm_region(C); /* store initial mouse position (in view space) */ - UI_view2d_region_to_view(&ar->v2d, - event->mval[0], event->mval[1], - &vzd->mx_2d, &vzd->my_2d); + UI_view2d_region_to_view( + &ar->v2d, + event->mval[0], event->mval[1], + &vzd->mx_2d, &vzd->my_2d); } return view_zoomin_exec(C, op); @@ -853,9 +856,10 @@ static int view_zoomout_invoke(bContext *C, wmOperator *op, const wmEvent *event ARegion *ar = CTX_wm_region(C); /* store initial mouse position (in view space) */ - UI_view2d_region_to_view(&ar->v2d, - event->mval[0], event->mval[1], - &vzd->mx_2d, &vzd->my_2d); + UI_view2d_region_to_view( + &ar->v2d, + event->mval[0], event->mval[1], + &vzd->mx_2d, &vzd->my_2d); } return view_zoomout_exec(C, op); @@ -1056,9 +1060,10 @@ static int view_zoomdrag_invoke(bContext *C, wmOperator *op, const wmEvent *even ARegion *ar = CTX_wm_region(C); /* store initial mouse position (in view space) */ - UI_view2d_region_to_view(&ar->v2d, - event->mval[0], event->mval[1], - &vzd->mx_2d, &vzd->my_2d); + UI_view2d_region_to_view( + &ar->v2d, + event->mval[0], event->mval[1], + &vzd->mx_2d, &vzd->my_2d); } if (v2d->keepofs & V2D_LOCKOFS_X) @@ -1114,7 +1119,7 @@ static int view_zoomdrag_modal(bContext *C, wmOperator *op, const wmEvent *event /* some view2d's (graph) don't have min/max zoom, or extreme ones */ if (v2d->maxzoom > 0.0f) - zoomfac = CLAMPIS(0.001f * v2d->maxzoom, 0.001f, 0.01f); + zoomfac = clamp_f(0.001f * v2d->maxzoom, 0.001f, 0.01f); /* x-axis transform */ fac = zoomfac * (event->x - vzd->lastx); @@ -1345,9 +1350,10 @@ static int view2d_ndof_invoke(bContext *C, wmOperator *op, const wmEvent *event) vzd = op->customdata; - view_zoomstep_apply_ex(C, vzd, false, - do_zoom_xy[0] ? zoom_factor : 0.0f, - do_zoom_xy[1] ? zoom_factor : 0.0f); + view_zoomstep_apply_ex( + C, vzd, false, + do_zoom_xy[0] ? zoom_factor : 0.0f, + do_zoom_xy[1] ? zoom_factor : 0.0f); view_zoomstep_exit(op); } @@ -1392,14 +1398,18 @@ struct SmoothView2DStore { */ static float smooth_view_rect_to_fac(const rctf *rect_a, const rctf *rect_b) { - const float size_a[2] = {BLI_rctf_size_x(rect_a), - BLI_rctf_size_y(rect_a)}; - const float size_b[2] = {BLI_rctf_size_x(rect_b), - BLI_rctf_size_y(rect_b)}; - const float cent_a[2] = {BLI_rctf_cent_x(rect_a), - BLI_rctf_cent_y(rect_a)}; - const float cent_b[2] = {BLI_rctf_cent_x(rect_b), - BLI_rctf_cent_y(rect_b)}; + const float size_a[2] = { + BLI_rctf_size_x(rect_a), + BLI_rctf_size_y(rect_a)}; + const float size_b[2] = { + BLI_rctf_size_x(rect_b), + BLI_rctf_size_y(rect_b)}; + const float cent_a[2] = { + BLI_rctf_cent_x(rect_a), + BLI_rctf_cent_y(rect_a)}; + const float cent_b[2] = { + BLI_rctf_cent_x(rect_b), + BLI_rctf_cent_y(rect_b)}; float fac_max = 0.0f; float tfac; @@ -1699,9 +1709,10 @@ static void scroller_activate_init(bContext *C, wmOperator *op, const wmEvent *e vsm->fac_round = (BLI_rctf_size_x(&v2d->cur)) / (float)(BLI_rcti_size_x(&ar->winrct) + 1); /* get 'zone' (i.e. which part of scroller is activated) */ - vsm->zone = mouse_in_scroller_handle(event->mval[0], - v2d->hor.xmin, v2d->hor.xmax, - scrollers->hor_min, scrollers->hor_max); + vsm->zone = mouse_in_scroller_handle( + event->mval[0], + v2d->hor.xmin, v2d->hor.xmax, + scrollers->hor_min, scrollers->hor_max); if ((v2d->keepzoom & V2D_LOCKZOOM_X) && ELEM(vsm->zone, SCROLLHANDLE_MIN, SCROLLHANDLE_MAX)) { /* default to scroll, as handles not usable */ @@ -1720,9 +1731,10 @@ static void scroller_activate_init(bContext *C, wmOperator *op, const wmEvent *e vsm->fac_round = (BLI_rctf_size_y(&v2d->cur)) / (float)(BLI_rcti_size_y(&ar->winrct) + 1); /* get 'zone' (i.e. which part of scroller is activated) */ - vsm->zone = mouse_in_scroller_handle(event->mval[1], - v2d->vert.ymin, v2d->vert.ymax, - scrollers->vert_min, scrollers->vert_max); + vsm->zone = mouse_in_scroller_handle( + event->mval[1], + v2d->vert.ymin, v2d->vert.ymax, + scrollers->vert_min, scrollers->vert_max); if ((v2d->keepzoom & V2D_LOCKZOOM_Y) && ELEM(vsm->zone, SCROLLHANDLE_MIN, SCROLLHANDLE_MAX)) { /* default to scroll, as handles not usable */ @@ -2086,7 +2098,7 @@ void ED_operatortypes_view2d(void) void ED_keymap_view2d(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "View2D", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "View2D", 0, 0); wmKeyMapItem *kmi; /* scrollers */ @@ -2146,7 +2158,7 @@ void ED_keymap_view2d(wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "VIEW2D_OT_zoom_border", BKEY, KM_PRESS, KM_SHIFT, 0); /* Alternative keymap for buttons listview */ - keymap = WM_keymap_find(keyconf, "View2D Buttons List", 0, 0); + keymap = WM_keymap_ensure(keyconf, "View2D Buttons List", 0, 0); WM_keymap_add_item(keymap, "VIEW2D_OT_scroller_activate", LEFTMOUSE, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "VIEW2D_OT_scroller_activate", MIDDLEMOUSE, KM_PRESS, 0, 0); @@ -2168,4 +2180,3 @@ void ED_keymap_view2d(wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "VIEW2D_OT_zoom_in", PADPLUSKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "VIEW2D_OT_reset", HOMEKEY, KM_PRESS, 0, 0); } - diff --git a/source/blender/editors/io/io_alembic.c b/source/blender/editors/io/io_alembic.c index 671857443d2f..9131243b9265 100644 --- a/source/blender/editors/io/io_alembic.c +++ b/source/blender/editors/io/io_alembic.c @@ -86,7 +86,7 @@ static int wm_alembic_export_invoke(bContext *C, wmOperator *op, const wmEvent * BLI_strncpy(filepath, BKE_main_blendfile_path(bmain), sizeof(filepath)); } - BLI_replace_extension(filepath, sizeof(filepath), ".abc"); + BLI_path_extension_replace(filepath, sizeof(filepath), ".abc"); RNA_string_set(op->ptr, "filepath", filepath); } @@ -284,8 +284,8 @@ static bool wm_alembic_export_check(bContext *UNUSED(C), wmOperator *op) char filepath[FILE_MAX]; RNA_string_get(op->ptr, "filepath", filepath); - if (!BLI_testextensie(filepath, ".abc")) { - BLI_ensure_extension(filepath, FILE_MAX, ".abc"); + if (!BLI_path_extension_check(filepath, ".abc")) { + BLI_path_extension_ensure(filepath, FILE_MAX, ".abc"); RNA_string_set(op->ptr, "filepath", filepath); return true; } diff --git a/source/blender/editors/io/io_cache.c b/source/blender/editors/io/io_cache.c index b13eaced843a..221142a6cf8e 100644 --- a/source/blender/editors/io/io_cache.c +++ b/source/blender/editors/io/io_cache.c @@ -61,7 +61,7 @@ static int cachefile_open_invoke(bContext *C, wmOperator *op, const wmEvent *eve Main *bmain = CTX_data_main(C); BLI_strncpy(filepath, BKE_main_blendfile_path(bmain), sizeof(filepath)); - BLI_replace_extension(filepath, sizeof(filepath), ".abc"); + BLI_path_extension_replace(filepath, sizeof(filepath), ".abc"); RNA_string_set(op->ptr, "filepath", filepath); } diff --git a/source/blender/editors/io/io_collada.c b/source/blender/editors/io/io_collada.c index 30323d421de5..76ddd221ea40 100644 --- a/source/blender/editors/io/io_collada.c +++ b/source/blender/editors/io/io_collada.c @@ -71,7 +71,7 @@ static int wm_collada_export_invoke(bContext *C, wmOperator *op, const wmEvent * else BLI_strncpy(filepath, blendfile_path, sizeof(filepath)); - BLI_replace_extension(filepath, sizeof(filepath), ".dae"); + BLI_path_extension_replace(filepath, sizeof(filepath), ".dae"); RNA_string_set(op->ptr, "filepath", filepath); } @@ -118,7 +118,7 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op) } RNA_string_get(op->ptr, "filepath", filepath); - BLI_ensure_extension(filepath, sizeof(filepath), ".dae"); + BLI_path_extension_ensure(filepath, sizeof(filepath), ".dae"); /* Avoid File write exceptions in Collada */ @@ -336,8 +336,8 @@ static bool wm_collada_export_check(bContext *UNUSED(C), wmOperator *op) char filepath[FILE_MAX]; RNA_string_get(op->ptr, "filepath", filepath); - if (!BLI_testextensie(filepath, ".dae")) { - BLI_ensure_extension(filepath, FILE_MAX, ".dae"); + if (!BLI_path_extension_check(filepath, ".dae")) { + BLI_path_extension_ensure(filepath, FILE_MAX, ".dae"); RNA_string_set(op->ptr, "filepath", filepath); return true; } diff --git a/source/blender/editors/lattice/editlattice_tools.c b/source/blender/editors/lattice/editlattice_tools.c index c39ba44c1dcb..8ecb182528af 100644 --- a/source/blender/editors/lattice/editlattice_tools.c +++ b/source/blender/editors/lattice/editlattice_tools.c @@ -55,7 +55,7 @@ /** \name Make Regular Operator * \{ */ -static int make_regular_poll(bContext *C) +static bool make_regular_poll(bContext *C) { Object *ob; diff --git a/source/blender/editors/lattice/lattice_ops.c b/source/blender/editors/lattice/lattice_ops.c index 4f2e87c11c14..561397d71ffe 100644 --- a/source/blender/editors/lattice/lattice_ops.c +++ b/source/blender/editors/lattice/lattice_ops.c @@ -58,7 +58,7 @@ void ED_keymap_lattice(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "Lattice", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Lattice", 0, 0); keymap->poll = ED_operator_editlattice; kmi = WM_keymap_add_item(keymap, "LATTICE_OT_select_all", AKEY, KM_PRESS, 0, 0); diff --git a/source/blender/editors/mask/mask_edit.c b/source/blender/editors/mask/mask_edit.c index 9a2635c37d29..540101ba401c 100644 --- a/source/blender/editors/mask/mask_edit.c +++ b/source/blender/editors/mask/mask_edit.c @@ -57,7 +57,7 @@ /********************** generic poll functions *********************/ -int ED_maskedit_poll(bContext *C) +bool ED_maskedit_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); if (sa) { @@ -73,7 +73,7 @@ int ED_maskedit_poll(bContext *C) return false; } -int ED_maskedit_mask_poll(bContext *C) +bool ED_maskedit_mask_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); if (sa) { @@ -525,7 +525,7 @@ void ED_keymap_mask(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "Mask Editing", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Mask Editing", 0, 0); keymap->poll = ED_maskedit_poll; WM_keymap_add_item(keymap, "MASK_OT_new", NKEY, KM_PRESS, KM_ALT, 0); diff --git a/source/blender/editors/mask/mask_editaction.c b/source/blender/editors/mask/mask_editaction.c index 364800ed1a2e..771deca69b60 100644 --- a/source/blender/editors/mask/mask_editaction.c +++ b/source/blender/editors/mask/mask_editaction.c @@ -336,4 +336,3 @@ void ED_masklayer_snap_frames(MaskLayer *masklay, Scene *scene, short mode) break; } } - diff --git a/source/blender/editors/mask/mask_intern.h b/source/blender/editors/mask/mask_intern.h index 66a6c75272e1..e9ef06a368f5 100644 --- a/source/blender/editors/mask/mask_intern.h +++ b/source/blender/editors/mask/mask_intern.h @@ -121,8 +121,8 @@ void ED_mask_select_toggle_all(struct Mask *mask, int action); void ED_mask_select_flush_all(struct Mask *mask); /* mask_editor.c */ -int ED_maskedit_poll(struct bContext *C); -int ED_maskedit_mask_poll(struct bContext *C); +bool ED_maskedit_poll(struct bContext *C); +bool ED_maskedit_mask_poll(struct bContext *C); /* mask_shapekey.c */ void MASK_OT_shape_key_insert(struct wmOperatorType *ot); diff --git a/source/blender/editors/mask/mask_ops.c b/source/blender/editors/mask/mask_ops.c index 97d5ee1eff0d..cf67a9715a8b 100644 --- a/source/blender/editors/mask/mask_ops.c +++ b/source/blender/editors/mask/mask_ops.c @@ -2105,7 +2105,7 @@ void MASK_OT_feather_weight_clear(wmOperatorType *ot) /******************** move mask layer operator *********************/ -static int mask_layer_move_poll(bContext *C) +static bool mask_layer_move_poll(bContext *C) { if (ED_maskedit_mask_poll(C)) { Mask *mask = CTX_data_edit_mask(C); @@ -2334,7 +2334,7 @@ void MASK_OT_copy_splines(wmOperatorType *ot) /********************** paste tracks from clipboard operator *********************/ -static int paste_splines_poll(bContext *C) +static bool paste_splines_poll(bContext *C) { if (ED_maskedit_mask_poll(C)) { return BKE_mask_clipboard_is_empty() == false; diff --git a/source/blender/editors/mesh/editface.c b/source/blender/editors/mesh/editface.c index 899f19242220..d497a073f778 100644 --- a/source/blender/editors/mesh/editface.c +++ b/source/blender/editors/mesh/editface.c @@ -414,12 +414,6 @@ int do_paintface_box_select(ViewContext *vc, rcti *rect, bool select, bool exten if (extend == false && select) { paintface_deselect_all_visible(vc->obact, SEL_DESELECT, false); - - mpoly = me->mpoly; - for (a = 1; a <= me->totpoly; a++, mpoly++) { - if ((mpoly->flag & ME_HIDE) == 0) - mpoly->flag &= ~ME_FACE_SEL; - } } ED_view3d_backbuf_validate(vc); diff --git a/source/blender/editors/mesh/editmesh_bevel.c b/source/blender/editors/mesh/editmesh_bevel.c index bf349a4c6787..e44a43c4c3a9 100644 --- a/source/blender/editors/mesh/editmesh_bevel.c +++ b/source/blender/editors/mesh/editmesh_bevel.c @@ -624,7 +624,7 @@ void MESH_OT_bevel(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_CURSOR | OPTYPE_BLOCKING; RNA_def_enum(ot->srna, "offset_type", offset_type_items, 0, "Amount Type", "What distance Amount measures"); - prop = RNA_def_float(ot->srna, "offset", 0.0f, -1e6f, 1e6f, "Amount", "", 0.0f, 1.0f); + prop = RNA_def_float(ot->srna, "offset", 0.0f, -1e6f, 1e6f, "Amount", "", 0.0f, 100.0f); RNA_def_property_float_array_funcs_runtime(prop, NULL, NULL, mesh_ot_bevel_offset_range_func); RNA_def_int(ot->srna, "segments", 1, 1, SEGMENTS_HARD_MAX, "Segments", "Segments for curved edge", 1, 8); RNA_def_float(ot->srna, "profile", 0.5f, PROFILE_HARD_MIN, 1.0f, "Profile", diff --git a/source/blender/editors/mesh/editmesh_bisect.c b/source/blender/editors/mesh/editmesh_bisect.c index 3a9e278f0395..783fe9316707 100644 --- a/source/blender/editors/mesh/editmesh_bisect.c +++ b/source/blender/editors/mesh/editmesh_bisect.c @@ -347,7 +347,8 @@ void MESH_OT_bisect(struct wmOperatorType *ot) RNA_def_boolean(ot->srna, "clear_inner", false, "Clear Inner", "Remove geometry behind the plane"); RNA_def_boolean(ot->srna, "clear_outer", false, "Clear Outer", "Remove geometry in front of the plane"); - RNA_def_float(ot->srna, "threshold", 0.0001, 0.0, 10.0, "Axis Threshold", "", 0.00001, 0.1); + RNA_def_float(ot->srna, "threshold", 0.0001, 0.0, 10.0, "Axis Threshold", + "Preserves the existing geometry along the cut plane", 0.00001, 0.1); WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT); } diff --git a/source/blender/editors/mesh/editmesh_extrude.c b/source/blender/editors/mesh/editmesh_extrude.c index 9467c545bbf2..7ea89c564323 100644 --- a/source/blender/editors/mesh/editmesh_extrude.c +++ b/source/blender/editors/mesh/editmesh_extrude.c @@ -661,7 +661,7 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const w /* also project the source, for retopo workflow */ if (use_proj) - EMBM_project_snap_verts(C, vc.ar, vc.em); + EDBM_project_snap_verts(C, vc.ar, vc.em); } edbm_extrude_ex(vc.obedit, vc.em, extrude_htype, BM_ELEM_SELECT, true, true); @@ -693,7 +693,7 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const w } if (use_proj) - EMBM_project_snap_verts(C, vc.ar, vc.em); + EDBM_project_snap_verts(C, vc.ar, vc.em); /* This normally happens when pushing undo but modal operators * like this one don't push undo data until after modal mode is @@ -723,4 +723,3 @@ void MESH_OT_dupli_extrude_cursor(wmOperatorType *ot) } /** \} */ - diff --git a/source/blender/editors/mesh/editmesh_extrude_screw.c b/source/blender/editors/mesh/editmesh_extrude_screw.c index ffbbae609499..de9f714dfe8e 100644 --- a/source/blender/editors/mesh/editmesh_extrude_screw.c +++ b/source/blender/editors/mesh/editmesh_extrude_screw.c @@ -25,7 +25,7 @@ * ***** END GPL LICENSE BLOCK ***** */ -/** \file blender/editors/mesh/editmesh_extrude_spin.c +/** \file blender/editors/mesh/editmesh_extrude_screw.c * \ingroup edmesh */ diff --git a/source/blender/editors/mesh/editmesh_extrude_spin.c b/source/blender/editors/mesh/editmesh_extrude_spin.c index 4cd3b033ca76..5f1670bf57d0 100644 --- a/source/blender/editors/mesh/editmesh_extrude_spin.c +++ b/source/blender/editors/mesh/editmesh_extrude_spin.c @@ -149,4 +149,3 @@ void MESH_OT_spin(wmOperatorType *ot) } /** \} */ - diff --git a/source/blender/editors/mesh/editmesh_loopcut.c b/source/blender/editors/mesh/editmesh_loopcut.c index f07073cd3d79..34951a24805a 100644 --- a/source/blender/editors/mesh/editmesh_loopcut.c +++ b/source/blender/editors/mesh/editmesh_loopcut.c @@ -594,7 +594,7 @@ static int loopcut_init(bContext *C, wmOperator *op, const wmEvent *event) { Scene *scene = CTX_data_scene(C); ToolSettings *settings = scene->toolsettings; - const int mesh_select_mode[3] = { + const bool mesh_select_mode[3] = { (settings->selectmode & SCE_SELECT_VERTEX) != 0, (settings->selectmode & SCE_SELECT_EDGE) != 0, (settings->selectmode & SCE_SELECT_FACE) != 0, @@ -771,7 +771,7 @@ static int loopcut_modal(bContext *C, wmOperator *op, const wmEvent *event) if (cuts != lcd->cuts) { /* allow zero so you can backspace and type in a value * otherwise 1 as minimum would make more sense */ - lcd->cuts = CLAMPIS(cuts, 0, SUBD_CUTS_MAX); + lcd->cuts = clamp_i(cuts, 0, SUBD_CUTS_MAX); RNA_int_set(op->ptr, "number_cuts", (int)lcd->cuts); ringsel_find_edge(lcd, (int)lcd->cuts); show_cuts = true; @@ -779,7 +779,7 @@ static int loopcut_modal(bContext *C, wmOperator *op, const wmEvent *event) } if (smoothness != lcd->smoothness) { - lcd->smoothness = CLAMPIS(smoothness, -SUBD_SMOOTH_MAX, SUBD_SMOOTH_MAX); + lcd->smoothness = clamp_f(smoothness, -SUBD_SMOOTH_MAX, SUBD_SMOOTH_MAX); RNA_float_set(op->ptr, "smoothness", lcd->smoothness); show_cuts = true; ED_region_tag_redraw(lcd->ar); diff --git a/source/blender/editors/mesh/editmesh_path.c b/source/blender/editors/mesh/editmesh_path.c index bf5a7e3a053c..eccc15bf83fa 100644 --- a/source/blender/editors/mesh/editmesh_path.c +++ b/source/blender/editors/mesh/editmesh_path.c @@ -176,7 +176,8 @@ static void mouse_mesh_shortest_path_vert( } } while ((node = node->next)); - int depth = 1; + /* We need to start as if just *after* a 'skip' block... */ + int depth = op_params->interval_params.skip; node = path; do { if ((is_path_ordered == false) || @@ -366,7 +367,8 @@ static void mouse_mesh_shortest_path_edge( } } while ((node = node->next)); - int depth = 1; + /* We need to start as if just *after* a 'skip' block... */ + int depth = op_params->interval_params.skip; node = path; do { if ((is_path_ordered == false) || @@ -511,7 +513,8 @@ static void mouse_mesh_shortest_path_face( } } while ((node = node->next)); - int depth = 1; + /* We need to start as if just *after* a 'skip' block... */ + int depth = op_params->interval_params.skip; node = path; do { if ((is_path_ordered == false) || diff --git a/source/blender/editors/mesh/editmesh_select.c b/source/blender/editors/mesh/editmesh_select.c index 019aa6d42015..968c276c8bd5 100644 --- a/source/blender/editors/mesh/editmesh_select.c +++ b/source/blender/editors/mesh/editmesh_select.c @@ -3833,7 +3833,7 @@ void MESH_OT_select_random(wmOperatorType *ot) /** \name Select Ungrouped Operator * \{ */ -static int edbm_select_ungrouped_poll(bContext *C) +static bool edbm_select_ungrouped_poll(bContext *C) { if (ED_operator_editmesh(C)) { Object *obedit = CTX_data_edit_object(C); diff --git a/source/blender/editors/mesh/editmesh_tools.c b/source/blender/editors/mesh/editmesh_tools.c index 70c4f341bd8b..313dd28e806e 100644 --- a/source/blender/editors/mesh/editmesh_tools.c +++ b/source/blender/editors/mesh/editmesh_tools.c @@ -312,7 +312,7 @@ void MESH_OT_unsubdivide(wmOperatorType *ot) RNA_def_int(ot->srna, "iterations", 2, 1, 1000, "Iterations", "Number of times to unsubdivide", 1, 100); } -void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em) +void EDBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em) { Object *obedit = em->ob; BMIter iter; @@ -3888,11 +3888,13 @@ void MESH_OT_fill_grid(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ - prop = RNA_def_int(ot->srna, "span", 1, 1, 1000, "Span", "Number of sides (zero disables)", 1, 100); + prop = RNA_def_int(ot->srna, "span", 1, 1, 1000, "Span", "Number of grid columns", 1, 100); RNA_def_property_flag(prop, PROP_SKIP_SAVE); - prop = RNA_def_int(ot->srna, "offset", 0, -1000, 1000, "Offset", "Number of sides (zero disables)", -100, 100); + prop = RNA_def_int(ot->srna, "offset", 0, -1000, 1000, "Offset", + "Vertex that is the corner of the grid", -100, 100); RNA_def_property_flag(prop, PROP_SKIP_SAVE); - RNA_def_boolean(ot->srna, "use_interp_simple", false, "Simple Blending", ""); + RNA_def_boolean(ot->srna, "use_interp_simple", false, "Simple Blending", + "Use simple interpolation of grid vertices"); } /** \} */ @@ -5371,10 +5373,10 @@ static int edbm_sort_elements_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static bool edbm_sort_elements_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) +static bool edbm_sort_elements_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop) { const char *prop_id = RNA_property_identifier(prop); - const int action = RNA_enum_get(ptr, "type"); + const int action = RNA_enum_get(op->ptr, "type"); /* Only show seed for randomize action! */ if (STREQ(prop_id, "seed")) { @@ -5395,18 +5397,6 @@ static bool edbm_sort_elements_draw_check_prop(PointerRNA *ptr, PropertyRNA *pro return true; } -static void edbm_sort_elements_ui(bContext *C, wmOperator *op) -{ - uiLayout *layout = op->layout; - wmWindowManager *wm = CTX_wm_manager(C); - PointerRNA ptr; - - RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); - - /* Main auto-draw call. */ - uiDefAutoButsRNA(layout, &ptr, edbm_sort_elements_draw_check_prop, '\0'); -} - void MESH_OT_sort_elements(wmOperatorType *ot) { static const EnumPropertyItem type_items[] = { @@ -5442,7 +5432,7 @@ void MESH_OT_sort_elements(wmOperatorType *ot) ot->invoke = WM_menu_invoke; ot->exec = edbm_sort_elements_exec; ot->poll = ED_operator_editmesh; - ot->ui = edbm_sort_elements_ui; + ot->poll_property = edbm_sort_elements_poll_property; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; @@ -6019,7 +6009,8 @@ void MESH_OT_symmetrize(struct wmOperatorType *ot) ot->srna, "direction", rna_enum_symmetrize_direction_items, BMO_SYMMETRIZE_NEGATIVE_X, "Direction", "Which sides to copy from and to"); - RNA_def_float(ot->srna, "threshold", 1e-4f, 0.0f, 10.0f, "Threshold", "", 1e-5f, 0.1f); + RNA_def_float(ot->srna, "threshold", 1e-4f, 0.0f, 10.0f, "Threshold", + "Limit for snap middle vertices to the axis center", 1e-5f, 0.1f); } /** \} */ @@ -6150,9 +6141,11 @@ void MESH_OT_symmetry_snap(struct wmOperatorType *ot) ot->srna, "direction", rna_enum_symmetrize_direction_items, BMO_SYMMETRIZE_NEGATIVE_X, "Direction", "Which sides to copy from and to"); - RNA_def_float_distance(ot->srna, "threshold", 0.05f, 0.0f, 10.0f, "Threshold", "", 1e-4f, 1.0f); - RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0f, "Factor", "", 0.0f, 1.0f); - RNA_def_boolean(ot->srna, "use_center", true, "Center", "Snap mid verts to the axis center"); + RNA_def_float_distance(ot->srna, "threshold", 0.05f, 0.0f, 10.0f, "Threshold", + "Distance within which matching vertices are searched", 1e-4f, 1.0f); + RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0f, "Factor", + "Mix factor of the locations of the vertices", 0.0f, 1.0f); + RNA_def_boolean(ot->srna, "use_center", true, "Center", "Snap middle vertices to the axis center"); } /** \} */ diff --git a/source/blender/editors/mesh/editmesh_utils.c b/source/blender/editors/mesh/editmesh_utils.c index 4500aeda70a1..7a344be8e5a1 100644 --- a/source/blender/editors/mesh/editmesh_utils.c +++ b/source/blender/editors/mesh/editmesh_utils.c @@ -561,8 +561,8 @@ UvVertMap *BM_uv_vert_map_create( } BM_ITER_ELEM_INDEX(l, &liter, efa, BM_LOOPS_OF_FACE, i) { - buf->tfindex = i; - buf->f = a; + buf->loop_of_poly_index = i; + buf->poly_index = a; buf->separate = 0; buf->next = vmap->vert[BM_elem_index_get(l->v)]; @@ -593,10 +593,10 @@ UvVertMap *BM_uv_vert_map_create( v->next = newvlist; newvlist = v; - efa = BM_face_at_index(bm, v->f); + efa = BM_face_at_index(bm, v->poly_index); /* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */ - l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, v->tfindex); + l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, v->loop_of_poly_index); luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset); uv = luv->uv; @@ -605,17 +605,17 @@ UvVertMap *BM_uv_vert_map_create( while (iterv) { next = iterv->next; - efa = BM_face_at_index(bm, iterv->f); + efa = BM_face_at_index(bm, iterv->poly_index); /* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */ - l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, iterv->tfindex); + l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, iterv->loop_of_poly_index); luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset); uv2 = luv->uv; sub_v2_v2v2(uvdiff, uv2, uv); if (fabsf(uvdiff[0]) < limit[0] && fabsf(uvdiff[1]) < limit[1] && - (!use_winding || winding[iterv->f] == winding[v->f])) + (!use_winding || winding[iterv->poly_index] == winding[v->poly_index])) { if (lastv) lastv->next = next; else vlist = next; @@ -712,7 +712,7 @@ UvElementMap *BM_uv_element_map_create( buf->l = l; buf->separate = 0; buf->island = INVALID_ISLAND; - buf->tfindex = i; + buf->loop_of_poly_index = i; buf->next = element_map->vert[BM_elem_index_get(l->v)]; element_map->vert[BM_elem_index_get(l->v)] = buf; @@ -825,7 +825,7 @@ UvElementMap *BM_uv_element_map_create( map[element - element_map->buf] = islandbufsize; islandbuf[islandbufsize].l = element->l; islandbuf[islandbufsize].separate = element->separate; - islandbuf[islandbufsize].tfindex = element->tfindex; + islandbuf[islandbufsize].loop_of_poly_index = element->loop_of_poly_index; islandbuf[islandbufsize].island = nislands; islandbufsize++; @@ -1384,7 +1384,7 @@ DerivedMesh *EDBM_mesh_deform_dm_get(BMEditMesh *em) * \{ */ /* poll call for mesh operators requiring a view3d context */ -int EDBM_view3d_poll(bContext *C) +bool EDBM_view3d_poll(bContext *C) { if (ED_operator_editmesh(C) && ED_operator_view3d_active(C)) { return 1; diff --git a/source/blender/editors/mesh/mesh_data.c b/source/blender/editors/mesh/mesh_data.c index fc74397010cc..37d3eb22e193 100644 --- a/source/blender/editors/mesh/mesh_data.c +++ b/source/blender/editors/mesh/mesh_data.c @@ -521,7 +521,7 @@ bool ED_mesh_color_remove_named(Mesh *me, const char *name) /*********************** UV texture operators ************************/ -static int layers_poll(bContext *C) +static bool layers_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -762,7 +762,7 @@ static int mesh_customdata_clear_exec__internal(bContext *C, } /* Clear Mask */ -static int mesh_customdata_mask_clear_poll(bContext *C) +static bool mesh_customdata_mask_clear_poll(bContext *C) { Object *ob = ED_object_context(C); if (ob && ob->type == OB_MESH) { @@ -835,7 +835,7 @@ static int mesh_customdata_skin_state(bContext *C) return -1; } -static int mesh_customdata_skin_add_poll(bContext *C) +static bool mesh_customdata_skin_add_poll(bContext *C) { return (mesh_customdata_skin_state(C) == 0); } @@ -868,7 +868,7 @@ void MESH_OT_customdata_skin_add(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } -static int mesh_customdata_skin_clear_poll(bContext *C) +static bool mesh_customdata_skin_clear_poll(bContext *C) { return (mesh_customdata_skin_state(C) == 1); } @@ -989,7 +989,7 @@ void MESH_OT_customdata_custom_splitnormals_clear(wmOperatorType *ot) /************************** Add Geometry Layers *************************/ -void ED_mesh_update(Mesh *mesh, bContext *C, int calc_edges, int calc_tessface) +void ED_mesh_update(Mesh *mesh, bContext *C, bool calc_edges, bool calc_tessface) { bool tessface_input = false; diff --git a/source/blender/editors/mesh/mesh_intern.h b/source/blender/editors/mesh/mesh_intern.h index 74da7405d056..593e6b59d85e 100644 --- a/source/blender/editors/mesh/mesh_intern.h +++ b/source/blender/editors/mesh/mesh_intern.h @@ -73,7 +73,7 @@ bool EDBM_op_finish(struct BMEditMesh *em, struct BMOperator *bmop, void EDBM_stats_update(struct BMEditMesh *em); -int EDBM_view3d_poll(struct bContext *C); +bool EDBM_view3d_poll(struct bContext *C); struct BMElem *EDBM_elem_from_selectmode( struct BMEditMesh *em, diff --git a/source/blender/editors/mesh/mesh_navmesh.c b/source/blender/editors/mesh/mesh_navmesh.c index 4aca37988664..37e299d3d966 100644 --- a/source/blender/editors/mesh/mesh_navmesh.c +++ b/source/blender/editors/mesh/mesh_navmesh.c @@ -654,7 +654,7 @@ void MESH_OT_navmesh_face_add(struct wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } -static int navmesh_obmode_data_poll(bContext *C) +static bool navmesh_obmode_data_poll(bContext *C) { Object *ob = ED_object_active_context(C); if (ob && (ob->mode == OB_MODE_OBJECT) && (ob->type == OB_MESH)) { @@ -664,7 +664,7 @@ static int navmesh_obmode_data_poll(bContext *C) return false; } -static int navmesh_obmode_poll(bContext *C) +static bool navmesh_obmode_poll(bContext *C) { Object *ob = ED_object_active_context(C); if (ob && (ob->mode == OB_MODE_OBJECT) && (ob->type == OB_MESH)) { diff --git a/source/blender/editors/mesh/mesh_ops.c b/source/blender/editors/mesh/mesh_ops.c index 3c8e18027f41..ca43cfdf3a31 100644 --- a/source/blender/editors/mesh/mesh_ops.c +++ b/source/blender/editors/mesh/mesh_ops.c @@ -297,7 +297,7 @@ void ED_keymap_mesh(wmKeyConfig *keyconf) wmKeyMapItem *kmi; int i; - keymap = WM_keymap_find(keyconf, "Mesh", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Mesh", 0, 0); keymap->poll = ED_operator_editmesh; WM_keymap_add_item(keymap, "MESH_OT_loopcut_slide", RKEY, KM_PRESS, KM_CTRL, 0); @@ -465,4 +465,3 @@ void ED_keymap_mesh(wmKeyConfig *keyconf) knifetool_modal_keymap(keyconf); } - diff --git a/source/blender/editors/metaball/mball_edit.c b/source/blender/editors/metaball/mball_edit.c index fa48462d2c71..84301a22fa0e 100644 --- a/source/blender/editors/metaball/mball_edit.c +++ b/source/blender/editors/metaball/mball_edit.c @@ -661,5 +661,3 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese return false; } - - diff --git a/source/blender/editors/metaball/mball_intern.h b/source/blender/editors/metaball/mball_intern.h index 6e96514c0227..927a8acf5db8 100644 --- a/source/blender/editors/metaball/mball_intern.h +++ b/source/blender/editors/metaball/mball_intern.h @@ -47,4 +47,3 @@ void MBALL_OT_select_similar(struct wmOperatorType *ot); void MBALL_OT_select_random_metaelems(struct wmOperatorType *ot); #endif - diff --git a/source/blender/editors/metaball/mball_ops.c b/source/blender/editors/metaball/mball_ops.c index 2e1b7299295b..b277584ab9eb 100644 --- a/source/blender/editors/metaball/mball_ops.c +++ b/source/blender/editors/metaball/mball_ops.c @@ -72,7 +72,7 @@ void ED_keymap_metaball(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "Metaball", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Metaball", 0, 0); keymap->poll = ED_operator_editmball; WM_keymap_add_item(keymap, "OBJECT_OT_metaball_add", AKEY, KM_PRESS, KM_SHIFT, 0); @@ -97,4 +97,3 @@ void ED_keymap_metaball(wmKeyConfig *keyconf) ED_keymap_proportional_cycle(keyconf, keymap); ED_keymap_proportional_editmode(keyconf, keymap, true); } - diff --git a/source/blender/editors/object/object_add.c b/source/blender/editors/object/object_add.c index 10121e8ae2f1..efc69c36cc38 100644 --- a/source/blender/editors/object/object_add.c +++ b/source/blender/editors/object/object_add.c @@ -321,7 +321,8 @@ bool ED_object_add_generic_get_opts(bContext *C, wmOperator *op, const char view /* Get layers! */ { - int a, layer_values[20]; + int a; + bool layer_values[20]; if (!layer) layer = &_layer; @@ -860,7 +861,7 @@ static int empty_drop_named_image_invoke(bContext *C, wmOperator *op, const wmEv /* add under the mouse */ ED_object_location_from_view(C, ob->loc); - ED_view3d_cursor3d_position(C, ob->loc, event->mval); + ED_view3d_cursor3d_position(C, event->mval, ob->loc); } BKE_object_empty_draw_type_set(ob, OB_EMPTY_IMAGE); @@ -984,7 +985,7 @@ static int group_instance_add_exec(bContext *C, wmOperator *op) const int mval[2] = {event->x - ar->winrct.xmin, event->y - ar->winrct.ymin}; ED_object_location_from_view(C, loc); - ED_view3d_cursor3d_position(C, loc, mval); + ED_view3d_cursor3d_position(C, mval, loc); RNA_float_set_array(op->ptr, "location", loc); } } @@ -1581,7 +1582,7 @@ static void curvetomesh(Main *bmain, Scene *scene, Object *ob) } } -static int convert_poll(bContext *C) +static bool convert_poll(bContext *C) { Object *obact = CTX_data_active_object(C); Scene *scene = CTX_data_scene(C); @@ -1620,7 +1621,7 @@ static int convert_exec(bContext *C, wmOperator *op) Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); Base *basen = NULL, *basact = NULL; - Object *ob, *ob1, *newob, *obact = CTX_data_active_object(C); + Object *ob, *ob1, *obact = CTX_data_active_object(C); DerivedMesh *dm; Curve *cu; Nurb *nu; @@ -1688,6 +1689,7 @@ static int convert_exec(bContext *C, wmOperator *op) } for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) { + Object *newob = NULL; Base *base = link->ptr.data; ob = base->object; @@ -1902,6 +1904,11 @@ static int convert_exec(bContext *C, wmOperator *op) continue; } + /* Ensure new object has consistent material data with its new obdata. */ + if (newob) { + test_object_materials(bmain, newob, newob->data); + } + /* tag obdata if it was been changed */ /* If the original object is active then make this object active */ @@ -2384,7 +2391,7 @@ static int add_named_exec(bContext *C, wmOperator *op) const int mval[2] = {event->x - ar->winrct.xmin, event->y - ar->winrct.ymin}; ED_object_location_from_view(C, basen->object->loc); - ED_view3d_cursor3d_position(C, basen->object->loc, mval); + ED_view3d_cursor3d_position(C, mval, basen->object->loc); } ED_base_object_select(basen, BA_SELECT); @@ -2424,7 +2431,7 @@ void OBJECT_OT_add_named(wmOperatorType *ot) /**************************** Join *************************/ -static int join_poll(bContext *C) +static bool join_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -2477,7 +2484,7 @@ void OBJECT_OT_join(wmOperatorType *ot) /**************************** Join as Shape Key*************************/ -static int join_shapes_poll(bContext *C) +static bool join_shapes_poll(bContext *C) { Object *ob = CTX_data_active_object(C); diff --git a/source/blender/editors/object/object_constraint.c b/source/blender/editors/object/object_constraint.c index 1fc47905db0d..214c995a26e2 100644 --- a/source/blender/editors/object/object_constraint.c +++ b/source/blender/editors/object/object_constraint.c @@ -576,7 +576,7 @@ static const EnumPropertyItem constraint_owner_items[] = { {0, NULL, 0, NULL, NULL}}; -static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type) +static bool edit_constraint_poll_generic(bContext *C, StructRNA *rna_type) { PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", rna_type); Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C); @@ -599,7 +599,7 @@ static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type) return 1; } -static int edit_constraint_poll(bContext *C) +static bool edit_constraint_poll(bContext *C) { return edit_constraint_poll_generic(C, &RNA_Constraint); } @@ -1251,7 +1251,7 @@ void ED_object_constraint_dependency_tag_update(Main *bmain, Object *ob, bConstr DAG_relations_tag_update(bmain); } -static int constraint_poll(bContext *C) +static bool constraint_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint); return (ptr.id.data && ptr.data); @@ -2096,4 +2096,3 @@ void POSE_OT_ik_clear(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/object/object_data_transfer.c b/source/blender/editors/object/object_data_transfer.c index 7845cfe10229..910813450698 100644 --- a/source/blender/editors/object/object_data_transfer.c +++ b/source/blender/editors/object/object_data_transfer.c @@ -445,7 +445,7 @@ static int data_transfer_exec(bContext *C, wmOperator *op) /* Used by both OBJECT_OT_data_transfer and OBJECT_OT_datalayout_transfer */ /* Note this context poll is only really partial, it cannot check for all possible invalid cases. */ -static int data_transfer_poll(bContext *C) +static bool data_transfer_poll(bContext *C) { Object *ob = ED_object_active_context(C); ID *data = (ob) ? ob->data : NULL; @@ -453,8 +453,9 @@ static int data_transfer_poll(bContext *C) } /* Used by both OBJECT_OT_data_transfer and OBJECT_OT_datalayout_transfer */ -static bool data_transfer_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) +static bool data_transfer_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop) { + PointerRNA *ptr = op->ptr; PropertyRNA *prop_other; const char *prop_id = RNA_property_identifier(prop); @@ -515,19 +516,6 @@ static bool data_transfer_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) return true; } -/* Used by both OBJECT_OT_data_transfer and OBJECT_OT_datalayout_transfer */ -static void data_transfer_ui(bContext *C, wmOperator *op) -{ - uiLayout *layout = op->layout; - wmWindowManager *wm = CTX_wm_manager(C); - PointerRNA ptr; - - RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); - - /* Main auto-draw call */ - uiDefAutoButsRNA(layout, &ptr, data_transfer_draw_check_prop, '\0'); -} - /* transfers weight from active to selected */ void OBJECT_OT_data_transfer(wmOperatorType *ot) { @@ -540,10 +528,10 @@ void OBJECT_OT_data_transfer(wmOperatorType *ot) /* API callbacks.*/ ot->poll = data_transfer_poll; + ot->poll_property = data_transfer_poll_property; ot->invoke = WM_menu_invoke; ot->exec = data_transfer_exec; ot->check = data_transfer_check; - ot->ui = data_transfer_ui; /* Flags.*/ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; @@ -613,7 +601,7 @@ void OBJECT_OT_data_transfer(wmOperatorType *ot) * or as a DataTransfer modifier tool. */ -static int datalayout_transfer_poll(bContext *C) +static bool datalayout_transfer_poll(bContext *C) { return (edit_modifier_poll_generic(C, &RNA_DataTransferModifier, (1 << OB_MESH)) || data_transfer_poll(C)); } @@ -702,10 +690,10 @@ void OBJECT_OT_datalayout_transfer(wmOperatorType *ot) ot->idname = "OBJECT_OT_datalayout_transfer"; ot->poll = datalayout_transfer_poll; + ot->poll_property = data_transfer_poll_property; ot->invoke = datalayout_transfer_invoke; ot->exec = datalayout_transfer_exec; ot->check = data_transfer_check; - ot->ui = data_transfer_ui; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; diff --git a/source/blender/editors/object/object_edit.c b/source/blender/editors/object/object_edit.c index a1c0aecbc494..b795b342a3a2 100644 --- a/source/blender/editors/object/object_edit.c +++ b/source/blender/editors/object/object_edit.c @@ -654,7 +654,7 @@ static int editmode_toggle_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int editmode_toggle_poll(bContext *C) +static bool editmode_toggle_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -1348,7 +1348,7 @@ void OBJECT_OT_paths_calculate(wmOperatorType *ot) /* --------- */ -static int object_update_paths_poll(bContext *C) +static bool object_update_paths_poll(bContext *C) { if (ED_operator_object_active_editable(C)) { Object *ob = ED_object_active_context(C); @@ -1516,7 +1516,7 @@ static int shade_smooth_exec(bContext *C, wmOperator *op) return (done) ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } -static int shade_poll(bContext *C) +static bool shade_poll(bContext *C) { return (CTX_data_edit_object(C) == NULL); } @@ -1665,7 +1665,7 @@ static const EnumPropertyItem *object_mode_set_itemsf( return item; } -static int object_mode_set_poll(bContext *C) +static bool object_mode_set_poll(bContext *C) { /* Since Grease Pencil editmode is also handled here, * we have a special exception for allowing this operator diff --git a/source/blender/editors/object/object_hook.c b/source/blender/editors/object/object_hook.c index 94ec87556161..bfc24d4f3256 100644 --- a/source/blender/editors/object/object_hook.c +++ b/source/blender/editors/object/object_hook.c @@ -431,7 +431,7 @@ static void object_hook_select(Object *ob, HookModifierData *hmd) /* special poll operators for hook operators */ /* TODO: check for properties window modifier context too as alternative? */ -static int hook_op_edit_poll(bContext *C) +static bool hook_op_edit_poll(bContext *C) { Object *obedit = CTX_data_edit_object(C); @@ -910,4 +910,3 @@ void OBJECT_OT_hook_select(wmOperatorType *ot) RNA_def_enum_funcs(prop, hook_mod_itemf); RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE); } - diff --git a/source/blender/editors/object/object_intern.h b/source/blender/editors/object/object_intern.h index 1be331d8ac42..f962f83844b6 100644 --- a/source/blender/editors/object/object_intern.h +++ b/source/blender/editors/object/object_intern.h @@ -148,8 +148,8 @@ void GROUP_OT_objects_add_active(struct wmOperatorType *ot); void GROUP_OT_objects_remove_active(struct wmOperatorType *ot); /* object_modifier.c */ -int edit_modifier_poll_generic(struct bContext *C, struct StructRNA *rna_type, int obtype_flag); -int edit_modifier_poll(struct bContext *C); +bool edit_modifier_poll_generic(struct bContext *C, struct StructRNA *rna_type, int obtype_flag); +bool edit_modifier_poll(struct bContext *C); void edit_modifier_properties(struct wmOperatorType *ot); int edit_modifier_invoke_properties(struct bContext *C, struct wmOperator *op); struct ModifierData *edit_modifier_property_get(struct wmOperator *op, struct Object *ob, int type); @@ -271,4 +271,3 @@ void OBJECT_OT_data_transfer(struct wmOperatorType *ot); void OBJECT_OT_datalayout_transfer(struct wmOperatorType *ot); #endif /* __OBJECT_INTERN_H__ */ - diff --git a/source/blender/editors/object/object_modifier.c b/source/blender/editors/object/object_modifier.c index 9dbb724c9f74..5f3a6d0ac949 100644 --- a/source/blender/editors/object/object_modifier.c +++ b/source/blender/editors/object/object_modifier.c @@ -814,7 +814,7 @@ void OBJECT_OT_modifier_add(wmOperatorType *ot) /************************ generic functions for operators using mod names and data context *********************/ -int edit_modifier_poll_generic(bContext *C, StructRNA *rna_type, int obtype_flag) +bool edit_modifier_poll_generic(bContext *C, StructRNA *rna_type, int obtype_flag) { PointerRNA ptr = CTX_data_pointer_get_type(C, "modifier", rna_type); Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C); @@ -826,7 +826,7 @@ int edit_modifier_poll_generic(bContext *C, StructRNA *rna_type, int obtype_flag return 1; } -int edit_modifier_poll(bContext *C) +bool edit_modifier_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_Modifier, 0); } @@ -1127,7 +1127,7 @@ void OBJECT_OT_modifier_copy(wmOperatorType *ot) /************* multires delete higher levels operator ****************/ -static int multires_poll(bContext *C) +static bool multires_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_MultiresModifier, (1 << OB_MESH)); } @@ -1452,13 +1452,13 @@ static void modifier_skin_customdata_delete(Object *ob) CustomData_free_layer_active(&me->vdata, CD_MVERT_SKIN, me->totvert); } -static int skin_poll(bContext *C) +static bool skin_poll(bContext *C) { return (!CTX_data_edit_object(C) && edit_modifier_poll_generic(C, &RNA_SkinModifier, (1 << OB_MESH))); } -static int skin_edit_poll(bContext *C) +static bool skin_edit_poll(bContext *C) { return (CTX_data_edit_object(C) && edit_modifier_poll_generic(C, &RNA_SkinModifier, (1 << OB_MESH))); @@ -1824,7 +1824,7 @@ void OBJECT_OT_skin_armature_create(wmOperatorType *ot) } /************************ delta mush bind operator *********************/ -static int correctivesmooth_poll(bContext *C) +static bool correctivesmooth_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_CorrectiveSmoothModifier, 0); } @@ -1892,7 +1892,7 @@ void OBJECT_OT_correctivesmooth_bind(wmOperatorType *ot) /************************ mdef bind operator *********************/ -static int meshdeform_poll(bContext *C) +static bool meshdeform_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_MeshDeformModifier, 0); } @@ -1988,7 +1988,7 @@ void OBJECT_OT_meshdeform_bind(wmOperatorType *ot) /****************** explode refresh operator *********************/ -static int explode_poll(bContext *C) +static bool explode_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_ExplodeModifier, 0); } @@ -2036,7 +2036,7 @@ void OBJECT_OT_explode_refresh(wmOperatorType *ot) /****************** ocean bake operator *********************/ -static int ocean_bake_poll(bContext *C) +static bool ocean_bake_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_OceanModifier, 0); } @@ -2254,7 +2254,7 @@ void OBJECT_OT_ocean_bake(wmOperatorType *ot) /************************ LaplacianDeform bind operator *********************/ -static int laplaciandeform_poll(bContext *C) +static bool laplaciandeform_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_LaplacianDeformModifier, 0); } @@ -2304,7 +2304,7 @@ void OBJECT_OT_laplaciandeform_bind(wmOperatorType *ot) /************************ sdef bind operator *********************/ -static int surfacedeform_bind_poll(bContext *C) +static bool surfacedeform_bind_poll(bContext *C) { return edit_modifier_poll_generic(C, &RNA_SurfaceDeformModifier, 0); } diff --git a/source/blender/editors/object/object_ops.c b/source/blender/editors/object/object_ops.c index 9a0b37e6daba..f6db6d1f5fc5 100644 --- a/source/blender/editors/object/object_ops.c +++ b/source/blender/editors/object/object_ops.c @@ -274,7 +274,7 @@ void ED_operatormacros_object(void) } -static int object_mode_poll(bContext *C) +static bool object_mode_poll(bContext *C) { Object *ob = CTX_data_active_object(C); return (!ob || ob->mode == OB_MODE_OBJECT); @@ -287,7 +287,7 @@ void ED_keymap_object(wmKeyConfig *keyconf) int i; /* Objects, Regardless of Mode -------------------------------------------------- */ - keymap = WM_keymap_find(keyconf, "Object Non-modal", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Object Non-modal", 0, 0); /* Note: this keymap works disregarding mode */ kmi = WM_keymap_add_item(keymap, "OBJECT_OT_mode_set", TABKEY, KM_PRESS, 0, 0); @@ -310,7 +310,7 @@ void ED_keymap_object(wmKeyConfig *keyconf) /* Object Mode ---------------------------------------------------------------- */ /* Note: this keymap gets disabled in non-objectmode, */ - keymap = WM_keymap_find(keyconf, "Object Mode", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Object Mode", 0, 0); keymap->poll = object_mode_poll; /* object mode supports PET now */ diff --git a/source/blender/editors/object/object_relations.c b/source/blender/editors/object/object_relations.c index 8abbb5359810..34f640234412 100644 --- a/source/blender/editors/object/object_relations.c +++ b/source/blender/editors/object/object_relations.c @@ -114,7 +114,7 @@ /*********************** Make Vertex Parent Operator ************************/ -static int vertex_parent_set_poll(bContext *C) +static bool vertex_parent_set_poll(bContext *C) { return ED_operator_editmesh(C) || ED_operator_editsurfcurve(C) || ED_operator_editlattice(C); } @@ -938,13 +938,13 @@ static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent return OPERATOR_INTERFACE; } -static bool parent_set_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) +static bool parent_set_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop) { const char *prop_id = RNA_property_identifier(prop); - const int type = RNA_enum_get(ptr, "type"); /* Only show XMirror for PAR_ARMATURE_ENVELOPE and PAR_ARMATURE_AUTO! */ if (STREQ(prop_id, "xmirror")) { + const int type = RNA_enum_get(op->ptr, "type"); if (ELEM(type, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO)) return true; else @@ -954,18 +954,6 @@ static bool parent_set_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) return true; } -static void parent_set_ui(bContext *C, wmOperator *op) -{ - uiLayout *layout = op->layout; - wmWindowManager *wm = CTX_wm_manager(C); - PointerRNA ptr; - - RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); - - /* Main auto-draw call. */ - uiDefAutoButsRNA(layout, &ptr, parent_set_draw_check_prop, '\0'); -} - void OBJECT_OT_parent_set(wmOperatorType *ot) { /* identifiers */ @@ -977,7 +965,7 @@ void OBJECT_OT_parent_set(wmOperatorType *ot) ot->invoke = parent_set_invoke; ot->exec = parent_set_exec; ot->poll = ED_operator_object_active; - ot->ui = parent_set_ui; + ot->poll_property = parent_set_poll_property; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; @@ -1313,7 +1301,8 @@ void OBJECT_OT_track_set(wmOperatorType *ot) static unsigned int move_to_layer_init(bContext *C, wmOperator *op) { - int values[20], a; + int a; + bool values[20]; unsigned int lay = 0; if (!RNA_struct_property_is_set(op->ptr, "layers")) { diff --git a/source/blender/editors/object/object_select.c b/source/blender/editors/object/object_select.c index 6b53807ce1cc..2fc6207d6c13 100644 --- a/source/blender/editors/object/object_select.c +++ b/source/blender/editors/object/object_select.c @@ -121,7 +121,7 @@ void ED_base_object_activate(bContext *C, Base *base) /********************** Selection Operators **********************/ -static int objects_selectable_poll(bContext *C) +static bool objects_selectable_poll(bContext *C) { /* we don't check for linked scenes here, selection is * still allowed then for inspection of scene */ diff --git a/source/blender/editors/object/object_shapekey.c b/source/blender/editors/object/object_shapekey.c index 2f536f59c81c..e67b62ea6247 100644 --- a/source/blender/editors/object/object_shapekey.c +++ b/source/blender/editors/object/object_shapekey.c @@ -222,14 +222,14 @@ static bool object_shape_key_mirror(bContext *C, Object *ob, /********************** shape key operators *********************/ -static int shape_key_mode_poll(bContext *C) +static bool shape_key_mode_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; return (ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data) && ob->mode != OB_MODE_EDIT); } -static int shape_key_mode_exists_poll(bContext *C) +static bool shape_key_mode_exists_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -240,7 +240,7 @@ static int shape_key_mode_exists_poll(bContext *C) (BKE_keyblock_from_object(ob) != NULL); } -static int shape_key_move_poll(bContext *C) +static bool shape_key_move_poll(bContext *C) { /* Same as shape_key_mode_exists_poll above, but ensure we have at least two shapes! */ Object *ob = ED_object_context(C); @@ -251,7 +251,7 @@ static int shape_key_move_poll(bContext *C) ob->mode != OB_MODE_EDIT && key && key->totkey > 1); } -static int shape_key_poll(bContext *C) +static bool shape_key_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -376,8 +376,10 @@ static int shape_key_retime_exec(bContext *C, wmOperator *UNUSED(op)) if (!key || !kb) return OPERATOR_CANCELLED; - for (kb = key->block.first; kb; kb = kb->next) - kb->pos = (cfra += 0.1f); + for (kb = key->block.first; kb; kb = kb->next) { + kb->pos = cfra; + cfra += 0.1f; + } DAG_id_tag_update(&ob->id, OB_RECALC_DATA); WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob); @@ -500,4 +502,3 @@ void OBJECT_OT_shape_key_move(wmOperatorType *ot) RNA_def_enum(ot->srna, "type", slot_move, 0, "Type", ""); } - diff --git a/source/blender/editors/object/object_vgroup.c b/source/blender/editors/object/object_vgroup.c index fcb2d45f73bf..6c5076ef5637 100644 --- a/source/blender/editors/object/object_vgroup.c +++ b/source/blender/editors/object/object_vgroup.c @@ -2480,7 +2480,7 @@ static void vgroup_assign_verts(Object *ob, const float weight) /********************** vertex group operators *********************/ -static int vertex_group_poll(bContext *C) +static bool vertex_group_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2491,7 +2491,7 @@ static int vertex_group_poll(bContext *C) ob->defbase.first); } -static int vertex_group_supported_poll(bContext *C) +static bool vertex_group_supported_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2499,7 +2499,7 @@ static int vertex_group_supported_poll(bContext *C) data && !ID_IS_LINKED(data)); } -static int vertex_group_mesh_poll(bContext *C) +static bool vertex_group_mesh_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2510,7 +2510,7 @@ static int vertex_group_mesh_poll(bContext *C) ob->defbase.first); } -static int UNUSED_FUNCTION(vertex_group_mesh_supported_poll)(bContext *C) +static bool UNUSED_FUNCTION(vertex_group_mesh_supported_poll)(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2518,7 +2518,7 @@ static int UNUSED_FUNCTION(vertex_group_mesh_supported_poll)(bContext *C) } -static int UNUSED_FUNCTION(vertex_group_poll_edit) (bContext *C) +static bool UNUSED_FUNCTION(vertex_group_poll_edit) (bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2530,7 +2530,7 @@ static int UNUSED_FUNCTION(vertex_group_poll_edit) (bContext *C) } /* editmode _or_ weight paint vertex sel */ -static int vertex_group_vert_poll_ex(bContext *C, const bool needs_select, const short ob_type_flag) +static bool vertex_group_vert_poll_ex(bContext *C, const bool needs_select, const short ob_type_flag) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2565,25 +2565,25 @@ static int vertex_group_vert_poll_ex(bContext *C, const bool needs_select, const } #if 0 -static int vertex_group_vert_poll(bContext *C) +static bool vertex_group_vert_poll(bContext *C) { return vertex_group_vert_poll_ex(C, false, 0); } #endif -static int vertex_group_mesh_vert_poll(bContext *C) +static bool vertex_group_mesh_vert_poll(bContext *C) { return vertex_group_vert_poll_ex(C, false, (1 << OB_MESH)); } -static int vertex_group_vert_select_poll(bContext *C) +static bool vertex_group_vert_select_poll(bContext *C) { return vertex_group_vert_poll_ex(C, true, 0); } #if 0 -static int vertex_group_mesh_vert_select_poll(bContext *C) +static bool vertex_group_mesh_vert_select_poll(bContext *C) { return vertex_group_vert_poll_ex(C, true, (1 << OB_MESH)); } @@ -2591,7 +2591,7 @@ static int vertex_group_mesh_vert_select_poll(bContext *C) /* editmode _or_ weight paint vertex sel and active group unlocked */ -static int vertex_group_vert_select_unlocked_poll(bContext *C) +static bool vertex_group_vert_select_unlocked_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; @@ -2614,7 +2614,7 @@ static int vertex_group_vert_select_unlocked_poll(bContext *C) return 1; } -static int vertex_group_vert_select_mesh_poll(bContext *C) +static bool vertex_group_vert_select_mesh_poll(bContext *C) { Object *ob = ED_object_context(C); ID *data = (ob) ? ob->data : NULL; diff --git a/source/blender/editors/physics/particle_boids.c b/source/blender/editors/physics/particle_boids.c index 526eeb5d3ea0..bb7dd64fb470 100644 --- a/source/blender/editors/physics/particle_boids.c +++ b/source/blender/editors/physics/particle_boids.c @@ -57,7 +57,7 @@ static int rule_add_exec(bContext *C, wmOperator *op) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); ParticleSettings *part = ptr.data; - int type= RNA_enum_get(op->ptr, "type"); + int type = RNA_enum_get(op->ptr, "type"); BoidRule *rule; BoidState *state; @@ -67,7 +67,7 @@ static int rule_add_exec(bContext *C, wmOperator *op) state = boid_get_current_state(part->boids); - for (rule=state->rules.first; rule; rule=rule->next) + for (rule = state->rules.first; rule; rule = rule->next) rule->flag &= ~BOIDRULE_CURRENT; rule = boid_new_rule(type); @@ -75,7 +75,7 @@ static int rule_add_exec(bContext *C, wmOperator *op) BLI_addtail(&state->rules, rule); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); return OPERATOR_FINISHED; } @@ -92,7 +92,7 @@ void BOID_OT_rule_add(wmOperatorType *ot) ot->exec = rule_add_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_boidrule_type_items, 0, "Type", ""); } @@ -109,7 +109,7 @@ static int rule_del_exec(bContext *C, wmOperator *UNUSED(op)) state = boid_get_current_state(part->boids); - for (rule=state->rules.first; rule; rule=rule->next) { + for (rule = state->rules.first; rule; rule = rule->next) { if (rule->flag & BOIDRULE_CURRENT) { BLI_remlink(&state->rules, rule); MEM_freeN(rule); @@ -122,7 +122,7 @@ static int rule_del_exec(bContext *C, wmOperator *UNUSED(op)) rule->flag |= BOIDRULE_CURRENT; DAG_relations_tag_update(bmain); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); return OPERATOR_FINISHED; } @@ -138,7 +138,7 @@ void BOID_OT_rule_del(wmOperatorType *ot) ot->exec = rule_del_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up/down boid rule operators *********************/ @@ -153,12 +153,12 @@ static int rule_move_up_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule=rule->next) { + for (rule = state->rules.first; rule; rule = rule->next) { if (rule->flag & BOIDRULE_CURRENT && rule->prev) { BLI_remlink(&state->rules, rule); BLI_insertlinkbefore(&state->rules, rule->prev, rule); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); break; } } @@ -175,7 +175,7 @@ void BOID_OT_rule_move_up(wmOperatorType *ot) ot->exec = rule_move_up_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int rule_move_down_exec(bContext *C, wmOperator *UNUSED(op)) @@ -189,12 +189,12 @@ static int rule_move_down_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule=rule->next) { + for (rule = state->rules.first; rule; rule = rule->next) { if (rule->flag & BOIDRULE_CURRENT && rule->next) { BLI_remlink(&state->rules, rule); BLI_insertlinkafter(&state->rules, rule->next, rule); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); break; } } @@ -211,7 +211,7 @@ void BOID_OT_rule_move_down(wmOperatorType *ot) ot->exec = rule_move_down_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } @@ -225,7 +225,7 @@ static int state_add_exec(bContext *C, wmOperator *UNUSED(op)) if (!part || part->phystype != PART_PHYS_BOIDS) return OPERATOR_CANCELLED; - for (state=part->boids->states.first; state; state=state->next) + for (state = part->boids->states.first; state; state = state->next) state->flag &= ~BOIDSTATE_CURRENT; state = boid_new_state(part->boids); @@ -247,7 +247,7 @@ void BOID_OT_state_add(wmOperatorType *ot) ot->exec = state_add_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int state_del_exec(bContext *C, wmOperator *UNUSED(op)) { @@ -259,7 +259,7 @@ static int state_del_exec(bContext *C, wmOperator *UNUSED(op)) if (!part || part->phystype != PART_PHYS_BOIDS) return OPERATOR_CANCELLED; - for (state=part->boids->states.first; state; state=state->next) { + for (state = part->boids->states.first; state; state = state->next) { if (state->flag & BOIDSTATE_CURRENT) { BLI_remlink(&part->boids->states, state); MEM_freeN(state); @@ -278,7 +278,7 @@ static int state_del_exec(bContext *C, wmOperator *UNUSED(op)) state->flag |= BOIDSTATE_CURRENT; DAG_relations_tag_update(bmain); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); return OPERATOR_FINISHED; } @@ -294,7 +294,7 @@ void BOID_OT_state_del(wmOperatorType *ot) ot->exec = state_del_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up/down boid state operators *********************/ @@ -310,7 +310,7 @@ static int state_move_up_exec(bContext *C, wmOperator *UNUSED(op)) boids = part->boids; - for (state = boids->states.first; state; state=state->next) { + for (state = boids->states.first; state; state = state->next) { if (state->flag & BOIDSTATE_CURRENT && state->prev) { BLI_remlink(&boids->states, state); BLI_insertlinkbefore(&boids->states, state->prev, state); @@ -330,7 +330,7 @@ void BOID_OT_state_move_up(wmOperatorType *ot) ot->exec = state_move_up_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int state_move_down_exec(bContext *C, wmOperator *UNUSED(op)) @@ -345,11 +345,11 @@ static int state_move_down_exec(bContext *C, wmOperator *UNUSED(op)) boids = part->boids; - for (state = boids->states.first; state; state=state->next) { + for (state = boids->states.first; state; state = state->next) { if (state->flag & BOIDSTATE_CURRENT && state->next) { BLI_remlink(&boids->states, state); BLI_insertlinkafter(&boids->states, state->next, state); - DAG_id_tag_update(&part->id, OB_RECALC_DATA|PSYS_RECALC_RESET); + DAG_id_tag_update(&part->id, OB_RECALC_DATA | PSYS_RECALC_RESET); break; } } @@ -366,6 +366,5 @@ void BOID_OT_state_move_down(wmOperatorType *ot) ot->exec = state_move_down_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/physics/particle_edit.c b/source/blender/editors/physics/particle_edit.c index acfc3844b836..a03892a26d14 100644 --- a/source/blender/editors/physics/particle_edit.c +++ b/source/blender/editors/physics/particle_edit.c @@ -86,11 +86,11 @@ /**************************** utilities *******************************/ -int PE_poll(bContext *C) +bool PE_poll(bContext *C) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) return 0; @@ -98,22 +98,22 @@ int PE_poll(bContext *C) return (PE_get_current(bmain, scene, ob) != NULL); } -int PE_hair_poll(bContext *C) +bool PE_hair_poll(bContext *C) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); PTCacheEdit *edit; if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) return 0; - edit= PE_get_current(bmain, scene, ob); + edit = PE_get_current(bmain, scene, ob); return (edit && edit->psys); } -int PE_poll_view3d(bContext *C) +bool PE_poll_view3d(bContext *C) { ScrArea *sa = CTX_wm_area(C); ARegion *ar = CTX_wm_region(C); @@ -127,7 +127,7 @@ void PE_free_ptcache_edit(PTCacheEdit *edit) { POINT_P; - if (edit==0) return; + if (edit == 0) return; if (edit->points) { LOOP_POINTS { @@ -143,12 +143,12 @@ void PE_free_ptcache_edit(PTCacheEdit *edit) if (edit->emitter_cosnos) { MEM_freeN(edit->emitter_cosnos); - edit->emitter_cosnos= 0; + edit->emitter_cosnos = 0; } if (edit->emitter_field) { BLI_kdtree_free(edit->emitter_field); - edit->emitter_field= 0; + edit->emitter_field = 0; } psys_free_path_cache(edit->psys, edit); @@ -193,12 +193,12 @@ static float pe_brush_size_get(const Scene *UNUSED(scene), ParticleBrushData *br * keep it fast! */ static PTCacheEdit *pe_get_current(Main *bmain, Scene *scene, Object *ob, int create) { - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); PTCacheEdit *edit = NULL; ListBase pidlist; PTCacheID *pid; - if (pset==NULL || ob==NULL) + if (pset == NULL || ob == NULL) return NULL; pset->scene = scene; @@ -222,7 +222,7 @@ static PTCacheEdit *pe_get_current(Main *bmain, Scene *scene, Object *ob, int cr } } - for (pid=pidlist.first; pid; pid=pid->next) { + for (pid = pidlist.first; pid; pid = pid->next) { if (pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) { ParticleSystem *psys = pid->calldata; @@ -294,11 +294,11 @@ void PE_current_changed(Main *bmain, Scene *scene, Object *ob) void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra) { - ParticleEditSettings *pset=PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); POINT_P; KEY_K; - if (pset->flag & PE_FADE_TIME && pset->selectmode==SCE_SELECT_POINT) { + if (pset->flag & PE_FADE_TIME && pset->selectmode == SCE_SELECT_POINT) { LOOP_POINTS { LOOP_KEYS { if (fabsf(cfra - *key->time) < pset->fade_frames) @@ -341,7 +341,7 @@ typedef struct PEData { BVHTreeFromMesh shape_bvh; const int *mval; - rcti *rect; + const rcti *rect; float rad; float dist; float dval; @@ -369,9 +369,9 @@ static void PE_set_data(bContext *C, PEData *data) memset(data, 0, sizeof(*data)); data->bmain = CTX_data_main(C); - data->scene= CTX_data_scene(C); - data->ob= CTX_data_active_object(C); - data->edit= PE_get_current(data->bmain, data->scene, data->ob); + data->scene = CTX_data_scene(C); + data->ob = CTX_data_active_object(C); + data->edit = PE_get_current(data->bmain, data->scene, data->ob); } static void PE_set_view3d_data(bContext *C, PEData *data) @@ -418,7 +418,7 @@ static void PE_free_shape_tree(PEData *data) static bool key_test_depth(PEData *data, const float co[3], const int screen_co[2]) { - View3D *v3d= data->vc.v3d; + View3D *v3d = data->vc.v3d; ViewDepths *vd = data->vc.rv3d->depths; double ux, uy, uz; float depth; @@ -464,8 +464,8 @@ static bool key_inside_circle(PEData *data, float rad, const float co[3], float return 0; } - dx= data->mval[0] - screen_co[0]; - dy= data->mval[1] - screen_co[1]; + dx = data->mval[0] - screen_co[0]; + dy = data->mval[1] - screen_co[1]; dist = sqrtf(dx * dx + dy * dy); if (dist > rad) @@ -473,7 +473,7 @@ static bool key_inside_circle(PEData *data, float rad, const float co[3], float if (key_test_depth(data, co, screen_co)) { if (distance) - *distance=dist; + *distance = dist; return 1; } @@ -526,35 +526,35 @@ typedef void (*ForPointFunc)(PEData *data, int point_index); typedef void (*ForKeyFunc)(PEData *data, int point_index, int key_index); typedef void (*ForKeyMatFunc)(PEData *data, float mat[4][4], float imat[4][4], int point_index, int key_index, PTCacheEditKey *key); -static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest) +static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, bool nearest) { - ParticleEditSettings *pset= PE_settings(data->scene); - PTCacheEdit *edit= data->edit; + ParticleEditSettings *pset = PE_settings(data->scene); + PTCacheEdit *edit = data->edit; POINT_P; KEY_K; int nearest_point, nearest_key; - float dist= data->rad; + float dist = data->rad; /* in path select mode we have no keys */ - if (pset->selectmode==SCE_SELECT_PATH) + if (pset->selectmode == SCE_SELECT_PATH) return; - nearest_point= -1; - nearest_key= -1; + nearest_point = -1; + nearest_key = -1; LOOP_VISIBLE_POINTS { if (pset->selectmode == SCE_SELECT_END) { if (point->totkey) { /* only do end keys */ - key= point->keys + point->totkey-1; + key = point->keys + point->totkey - 1; if (nearest) { if (key_inside_circle(data, dist, KEY_WCO, &dist)) { - nearest_point= p; - nearest_key= point->totkey-1; + nearest_point = p; + nearest_key = point->totkey - 1; } } else if (key_inside_test(data, KEY_WCO)) - func(data, p, point->totkey-1); + func(data, p, point->totkey - 1); } } else { @@ -562,8 +562,8 @@ static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest) LOOP_VISIBLE_KEYS { if (nearest) { if (key_inside_circle(data, dist, KEY_WCO, &dist)) { - nearest_point= p; - nearest_key= k; + nearest_point = p; + nearest_key = k; } } else if (key_inside_test(data, KEY_WCO)) @@ -579,21 +579,21 @@ static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest) static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selected) { - ParticleEditSettings *pset= PE_settings(data->scene); - PTCacheEdit *edit= data->edit; + ParticleEditSettings *pset = PE_settings(data->scene); + PTCacheEdit *edit = data->edit; POINT_P; KEY_K; /* all is selected in path mode */ - if (pset->selectmode==SCE_SELECT_PATH) - selected=0; + if (pset->selectmode == SCE_SELECT_PATH) + selected = 0; LOOP_VISIBLE_POINTS { - if (pset->selectmode==SCE_SELECT_END) { + if (pset->selectmode == SCE_SELECT_END) { if (point->totkey) { /* only do end keys */ - key= point->keys + point->totkey - 1; + key = point->keys + point->totkey - 1; - if (selected==0 || key->flag & PEK_SELECT) + if (selected == 0 || key->flag & PEK_SELECT) if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) func(data, p); } @@ -601,7 +601,7 @@ static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selecte else { /* do all keys */ LOOP_VISIBLE_KEYS { - if (selected==0 || key->flag & PEK_SELECT) { + if (selected == 0 || key->flag & PEK_SELECT) { if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) { func(data, p); break; @@ -617,7 +617,7 @@ static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected PTCacheEdit *edit = data->edit; ParticleSystem *psys = edit->psys; ParticleSystemModifierData *psmd = NULL; - ParticleEditSettings *pset= PE_settings(data->scene); + ParticleEditSettings *pset = PE_settings(data->scene); POINT_P; KEY_K; float mat[4][4], imat[4][4]; @@ -625,26 +625,26 @@ static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected unit_m4(imat); if (edit->psys) - psmd= psys_get_modifier(data->ob, edit->psys); + psmd = psys_get_modifier(data->ob, edit->psys); /* all is selected in path mode */ - if (pset->selectmode==SCE_SELECT_PATH) - selected= 0; + if (pset->selectmode == SCE_SELECT_PATH) + selected = 0; LOOP_VISIBLE_POINTS { - if (pset->selectmode==SCE_SELECT_END) { + if (pset->selectmode == SCE_SELECT_END) { if (point->totkey) { /* only do end keys */ - key= point->keys + point->totkey-1; + key = point->keys + point->totkey - 1; - if (selected==0 || key->flag & PEK_SELECT) { + if (selected == 0 || key->flag & PEK_SELECT) { if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) { if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { psys_mat_hair_to_global(data->ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); invert_m4_m4(imat, mat); } - func(data, mat, imat, p, point->totkey-1, key); + func(data, mat, imat, p, point->totkey - 1, key); } } } @@ -652,7 +652,7 @@ static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected else { /* do all keys */ LOOP_VISIBLE_KEYS { - if (selected==0 || key->flag & PEK_SELECT) { + if (selected == 0 || key->flag & PEK_SELECT) { if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) { if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { psys_mat_hair_to_global(data->ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); @@ -701,17 +701,17 @@ static void foreach_point(PEData *data, ForPointFunc func) static int count_selected_keys(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); POINT_P; KEY_K; - int sel= 0; + int sel = 0; LOOP_VISIBLE_POINTS { - if (pset->selectmode==SCE_SELECT_POINT) { + if (pset->selectmode == SCE_SELECT_POINT) { LOOP_SELECTED_KEYS { sel++; } } - else if (pset->selectmode==SCE_SELECT_END) { + else if (pset->selectmode == SCE_SELECT_END) { if (point->totkey) { key = point->keys + point->totkey - 1; if (key->flag & PEK_SELECT) @@ -738,14 +738,14 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) float mat[4][4], co[3]; int index, totpart; - edit= psys->edit; - psmd= psys_get_modifier(ob, psys); - totpart= psys->totpart; + edit = psys->edit; + psmd = psys_get_modifier(ob, psys); + totpart = psys->totpart; if (!psmd->dm_final) return; - tree= BLI_kdtree_new(totpart); + tree = BLI_kdtree_new(totpart); /* insert particles into kd tree */ LOOP_PARTICLES { @@ -760,7 +760,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) /* lookup particles and set in mirror cache */ if (!edit->mirror_cache) - edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache"); + edit->mirror_cache = MEM_callocN(sizeof(int) * totpart, "PE mirror cache"); LOOP_PARTICLES { key = pa->hair; @@ -769,7 +769,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) mul_m4_v3(mat, co); co[0] = -co[0]; - index= BLI_kdtree_find_nearest(tree, co, &nearest); + index = BLI_kdtree_find_nearest(tree, co, &nearest); /* this needs a custom threshold still, duplicated for editmode mirror */ if (index != -1 && index != p && (nearest.dist <= 0.0002f)) @@ -781,7 +781,7 @@ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) /* make sure mirrors are in two directions */ LOOP_PARTICLES { if (edit->mirror_cache[p]) { - index= edit->mirror_cache[p]; + index = edit->mirror_cache[p]; if (edit->mirror_cache[index] != p) edit->mirror_cache[p] = -1; } @@ -799,8 +799,8 @@ static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys float mat[4][4], mmat[4][4], immat[4][4]; int i, mi, k; - edit= psys->edit; - i= pa - psys->particles; + edit = psys->edit; + i = pa - psys->particles; /* find mirrored particle if needed */ if (!mpa) { @@ -810,13 +810,13 @@ static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys if (!edit->mirror_cache) return; /* something went wrong! */ - mi= edit->mirror_cache[i]; + mi = edit->mirror_cache[i]; if (mi == -1) return; - mpa= psys->particles + mi; + mpa = psys->particles + mi; } else - mi= mpa - psys->particles; + mi = mpa - psys->particles; point = edit->points + i; mpoint = edit->points + mi; @@ -826,16 +826,16 @@ static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys if (mpa->hair) MEM_freeN(mpa->hair); if (mpoint->keys) MEM_freeN(mpoint->keys); - mpa->hair= MEM_dupallocN(pa->hair); - mpa->totkey= pa->totkey; - mpoint->keys= MEM_dupallocN(point->keys); - mpoint->totkey= point->totkey; + mpa->hair = MEM_dupallocN(pa->hair); + mpa->totkey = pa->totkey; + mpoint->keys = MEM_dupallocN(point->keys); + mpoint->totkey = point->totkey; - mhkey= mpa->hair; - mkey= mpoint->keys; - for (k=0; ktotkey; k++, mkey++, mhkey++) { - mkey->co= mhkey->co; - mkey->time= &mhkey->time; + mhkey = mpa->hair; + mkey = mpoint->keys; + for (k = 0; k < mpa->totkey; k++, mkey++, mhkey++) { + mkey->co = mhkey->co; + mkey->time = &mhkey->time; mkey->flag &= ~PEK_SELECT; } } @@ -845,11 +845,11 @@ static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat); invert_m4_m4(immat, mmat); - hkey=pa->hair; - mhkey=mpa->hair; - key= point->keys; - mkey= mpoint->keys; - for (k=0; ktotkey; k++, hkey++, mhkey++, key++, mkey++) { + hkey = pa->hair; + mhkey = mpa->hair; + key = point->keys; + mkey = mpoint->keys; + for (k = 0; k < pa->totkey; k++, hkey++, mhkey++, key++, mkey++) { copy_v3_v3(mhkey->co, hkey->co); mul_m4_v3(mat, mhkey->co); mhkey->co[0] = -mhkey->co[0]; @@ -876,8 +876,8 @@ static void PE_apply_mirror(Object *ob, ParticleSystem *psys) if (!psys) return; - edit= psys->edit; - psmd= psys_get_modifier(ob, psys); + edit = psys->edit; + psmd = psys_get_modifier(ob, psys); if (!psmd->dm_final) return; @@ -912,16 +912,16 @@ static void PE_apply_mirror(Object *ob, ParticleSystem *psys) /* tries to stop edited particles from going through the emitter's surface */ static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit) { - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); ParticleSystem *psys; ParticleSystemModifierData *psmd; POINT_P; KEY_K; int index; - float *vec, *nor, dvec[3], dot, dist_1st=0.0f; + float *vec, *nor, dvec[3], dot, dist_1st = 0.0f; float hairimat[4][4], hairmat[4][4]; const float dist = ED_view3d_select_dist_px() * 0.01f; - if (edit==NULL || edit->psys==NULL || (pset->flag & PE_DEFLECT_EMITTER)==0 || (edit->psys->flag & PSYS_GLOBAL_HAIR)) + if (edit == NULL || edit->psys == NULL || (pset->flag & PE_DEFLECT_EMITTER) == 0 || (edit->psys->flag & PSYS_GLOBAL_HAIR)) return; psys = edit->psys; @@ -938,35 +938,35 @@ static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit) } LOOP_KEYS { - if (k==0) { - dist_1st = len_v3v3((key+1)->co, key->co); + if (k == 0) { + dist_1st = len_v3v3((key + 1)->co, key->co); dist_1st *= dist * pset->emitterdist; } else { - index= BLI_kdtree_find_nearest(edit->emitter_field, key->co, NULL); + index = BLI_kdtree_find_nearest(edit->emitter_field, key->co, NULL); - vec=edit->emitter_cosnos +index*6; - nor=vec+3; + vec = edit->emitter_cosnos + index * 6; + nor = vec + 3; sub_v3_v3v3(dvec, key->co, vec); - dot=dot_v3v3(dvec, nor); + dot = dot_v3v3(dvec, nor); copy_v3_v3(dvec, nor); - if (dot>0.0f) { - if (dot 0.0f) { + if (dot < dist_1st) { normalize_v3(dvec); - mul_v3_fl(dvec, dist_1st-dot); + mul_v3_fl(dvec, dist_1st - dot); add_v3_v3(key->co, dvec); } } else { normalize_v3(dvec); - mul_v3_fl(dvec, dist_1st-dot); + mul_v3_fl(dvec, dist_1st - dot); add_v3_v3(key->co, dvec); } - if (k==1) - dist_1st*=1.3333f; + if (k == 1) + dist_1st *= 1.3333f; } } @@ -981,11 +981,11 @@ static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit) static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset=PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); POINT_P; KEY_K; float dv1[3]; - if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0) + if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) return; if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) @@ -1005,7 +1005,7 @@ static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit) /* try to find a nice solution to keep distances between neighboring keys */ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset=PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); POINT_P; PTCacheEditKey *key; int j, k; @@ -1014,42 +1014,42 @@ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit) float dv1[3] = {0.0f, 0.0f, 0.0f}; float dv2[3] = {0.0f, 0.0f, 0.0f}; - if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0) + if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) return; if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) return; LOOP_EDITED_POINTS { - for (j=1; jtotkey; j++) { - float mul= 1.0f / (float)point->totkey; + for (j = 1; j < point->totkey; j++) { + float mul = 1.0f / (float)point->totkey; if (pset->flag & PE_LOCK_FIRST) { - key= point->keys + 1; - k= 1; + key = point->keys + 1; + k = 1; dv1[0] = dv1[1] = dv1[2] = 0.0; } else { - key= point->keys; - k= 0; + key = point->keys; + k = 0; dv0[0] = dv0[1] = dv0[2] = 0.0; } - for (; ktotkey; k++, key++) { + for (; k < point->totkey; k++, key++) { if (k) { sub_v3_v3v3(dv0, (key - 1)->co, key->co); - tlen= normalize_v3(dv0); + tlen = normalize_v3(dv0); mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length))); } if (k < point->totkey - 1) { sub_v3_v3v3(dv2, (key + 1)->co, key->co); - tlen= normalize_v3(dv2); + tlen = normalize_v3(dv2); mul_v3_fl(dv2, mul * (tlen - key->length)); } if (k) { - add_v3_v3((key-1)->co, dv1); + add_v3_v3((key - 1)->co, dv1); } add_v3_v3v3(dv1, dv0, dv2); @@ -1062,13 +1062,13 @@ void recalc_lengths(PTCacheEdit *edit) { POINT_P; KEY_K; - if (edit==0) + if (edit == 0) return; LOOP_EDITED_POINTS { - key= point->keys; - for (k=0; ktotkey-1; k++, key++) { - key->length= len_v3v3(key->co, (key + 1)->co); + key = point->keys; + for (k = 0; k < point->totkey - 1; k++, key++) { + key->length = len_v3v3(key->co, (key + 1)->co); } } } @@ -1076,8 +1076,8 @@ void recalc_lengths(PTCacheEdit *edit) /* calculate a tree for finding nearest emitter's vertice */ void recalc_emitter_field(Object *ob, ParticleSystem *psys) { - DerivedMesh *dm=psys_get_modifier(ob, psys)->dm_final; - PTCacheEdit *edit= psys->edit; + DerivedMesh *dm = psys_get_modifier(ob, psys)->dm_final; + PTCacheEdit *edit = psys->edit; float *vec, *nor; int i, totface /*, totvert*/; @@ -1089,34 +1089,34 @@ void recalc_emitter_field(Object *ob, ParticleSystem *psys) BLI_kdtree_free(edit->emitter_field); - totface=dm->getNumTessFaces(dm); + totface = dm->getNumTessFaces(dm); /*totvert=dm->getNumVerts(dm);*/ /*UNSUED*/ - edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float), "emitter cosnos"); + edit->emitter_cosnos = MEM_callocN(totface * 6 * sizeof(float), "emitter cosnos"); - edit->emitter_field= BLI_kdtree_new(totface); + edit->emitter_field = BLI_kdtree_new(totface); - vec=edit->emitter_cosnos; - nor=vec+3; + vec = edit->emitter_cosnos; + nor = vec + 3; - for (i=0; igetTessFaceData(dm, i, CD_MFACE); + for (i = 0; i < totface; i++, vec += 6, nor += 6) { + MFace *mface = dm->getTessFaceData(dm, i, CD_MFACE); MVert *mvert; - mvert=dm->getVertData(dm, mface->v1, CD_MVERT); + mvert = dm->getVertData(dm, mface->v1, CD_MVERT); copy_v3_v3(vec, mvert->co); VECCOPY(nor, mvert->no); - mvert=dm->getVertData(dm, mface->v2, CD_MVERT); + mvert = dm->getVertData(dm, mface->v2, CD_MVERT); add_v3_v3v3(vec, vec, mvert->co); VECADD(nor, nor, mvert->no); - mvert=dm->getVertData(dm, mface->v3, CD_MVERT); + mvert = dm->getVertData(dm, mface->v3, CD_MVERT); add_v3_v3v3(vec, vec, mvert->co); VECADD(nor, nor, mvert->no); if (mface->v4) { - mvert=dm->getVertData(dm, mface->v4, CD_MVERT); + mvert = dm->getVertData(dm, mface->v4, CD_MVERT); add_v3_v3v3(vec, vec, mvert->co); VECADD(nor, nor, mvert->no); @@ -1135,22 +1135,25 @@ void recalc_emitter_field(Object *ob, ParticleSystem *psys) static void PE_update_selection(Main *bmain, Scene *scene, Object *ob, int useflag) { - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); HairKey *hkey; POINT_P; KEY_K; /* flag all particles to be updated if not using flag */ if (!useflag) - LOOP_POINTS + LOOP_POINTS { point->flag |= PEP_EDIT_RECALC; + } /* flush edit key flag to hair key flag to preserve selection * on save */ - if (edit->psys) LOOP_POINTS { - hkey = edit->psys->particles[p].hair; - LOOP_KEYS { - hkey->editflag= key->flag; - hkey++; + if (edit->psys) { + LOOP_POINTS { + hkey = edit->psys->particles[p].hair; + LOOP_KEYS { + hkey->editflag = key->flag; + hkey++; + } } } @@ -1158,23 +1161,24 @@ static void PE_update_selection(Main *bmain, Scene *scene, Object *ob, int usefl /* disable update flag */ - LOOP_POINTS + LOOP_POINTS { point->flag &= ~PEP_EDIT_RECALC; + } } void update_world_cos(Object *ob, PTCacheEdit *edit) { ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys); + ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); POINT_P; KEY_K; float hairmat[4][4]; - if (psys==0 || psys->edit==0 || psmd->dm_final==NULL) + if (psys == 0 || psys->edit == 0 || psmd->dm_final == NULL) return; LOOP_POINTS { if (!(psys->flag & PSYS_GLOBAL_HAIR)) - psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles+p, hairmat); + psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + p, hairmat); LOOP_KEYS { copy_v3_v3(key->world_co, key->co); @@ -1197,45 +1201,45 @@ static void update_velocities(PTCacheEdit *edit) LOOP_EDITED_POINTS { LOOP_KEYS { - if (k==0) { - dfra = *(key+1)->time - *key->time; + if (k == 0) { + dfra = *(key + 1)->time - *key->time; if (dfra <= 0.0f) continue; - sub_v3_v3v3(key->vel, (key+1)->co, key->co); + sub_v3_v3v3(key->vel, (key + 1)->co, key->co); - if (point->totkey>2) { - sub_v3_v3v3(vec1, (key+1)->co, (key+2)->co); + if (point->totkey > 2) { + sub_v3_v3v3(vec1, (key + 1)->co, (key + 2)->co); project_v3_v3v3(vec2, vec1, key->vel); sub_v3_v3v3(vec2, vec1, vec2); madd_v3_v3fl(key->vel, vec2, 0.5f); } } - else if (k==point->totkey-1) { - dfra = *key->time - *(key-1)->time; + else if (k == point->totkey - 1) { + dfra = *key->time - *(key - 1)->time; if (dfra <= 0.0f) continue; - sub_v3_v3v3(key->vel, key->co, (key-1)->co); + sub_v3_v3v3(key->vel, key->co, (key - 1)->co); - if (point->totkey>2) { - sub_v3_v3v3(vec1, (key-2)->co, (key-1)->co); + if (point->totkey > 2) { + sub_v3_v3v3(vec1, (key - 2)->co, (key - 1)->co); project_v3_v3v3(vec2, vec1, key->vel); sub_v3_v3v3(vec2, vec1, vec2); madd_v3_v3fl(key->vel, vec2, 0.5f); } } else { - dfra = *(key+1)->time - *(key-1)->time; + dfra = *(key + 1)->time - *(key - 1)->time; if (dfra <= 0.0f) continue; - sub_v3_v3v3(key->vel, (key+1)->co, (key-1)->co); + sub_v3_v3v3(key->vel, (key + 1)->co, (key - 1)->co); } - mul_v3_fl(key->vel, frs_sec/dfra); + mul_v3_fl(key->vel, frs_sec / dfra); } } } @@ -1244,7 +1248,7 @@ void PE_update_object(Main *bmain, Scene *scene, Object *ob, int useflag) { /* use this to do partial particle updates, not usable when adding or * removing, then a full redo is necessary and calling this may crash */ - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); PTCacheEdit *edit = PE_get_current(bmain, scene, ob); POINT_P; @@ -1257,8 +1261,8 @@ void PE_update_object(Main *bmain, Scene *scene, Object *ob, int useflag) point->flag |= PEP_EDIT_RECALC; } - /* do post process on particle edit keys */ - pe_iterate_lengths(scene, edit); + /* do post process on particle edit keys */ + pe_iterate_lengths(scene, edit); pe_deflect_emitter(scene, ob, edit); PE_apply_lengths(scene, edit); if (pe_x_mirror(ob)) @@ -1380,9 +1384,9 @@ static void select_action_apply(PTCacheEditPoint *point, PTCacheEditKey *key, in static int pe_select_all_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); POINT_P; KEY_K; int action = RNA_enum_get(op->ptr, "action"); @@ -1406,7 +1410,7 @@ static int pe_select_all_exec(bContext *C, wmOperator *op) } PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1423,7 +1427,7 @@ void PARTICLE_OT_select_all(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; WM_operator_properties_select_all(ot); } @@ -1434,9 +1438,9 @@ int PE_mouse_particles(bContext *C, const int mval[2], bool extend, bool deselec { Main *bmain = CTX_data_main(C); PEData data; - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); POINT_P; KEY_K; if (!PE_start_edit(edit)) @@ -1452,19 +1456,19 @@ int PE_mouse_particles(bContext *C, const int mval[2], bool extend, bool deselec } PE_set_view3d_data(C, &data); - data.mval= mval; + data.mval = mval; data.rad = ED_view3d_select_dist_px(); /* 1 = nearest only */ if (extend) - for_mouse_hit_keys(&data, extend_key_select, 1); + for_mouse_hit_keys(&data, extend_key_select, true); else if (deselect) - for_mouse_hit_keys(&data, deselect_key_select, 1); + for_mouse_hit_keys(&data, deselect_key_select, true); else - for_mouse_hit_keys(&data, toggle_key_select, 1); + for_mouse_hit_keys(&data, toggle_key_select, true); PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -1505,7 +1509,7 @@ static int select_roots_exec(bContext *C, wmOperator *op) foreach_point(&data, select_root); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -1522,7 +1526,7 @@ void PARTICLE_OT_select_roots(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ WM_operator_properties_select_action(ot, SEL_SELECT); @@ -1570,7 +1574,7 @@ static int select_tips_exec(bContext *C, wmOperator *op) foreach_point(&data, select_tip); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -1587,7 +1591,7 @@ void PARTICLE_OT_select_tips(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ WM_operator_properties_select_action(ot, SEL_SELECT); @@ -1633,7 +1637,7 @@ static int select_random_exec(bContext *C, wmOperator *op) LOOP_VISIBLE_POINTS { int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; LOOP_KEYS { - select_action_apply (point, key, flag); + select_action_apply(point, key, flag); } } break; @@ -1641,7 +1645,7 @@ static int select_random_exec(bContext *C, wmOperator *op) LOOP_VISIBLE_POINTS { LOOP_VISIBLE_KEYS { int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; - select_action_apply (point, key, flag); + select_action_apply(point, key, flag); } } break; @@ -1650,7 +1654,7 @@ static int select_random_exec(bContext *C, wmOperator *op) BLI_rng_free(rng); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -1667,12 +1671,12 @@ void PARTICLE_OT_select_random(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ WM_operator_properties_select_random(ot); - ot->prop = RNA_def_enum (ot->srna, "type", select_random_type_items, RAN_HAIR, - "Type", "Select either hair or points"); + ot->prop = RNA_def_enum(ot->srna, "type", select_random_type_items, RAN_HAIR, + "Type", "Select either hair or points"); } /************************ select linked operator ************************/ @@ -1688,13 +1692,13 @@ static int select_linked_exec(bContext *C, wmOperator *op) mval[1] = location[1]; PE_set_view3d_data(C, &data); - data.mval= mval; - data.rad=75.0f; - data.select= !RNA_boolean_get(op->ptr, "deselect"); + data.mval = mval; + data.rad = 75.0f; + data.select = !RNA_boolean_get(op->ptr, "deselect"); - for_mouse_hit_keys(&data, select_keys, 1); /* nearest only */ + for_mouse_hit_keys(&data, select_keys, true); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -1718,7 +1722,7 @@ void PARTICLE_OT_select_linked(wmOperatorType *ot) ot->poll = PE_poll_view3d; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them"); @@ -1738,12 +1742,12 @@ void PE_deselect_all_visible(PTCacheEdit *edit) } } -int PE_border_select(bContext *C, rcti *rect, bool select, bool extend) +int PE_border_select(bContext *C, const rcti *rect, bool select, bool extend) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); PEData data; if (!PE_start_edit(edit)) @@ -1753,13 +1757,13 @@ int PE_border_select(bContext *C, rcti *rect, bool select, bool extend) PE_deselect_all_visible(edit); PE_set_view3d_data(C, &data); - data.rect= rect; - data.select= select; + data.rect = rect; + data.select = select; - for_mouse_hit_keys(&data, select_key, 0); + for_mouse_hit_keys(&data, select_key, false); PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1769,23 +1773,23 @@ int PE_border_select(bContext *C, rcti *rect, bool select, bool extend) int PE_circle_select(bContext *C, int selecting, const int mval[2], float rad) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); PEData data; if (!PE_start_edit(edit)) return OPERATOR_FINISHED; PE_set_view3d_data(C, &data); - data.mval= mval; - data.rad= rad; - data.select= selecting; + data.mval = mval; + data.rad = rad; + data.select = selecting; - for_mouse_hit_keys(&data, select_key, 0); + for_mouse_hit_keys(&data, select_key, false); PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1795,10 +1799,10 @@ int PE_circle_select(bContext *C, int selecting, const int mval[2], float rad) int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool extend, bool select) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - ARegion *ar= CTX_wm_region(C); - ParticleEditSettings *pset= PE_settings(scene); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + ARegion *ar = CTX_wm_region(C); + ParticleEditSettings *pset = PE_settings(scene); PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys = edit->psys; ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); @@ -1823,7 +1827,7 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool if (edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR)) psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); - if (pset->selectmode==SCE_SELECT_POINT) { + if (pset->selectmode == SCE_SELECT_POINT) { LOOP_KEYS { copy_v3_v3(co, key->co); mul_m4_v3(mat, co); @@ -1846,9 +1850,9 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool } } } - else if (pset->selectmode==SCE_SELECT_END) { + else if (pset->selectmode == SCE_SELECT_END) { if (point->totkey) { - key= point->keys + point->totkey - 1; + key = point->keys + point->totkey - 1; copy_v3_v3(co, key->co); mul_m4_v3(mat, co); @@ -1874,7 +1878,7 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool } PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1884,9 +1888,9 @@ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, bool static int hide_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Object *ob= CTX_data_active_object(C); - Scene *scene= CTX_data_scene(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); POINT_P; KEY_K; if (RNA_enum_get(op->ptr, "unselected")) { @@ -1894,8 +1898,9 @@ static int hide_exec(bContext *C, wmOperator *op) point->flag |= PEP_HIDE; point->flag |= PEP_EDIT_RECALC; - LOOP_KEYS + LOOP_KEYS { key->flag &= ~PEK_SELECT; + } } } else { @@ -1903,13 +1908,14 @@ static int hide_exec(bContext *C, wmOperator *op) point->flag |= PEP_HIDE; point->flag |= PEP_EDIT_RECALC; - LOOP_KEYS + LOOP_KEYS { key->flag &= ~PEK_SELECT; + } } } PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1926,7 +1932,7 @@ void PARTICLE_OT_hide(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected"); @@ -1937,8 +1943,8 @@ void PARTICLE_OT_hide(wmOperatorType *ot) static int reveal_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Object *ob= CTX_data_active_object(C); - Scene *scene= CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); PTCacheEdit *edit = PE_get_current(bmain, scene, ob); const bool select = RNA_boolean_get(op->ptr, "select"); POINT_P; KEY_K; @@ -1955,7 +1961,7 @@ static int reveal_exec(bContext *C, wmOperator *op) } PE_update_selection(bmain, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); return OPERATOR_FINISHED; } @@ -1972,7 +1978,7 @@ void PARTICLE_OT_reveal(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ RNA_def_boolean(ot->srna, "select", true, "Select", ""); @@ -1982,28 +1988,28 @@ void PARTICLE_OT_reveal(wmOperatorType *ot) static void select_less_keys(PEData *data, int point_index) { - PTCacheEdit *edit= data->edit; + PTCacheEdit *edit = data->edit; PTCacheEditPoint *point = edit->points + point_index; KEY_K; LOOP_SELECTED_KEYS { - if (k==0) { - if (((key+1)->flag&PEK_SELECT)==0) + if (k == 0) { + if (((key + 1)->flag & PEK_SELECT) == 0) key->flag |= PEK_TAG; } - else if (k==point->totkey-1) { - if (((key-1)->flag&PEK_SELECT)==0) + else if (k == point->totkey - 1) { + if (((key - 1)->flag & PEK_SELECT) == 0) key->flag |= PEK_TAG; } else { - if ((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0) + if ((((key - 1)->flag & (key + 1)->flag) & PEK_SELECT) == 0) key->flag |= PEK_TAG; } } LOOP_KEYS { - if (key->flag&PEK_TAG) { - key->flag &= ~(PEK_TAG|PEK_SELECT); + if (key->flag & PEK_TAG) { + key->flag &= ~(PEK_TAG | PEK_SELECT); point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ } } @@ -2017,7 +2023,7 @@ static int select_less_exec(bContext *C, wmOperator *UNUSED(op)) foreach_point(&data, select_less_keys); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -2034,36 +2040,36 @@ void PARTICLE_OT_select_less(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ select more operator ************************/ static void select_more_keys(PEData *data, int point_index) { - PTCacheEdit *edit= data->edit; + PTCacheEdit *edit = data->edit; PTCacheEditPoint *point = edit->points + point_index; KEY_K; LOOP_KEYS { if (key->flag & PEK_SELECT) continue; - if (k==0) { - if ((key+1)->flag&PEK_SELECT) + if (k == 0) { + if ((key + 1)->flag & PEK_SELECT) key->flag |= PEK_TAG; } - else if (k==point->totkey-1) { - if ((key-1)->flag&PEK_SELECT) + else if (k == point->totkey - 1) { + if ((key - 1)->flag & PEK_SELECT) key->flag |= PEK_TAG; } else { - if (((key-1)->flag | (key+1)->flag) & PEK_SELECT) + if (((key - 1)->flag | (key + 1)->flag) & PEK_SELECT) key->flag |= PEK_TAG; } } LOOP_KEYS { - if (key->flag&PEK_TAG) { + if (key->flag & PEK_TAG) { key->flag &= ~PEK_TAG; key->flag |= PEK_SELECT; point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ @@ -2079,7 +2085,7 @@ static int select_more_exec(bContext *C, wmOperator *UNUSED(op)) foreach_point(&data, select_more_keys); PE_update_selection(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); return OPERATOR_FINISHED; } @@ -2096,17 +2102,17 @@ void PARTICLE_OT_select_more(wmOperatorType *ot) ot->poll = PE_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ rekey operator ************************/ static void rekey_particle(PEData *data, int pa_index) { - PTCacheEdit *edit= data->edit; - ParticleSystem *psys= edit->psys; - ParticleSimulationData sim= {0}; - ParticleData *pa= psys->particles + pa_index; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSimulationData sim = {0}; + ParticleData *pa = psys->particles + pa_index; PTCacheEditPoint *point = edit->points + pa_index; ParticleKey state; HairKey *key, *new_keys, *okey; @@ -2114,46 +2120,46 @@ static void rekey_particle(PEData *data, int pa_index) float dval, sta, end; int k; - sim.scene= data->scene; - sim.ob= data->ob; - sim.psys= edit->psys; + sim.scene = data->scene; + sim.ob = data->ob; + sim.psys = edit->psys; pa->flag |= PARS_REKEY; - key= new_keys= MEM_callocN(data->totrekey * sizeof(HairKey), "Hair re-key keys"); + key = new_keys = MEM_callocN(data->totrekey * sizeof(HairKey), "Hair re-key keys"); okey = pa->hair; /* root and tip stay the same */ copy_v3_v3(key->co, okey->co); copy_v3_v3((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co); - sta= key->time= okey->time; - end= (key + data->totrekey - 1)->time= (okey + pa->totkey - 1)->time; - dval= (end - sta) / (float)(data->totrekey - 1); + sta = key->time = okey->time; + end = (key + data->totrekey - 1)->time = (okey + pa->totkey - 1)->time; + dval = (end - sta) / (float)(data->totrekey - 1); /* interpolate new keys from old ones */ - for (k=1, key++; ktotrekey-1; k++, key++) { - state.time= (float)k / (float)(data->totrekey-1); + for (k = 1, key++; k < data->totrekey - 1; k++, key++) { + state.time = (float)k / (float)(data->totrekey - 1); psys_get_particle_on_path(&sim, pa_index, &state, 0); copy_v3_v3(key->co, state.co); - key->time= sta + k * dval; + key->time = sta + k * dval; } /* replace keys */ if (pa->hair) MEM_freeN(pa->hair); - pa->hair= new_keys; + pa->hair = new_keys; - point->totkey=pa->totkey=data->totrekey; + point->totkey = pa->totkey = data->totrekey; if (point->keys) MEM_freeN(point->keys); - ekey= point->keys= MEM_callocN(pa->totkey * sizeof(PTCacheEditKey), "Hair re-key edit keys"); + ekey = point->keys = MEM_callocN(pa->totkey * sizeof(PTCacheEditKey), "Hair re-key edit keys"); - for (k=0, key=pa->hair; ktotkey; k++, key++, ekey++) { - ekey->co= key->co; - ekey->time= &key->time; + for (k = 0, key = pa->hair; k < pa->totkey; k++, key++, ekey++) { + ekey->co = key->co; + ekey->time = &key->time; ekey->flag |= PEK_SELECT; if (!(psys->flag & PSYS_GLOBAL_HAIR)) ekey->flag |= PEK_USE_WCO; @@ -2169,14 +2175,14 @@ static int rekey_exec(bContext *C, wmOperator *op) PE_set_data(C, &data); - data.dval= 1.0f / (float)(data.totrekey-1); - data.totrekey= RNA_int_get(op->ptr, "keys_number"); + data.dval = 1.0f / (float)(data.totrekey - 1); + data.totrekey = RNA_int_get(op->ptr, "keys_number"); foreach_selected_point(&data, rekey_particle); recalc_lengths(data.edit); PE_update_object(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); return OPERATOR_FINISHED; } @@ -2194,7 +2200,7 @@ void PARTICLE_OT_rekey(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ RNA_def_int(ot->srna, "keys_number", 2, 2, INT_MAX, "Number of Keys", "", 2, 100); @@ -2202,9 +2208,9 @@ void PARTICLE_OT_rekey(wmOperatorType *ot) static void rekey_particle_to_time(Main *bmain, Scene *scene, Object *ob, int pa_index, float path_time) { - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys; - ParticleSimulationData sim= {0}; + ParticleSimulationData sim = {0}; ParticleData *pa; ParticleKey state; HairKey *new_keys, *key; @@ -2215,19 +2221,19 @@ static void rekey_particle_to_time(Main *bmain, Scene *scene, Object *ob, int pa psys = edit->psys; - sim.scene= scene; - sim.ob= ob; - sim.psys= psys; + sim.scene = scene; + sim.ob = ob; + sim.psys = psys; - pa= psys->particles + pa_index; + pa = psys->particles + pa_index; pa->flag |= PARS_REKEY; - key= new_keys= MEM_dupallocN(pa->hair); + key = new_keys = MEM_dupallocN(pa->hair); /* interpolate new keys from old ones (roots stay the same) */ - for (k=1, key++; k < pa->totkey; k++, key++) { - state.time= path_time * (float)k / (float)(pa->totkey-1); + for (k = 1, key++; k < pa->totkey; k++, key++) { + state.time = path_time * (float)k / (float)(pa->totkey - 1); psys_get_particle_on_path(&sim, pa_index, &state, 0); copy_v3_v3(key->co, state.co); } @@ -2235,12 +2241,12 @@ static void rekey_particle_to_time(Main *bmain, Scene *scene, Object *ob, int pa /* replace hair keys */ if (pa->hair) MEM_freeN(pa->hair); - pa->hair= new_keys; + pa->hair = new_keys; /* update edit pointers */ - for (k=0, key=pa->hair, ekey=edit->points[pa_index].keys; ktotkey; k++, key++, ekey++) { - ekey->co= key->co; - ekey->time= &key->time; + for (k = 0, key = pa->hair, ekey = edit->points[pa_index].keys; k < pa->totkey; k++, key++, ekey++) { + ekey->co = key->co; + ekey->time = &key->time; } pa->flag &= ~PARS_REKEY; @@ -2251,15 +2257,15 @@ static void rekey_particle_to_time(Main *bmain, Scene *scene, Object *ob, int pa static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) { PTCacheEdit *edit = psys->edit; - ParticleData *pa, *npa=0, *new_pars=0; + ParticleData *pa, *npa = 0, *new_pars = 0; POINT_P; - PTCacheEditPoint *npoint=0, *new_points=0; + PTCacheEditPoint *npoint = 0, *new_points = 0; ParticleSystemModifierData *psmd; - int i, new_totpart= psys->totpart, removed= 0; + int i, new_totpart = psys->totpart, removed = 0; if (mirror) { /* mirror tags */ - psmd= psys_get_modifier(ob, psys); + psmd = psys_get_modifier(ob, psys); LOOP_TAGGED_POINTS { PE_mirror_particle(ob, psmd->dm_final, psys, psys->particles + p, NULL); @@ -2273,8 +2279,8 @@ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) if (new_totpart != psys->totpart) { if (new_totpart) { - npa= new_pars= MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array"); - npoint= new_points= MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array"); + npa = new_pars = MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array"); + npoint = new_points = MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array"); if (ELEM(NULL, new_pars, new_points)) { /* allocation error! */ @@ -2286,9 +2292,9 @@ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) } } - pa= psys->particles; - point= edit->points; - for (i=0; itotpart; i++, pa++, point++) { + pa = psys->particles; + point = edit->points; + for (i = 0; i < psys->totpart; i++, pa++, point++) { if (point->flag & PEP_TAG) { if (point->keys) MEM_freeN(point->keys); @@ -2304,23 +2310,23 @@ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) } if (psys->particles) MEM_freeN(psys->particles); - psys->particles= new_pars; + psys->particles = new_pars; if (edit->points) MEM_freeN(edit->points); - edit->points= new_points; + edit->points = new_points; if (edit->mirror_cache) { MEM_freeN(edit->mirror_cache); - edit->mirror_cache= NULL; + edit->mirror_cache = NULL; } if (psys->child) { MEM_freeN(psys->child); - psys->child= NULL; - psys->totchild=0; + psys->child = NULL; + psys->totchild = 0; } - edit->totpoint= psys->totpart= new_totpart; + edit->totpoint = psys->totpart = new_totpart; } return removed; @@ -2328,9 +2334,9 @@ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) static void remove_tagged_keys(Object *ob, ParticleSystem *psys) { - PTCacheEdit *edit= psys->edit; + PTCacheEdit *edit = psys->edit; ParticleData *pa; - HairKey *hkey, *nhkey, *new_hkeys=0; + HairKey *hkey, *nhkey, *new_hkeys = 0; POINT_P; KEY_K; PTCacheEditKey *nkey, *new_keys; ParticleSystemModifierData *psmd; @@ -2338,7 +2344,7 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) if (pe_x_mirror(ob)) { /* mirror key tags */ - psmd= psys_get_modifier(ob, psys); + psmd = psys_get_modifier(ob, psys); LOOP_POINTS { LOOP_TAGGED_KEYS { @@ -2349,7 +2355,7 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) } LOOP_POINTS { - new_totkey= point->totkey; + new_totkey = point->totkey; LOOP_TAGGED_KEYS { new_totkey--; } @@ -2361,17 +2367,17 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) LOOP_POINTS { pa = psys->particles + p; - new_totkey= pa->totkey; + new_totkey = pa->totkey; LOOP_TAGGED_KEYS { new_totkey--; } if (new_totkey != pa->totkey) { - nhkey= new_hkeys= MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys"); - nkey= new_keys= MEM_callocN(new_totkey*sizeof(PTCacheEditKey), "particle edit keys"); + nhkey = new_hkeys = MEM_callocN(new_totkey * sizeof(HairKey), "HairKeys"); + nkey = new_keys = MEM_callocN(new_totkey * sizeof(PTCacheEditKey), "particle edit keys"); - hkey= pa->hair; + hkey = pa->hair; LOOP_KEYS { while (key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) { key++; @@ -2381,11 +2387,11 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) if (hkey < pa->hair + pa->totkey) { copy_v3_v3(nhkey->co, hkey->co); nhkey->editflag = hkey->editflag; - nhkey->time= hkey->time; - nhkey->weight= hkey->weight; + nhkey->time = hkey->time; + nhkey->weight = hkey->weight; - nkey->co= nhkey->co; - nkey->time= &nhkey->time; + nkey->co = nhkey->co; + nkey->time = &nhkey->time; /* these can be copied from old edit keys */ nkey->flag = key->flag; nkey->ftime = key->ftime; @@ -2403,10 +2409,10 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) if (point->keys) MEM_freeN(point->keys); - pa->hair= new_hkeys; - point->keys= new_keys; + pa->hair = new_hkeys; + point->keys = new_keys; - point->totkey= pa->totkey= new_totkey; + point->totkey = pa->totkey = new_totkey; /* flag for recalculating length */ point->flag |= PEP_EDIT_RECALC; @@ -2419,56 +2425,56 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) /* works like normal edit mode subdivide, inserts keys between neighboring selected keys */ static void subdivide_particle(PEData *data, int pa_index) { - PTCacheEdit *edit= data->edit; - ParticleSystem *psys= edit->psys; - ParticleSimulationData sim= {0}; - ParticleData *pa= psys->particles + pa_index; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSimulationData sim = {0}; + ParticleData *pa = psys->particles + pa_index; PTCacheEditPoint *point = edit->points + pa_index; ParticleKey state; HairKey *key, *nkey, *new_keys; PTCacheEditKey *ekey, *nekey, *new_ekeys; int k; - short totnewkey=0; + short totnewkey = 0; float endtime; - sim.scene= data->scene; - sim.ob= data->ob; - sim.psys= edit->psys; + sim.scene = data->scene; + sim.ob = data->ob; + sim.psys = edit->psys; - for (k=0, ekey=point->keys; ktotkey-1; k++, ekey++) { - if (ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT) + for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, ekey++) { + if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) totnewkey++; } - if (totnewkey==0) return; + if (totnewkey == 0) return; pa->flag |= PARS_REKEY; - nkey= new_keys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)), "Hair subdivide keys"); - nekey= new_ekeys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(PTCacheEditKey)), "Hair subdivide edit keys"); + nkey = new_keys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(HairKey)), "Hair subdivide keys"); + nekey = new_ekeys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(PTCacheEditKey)), "Hair subdivide edit keys"); key = pa->hair; - endtime= key[pa->totkey-1].time; + endtime = key[pa->totkey - 1].time; - for (k=0, ekey=point->keys; ktotkey-1; k++, key++, ekey++) { + for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, key++, ekey++) { memcpy(nkey, key, sizeof(HairKey)); memcpy(nekey, ekey, sizeof(PTCacheEditKey)); - nekey->co= nkey->co; - nekey->time= &nkey->time; + nekey->co = nkey->co; + nekey->time = &nkey->time; nkey++; nekey++; - if (ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT) { + if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) { nkey->time = (key->time + (key + 1)->time) * 0.5f; - state.time = (endtime != 0.0f) ? nkey->time / endtime: 0.0f; + state.time = (endtime != 0.0f) ? nkey->time / endtime : 0.0f; psys_get_particle_on_path(&sim, pa_index, &state, 0); copy_v3_v3(nkey->co, state.co); - nekey->co= nkey->co; + nekey->co = nkey->co; nekey->time = &nkey->time; nekey->flag |= PEK_SELECT; if (!(psys->flag & PSYS_GLOBAL_HAIR)) @@ -2482,16 +2488,16 @@ static void subdivide_particle(PEData *data, int pa_index) memcpy(nkey, key, sizeof(HairKey)); memcpy(nekey, ekey, sizeof(PTCacheEditKey)); - nekey->co= nkey->co; - nekey->time= &nkey->time; + nekey->co = nkey->co; + nekey->time = &nkey->time; if (pa->hair) MEM_freeN(pa->hair); - pa->hair= new_keys; + pa->hair = new_keys; if (point->keys) MEM_freeN(point->keys); - point->keys= new_ekeys; + point->keys = new_ekeys; point->totkey = pa->totkey = pa->totkey + totnewkey; point->flag |= PEP_EDIT_RECALC; @@ -2507,7 +2513,7 @@ static int subdivide_exec(bContext *C, wmOperator *UNUSED(op)) recalc_lengths(data.edit); PE_update_object(data.bmain, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); return OPERATOR_FINISHED; } @@ -2524,7 +2530,7 @@ void PARTICLE_OT_subdivide(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ remove doubles opertor *********************/ @@ -2532,32 +2538,32 @@ void PARTICLE_OT_subdivide(wmOperatorType *ot) static int remove_doubles_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys = edit->psys; ParticleSystemModifierData *psmd; KDTree *tree; KDTreeNearest nearest[10]; POINT_P; - float mat[4][4], co[3], threshold= RNA_float_get(op->ptr, "threshold"); + float mat[4][4], co[3], threshold = RNA_float_get(op->ptr, "threshold"); int n, totn, removed, totremoved; if (psys->flag & PSYS_GLOBAL_HAIR) return OPERATOR_CANCELLED; - edit= psys->edit; - psmd= psys_get_modifier(ob, psys); - totremoved= 0; + edit = psys->edit; + psmd = psys_get_modifier(ob, psys); + totremoved = 0; do { - removed= 0; + removed = 0; - tree=BLI_kdtree_new(psys->totpart); + tree = BLI_kdtree_new(psys->totpart); /* insert particles into kd tree */ LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd->dm_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_object(ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); copy_v3_v3(co, point->keys->co); mul_m4_v3(mat, co); BLI_kdtree_insert(tree, p, co); @@ -2567,13 +2573,13 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) /* tag particles to be removed */ LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd->dm_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_object(ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); copy_v3_v3(co, point->keys->co); mul_m4_v3(mat, co); totn = BLI_kdtree_find_nearest_n(tree, co, nearest, 10); - for (n=0; n p && nearest[n].dist < threshold) { if (!(point->flag & PEP_TAG)) { @@ -2597,7 +2603,7 @@ static int remove_doubles_exec(bContext *C, wmOperator *op) BKE_reportf(op->reports, RPT_INFO, "Removed %d double particles", totremoved); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); return OPERATOR_FINISHED; } @@ -2614,7 +2620,7 @@ void PARTICLE_OT_remove_doubles(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ RNA_def_float(ot->srna, "threshold", 0.0002f, 0.0f, FLT_MAX, @@ -2625,32 +2631,32 @@ void PARTICLE_OT_remove_doubles(wmOperatorType *ot) static int weight_set_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - ParticleEditSettings *pset= PE_settings(scene); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + ParticleEditSettings *pset = PE_settings(scene); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys = edit->psys; POINT_P; KEY_K; HairKey *hkey; float weight; - ParticleBrushData *brush= &pset->brush[pset->brushtype]; - float factor= RNA_float_get(op->ptr, "factor"); + ParticleBrushData *brush = &pset->brush[pset->brushtype]; + float factor = RNA_float_get(op->ptr, "factor"); - weight= brush->strength; - edit= psys->edit; + weight = brush->strength; + edit = psys->edit; LOOP_SELECTED_POINTS { - ParticleData *pa= psys->particles + p; + ParticleData *pa = psys->particles + p; LOOP_SELECTED_KEYS { - hkey= pa->hair + k; - hkey->weight= interpf(weight, hkey->weight, factor); + hkey = pa->hair + k; + hkey->weight = interpf(weight, hkey->weight, factor); } } DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); return OPERATOR_FINISHED; } @@ -2667,7 +2673,7 @@ void PARTICLE_OT_weight_set(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; RNA_def_float(ot->srna, "factor", 1, 0, 1, "Factor", "Interpolation factor between current brush weight, and keys' weights", 0, 1); @@ -2678,13 +2684,13 @@ void PARTICLE_OT_weight_set(wmOperatorType *ot) static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata)) { Scene *scene = CTX_data_scene(C); - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); ParticleBrushData *brush; if (pset->brushtype < 0) return; - brush= &pset->brush[pset->brushtype]; + brush = &pset->brush[pset->brushtype]; if (brush) { glPushMatrix(); @@ -2694,7 +2700,7 @@ static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata) glColor4ub(255, 255, 255, 128); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); - glutil_draw_lined_arc(0.0, M_PI*2.0, pe_brush_size_get(scene, brush), 40); + glutil_draw_lined_arc(0.0, M_PI * 2.0, pe_brush_size_get(scene, brush), 40); glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); @@ -2704,14 +2710,14 @@ static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata) static void toggle_particle_cursor(bContext *C, int enable) { - ParticleEditSettings *pset= PE_settings(CTX_data_scene(C)); + ParticleEditSettings *pset = PE_settings(CTX_data_scene(C)); if (pset->paintcursor && !enable) { WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor); pset->paintcursor = NULL; } else if (enable) - pset->paintcursor= WM_paint_cursor_activate(CTX_wm_manager(C), PE_poll_view3d, brush_drawcursor, NULL); + pset->paintcursor = WM_paint_cursor_activate(CTX_wm_manager(C), PE_poll_view3d, brush_drawcursor, NULL); } /*************************** delete operator **************************/ @@ -2721,18 +2727,19 @@ enum { DEL_PARTICLE, DEL_KEY }; static const EnumPropertyItem delete_type_items[] = { {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""}, {DEL_KEY, "KEY", 0, "Key", ""}, - {0, NULL, 0, NULL, NULL}}; + {0, NULL, 0, NULL, NULL} +}; static void set_delete_particle(PEData *data, int pa_index) { - PTCacheEdit *edit= data->edit; + PTCacheEdit *edit = data->edit; edit->points[pa_index].flag |= PEP_TAG; } static void set_delete_particle_key(PEData *data, int pa_index, int key_index) { - PTCacheEdit *edit= data->edit; + PTCacheEdit *edit = data->edit; edit->points[pa_index].keys[key_index].flag |= PEK_TAG; } @@ -2740,7 +2747,7 @@ static void set_delete_particle_key(PEData *data, int pa_index, int key_index) static int delete_exec(bContext *C, wmOperator *op) { PEData data; - int type= RNA_enum_get(op->ptr, "type"); + int type = RNA_enum_get(op->ptr, "type"); PE_set_data(C, &data); @@ -2756,7 +2763,7 @@ static int delete_exec(bContext *C, wmOperator *op) } DAG_id_tag_update(&data.ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); return OPERATOR_FINISHED; } @@ -2774,7 +2781,7 @@ void PARTICLE_OT_delete(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ ot->prop = RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PARTICLE, "Type", "Delete a full particle or only keys"); @@ -2784,9 +2791,9 @@ void PARTICLE_OT_delete(wmOperatorType *ot) static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) { - Mesh *me= (Mesh *)(ob->data); + Mesh *me = (Mesh *)(ob->data); ParticleSystemModifierData *psmd; - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys = edit->psys; ParticleData *pa, *newpa, *new_pars; PTCacheEditPoint *newpoint, *new_points; @@ -2798,7 +2805,7 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) if (psys->flag & PSYS_GLOBAL_HAIR) return; - psmd= psys_get_modifier(ob, psys); + psmd = psys_get_modifier(ob, psys); if (!psmd->dm_final) return; @@ -2814,8 +2821,8 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) if (!edit->mirror_cache) PE_update_mirror_cache(ob, psys); - totpart= psys->totpart; - newtotpart= psys->totpart; + totpart = psys->totpart; + newtotpart = psys->totpart; LOOP_VISIBLE_POINTS { pa = psys->particles + p; @@ -2831,7 +2838,7 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) } } - if ((point->flag & PEP_TAG) && mirrorfaces[pa->num*2] != -1) + if ((point->flag & PEP_TAG) && mirrorfaces[pa->num * 2] != -1) newtotpart++; } @@ -2839,33 +2846,33 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) MFace *mtessface = use_dm_final_indices ? psmd->dm_final->getTessFaceArray(psmd->dm_final) : me->mface; /* allocate new arrays and copy existing */ - new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new"); - new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint), "PTCacheEditPoint new"); + new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); + new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), "PTCacheEditPoint new"); if (psys->particles) { - memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData)); + memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData)); MEM_freeN(psys->particles); } - psys->particles= new_pars; + psys->particles = new_pars; if (edit->points) { - memcpy(new_points, edit->points, totpart*sizeof(PTCacheEditPoint)); + memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint)); MEM_freeN(edit->points); } - edit->points= new_points; + edit->points = new_points; if (edit->mirror_cache) { MEM_freeN(edit->mirror_cache); - edit->mirror_cache= NULL; + edit->mirror_cache = NULL; } - edit->totpoint= psys->totpart= newtotpart; + edit->totpoint = psys->totpart = newtotpart; /* create new elements */ - newpa= psys->particles + totpart; - newpoint= edit->points + totpart; + newpa = psys->particles + totpart; + newpoint = edit->points + totpart; - for (p=0, point=edit->points; ppoints; p < totpart; p++, point++) { pa = psys->particles + p; const int pa_num = pa->num; @@ -2876,13 +2883,13 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) continue; /* duplicate */ - *newpa= *pa; - *newpoint= *point; - if (pa->hair) newpa->hair= MEM_dupallocN(pa->hair); - if (point->keys) newpoint->keys= MEM_dupallocN(point->keys); + *newpa = *pa; + *newpoint = *point; + if (pa->hair) newpa->hair = MEM_dupallocN(pa->hair); + if (point->keys) newpoint->keys = MEM_dupallocN(point->keys); /* rotate weights according to vertex index rotation */ - rotation= mirrorfaces[pa_num * 2 + 1]; + rotation = mirrorfaces[pa_num * 2 + 1]; newpa->fuv[0] = pa->fuv[2]; newpa->fuv[1] = pa->fuv[1]; newpa->fuv[2] = pa->fuv[0]; @@ -2905,14 +2912,14 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) } else { newpa->num_dmcache = psys_particle_dm_face_lookup( - psmd->dm_final, psmd->dm_deformed, newpa->num, newpa->fuv, NULL); + psmd->dm_final, psmd->dm_deformed, newpa->num, newpa->fuv, NULL); } /* update edit key pointers */ - key= newpoint->keys; - for (k=0, hkey=newpa->hair; ktotkey; k++, hkey++, key++) { - key->co= hkey->co; - key->time= &hkey->time; + key = newpoint->keys; + for (k = 0, hkey = newpa->hair; k < newpa->totkey; k++, hkey++, key++) { + key->co = hkey->co; + key->time = &hkey->time; } /* map key positions as mirror over x axis */ @@ -2933,14 +2940,14 @@ static void PE_mirror_x(Main *bmain, Scene *scene, Object *ob, int tagged) static int mirror_exec(bContext *C, wmOperator *UNUSED(op)) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); PE_mirror_x(bmain, scene, ob, 0); update_world_cos(ob, edit); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); return OPERATOR_FINISHED; @@ -2958,19 +2965,19 @@ void PARTICLE_OT_mirror(wmOperatorType *ot) ot->poll = PE_hair_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************* brush edit callbacks ********************/ static void brush_comb(PEData *data, float UNUSED(mat[4][4]), float imat[4][4], int point_index, int key_index, PTCacheEditKey *key) { - ParticleEditSettings *pset= PE_settings(data->scene); + ParticleEditSettings *pset = PE_settings(data->scene); float cvec[3], fac; if (pset->flag & PE_LOCK_FIRST && key_index == 0) return; - fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac); + fac = (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac); copy_v3_v3(cvec, data->dvec); mul_mat3_m4_v3(imat, cvec); @@ -2983,13 +2990,13 @@ static void brush_comb(PEData *data, float UNUSED(mat[4][4]), float imat[4][4], static void brush_cut(PEData *data, int pa_index) { PTCacheEdit *edit = data->edit; - ARegion *ar= data->vc.ar; - Object *ob= data->ob; - ParticleEditSettings *pset= PE_settings(data->scene); - ParticleCacheKey *key= edit->pathcache[pa_index]; - float rad2, cut_time= 1.0; + ARegion *ar = data->vc.ar; + Object *ob = data->ob; + ParticleEditSettings *pset = PE_settings(data->scene); + ParticleCacheKey *key = edit->pathcache[pa_index]; + float rad2, cut_time = 1.0; float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv; - int k, cut, keys= (int)pow(2.0, (double)pset->draw_step); + int k, cut, keys = (int)pow(2.0, (double)pset->draw_step); int screen_co[2]; /* blunt scissors */ @@ -3002,27 +3009,27 @@ static void brush_cut(PEData *data, int pa_index) if (ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) return; - rad2= data->rad * data->rad; + rad2 = data->rad * data->rad; - cut=0; + cut = 0; x0 = (float)screen_co[0]; x1 = (float)screen_co[1]; - o0= (float)data->mval[0]; - o1= (float)data->mval[1]; + o0 = (float)data->mval[0]; + o1 = (float)data->mval[1]; - xo0= x0 - o0; - xo1= x1 - o1; + xo0 = x0 - o0; + xo1 = x1 - o1; /* check if root is inside circle */ - if (xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co, screen_co)) { - cut_time= -1.0f; - cut= 1; + if (xo0 * xo0 + xo1 * xo1 < rad2 && key_test_depth(data, key->co, screen_co)) { + cut_time = -1.0f; + cut = 1; } else { /* calculate path time closest to root that was inside the circle */ - for (k=1, key++; k<=keys; k++, key++) { + for (k = 1, key++; k <= keys; k++, key++) { if ((ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) || key_test_depth(data, key->co, screen_co) == 0) @@ -3030,32 +3037,32 @@ static void brush_cut(PEData *data, int pa_index) x0 = (float)screen_co[0]; x1 = (float)screen_co[1]; - xo0= x0 - o0; - xo1= x1 - o1; + xo0 = x0 - o0; + xo1 = x1 - o1; continue; } v0 = (float)screen_co[0] - x0; v1 = (float)screen_co[1] - x1; - dv= v0*v0 + v1*v1; + dv = v0 * v0 + v1 * v1; - d= (v0*xo1 - v1*xo0); + d = (v0 * xo1 - v1 * xo0); - d= dv * rad2 - d*d; + d = dv * rad2 - d * d; if (d > 0.0f) { - d= sqrtf(d); + d = sqrtf(d); - cut_time= -(v0*xo0 + v1*xo1 + d); + cut_time = -(v0 * xo0 + v1 * xo1 + d); if (cut_time > 0.0f) { cut_time /= dv; if (cut_time < 1.0f) { - cut_time += (float)(k-1); + cut_time += (float)(k - 1); cut_time /= (float)keys; - cut= 1; + cut = 1; break; } } @@ -3064,8 +3071,8 @@ static void brush_cut(PEData *data, int pa_index) x0 = (float)screen_co[0]; x1 = (float)screen_co[1]; - xo0= x0 - o0; - xo1= x1 - o1; + xo0 = x0 - o0; + xo1 = x1 - o1; } } @@ -3082,20 +3089,20 @@ static void brush_cut(PEData *data, int pa_index) static void brush_length(PEData *data, int point_index) { - PTCacheEdit *edit= data->edit; + PTCacheEdit *edit = data->edit; PTCacheEditPoint *point = edit->points + point_index; KEY_K; float dvec[3], pvec[3] = {0.0f, 0.0f, 0.0f}; LOOP_KEYS { - if (k==0) { + if (k == 0) { copy_v3_v3(pvec, key->co); } else { sub_v3_v3v3(dvec, key->co, pvec); copy_v3_v3(pvec, key->co); mul_v3_fl(dvec, data->growfac); - add_v3_v3v3(key->co, (key-1)->co, dvec); + add_v3_v3v3(key->co, (key - 1)->co, dvec); } } @@ -3121,8 +3128,8 @@ static void brush_puff(PEData *data, int point_index) zero_v3(ofs_prev); { - ParticleEditSettings *pset= PE_settings(data->scene); - ParticleBrushData *brush= &pset->brush[pset->brushtype]; + ParticleEditSettings *pset = PE_settings(data->scene); + ParticleBrushData *brush = &pset->brush[pset->brushtype]; puff_volume = (brush->flag & PE_BRUSH_DATA_PUFF_VOLUME) != 0; } @@ -3138,13 +3145,13 @@ static void brush_puff(PEData *data, int point_index) LOOP_KEYS { float kco[3]; - if (k==0) { + if (k == 0) { /* find root coordinate and normal on emitter */ copy_v3_v3(co, key->co); mul_m4_v3(mat, co); mul_v3_m4v3(kco, data->ob->imat, co); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */ - point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL); + point_index = BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL); if (point_index == -1) return; copy_v3_v3(co_root, co); @@ -3158,10 +3165,10 @@ static void brush_puff(PEData *data, int point_index) normalize_v3(onor_prev); } - fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac); + fac = (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac); fac *= 0.025f; if (data->invert) - fac= -fac; + fac = -fac; } else { /* compute position as if hair was standing up straight. @@ -3173,7 +3180,7 @@ static void brush_puff(PEData *data, int point_index) length = len_v3v3(co_prev, co); length_accum += length; - if ((data->select==0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) { + if ((data->select == 0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) { float dco[3]; /* delta temp var */ madd_v3_v3v3fl(kco, co_root, no_root, length_accum); @@ -3205,7 +3212,7 @@ static void brush_puff(PEData *data, int point_index) #else /* translate (not rotate) the rest of the hair if its not selected */ { -#if 0 /* kindof works but looks worse then whats below */ +#if 0 /* kindof works but looks worse then whats below */ /* Move the unselected point on a vector based on the * hair direction and the offset */ @@ -3228,9 +3235,9 @@ static void brush_puff(PEData *data, int point_index) mul_m4_v3(mat, oco); mul_v3_m4v3(kco, data->ob->imat, oco); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */ - point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL); + point_index = BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL); if (point_index != -1) { - copy_v3_v3(onor, &edit->emitter_cosnos[point_index*6+3]); + copy_v3_v3(onor, &edit->emitter_cosnos[point_index * 6 + 3]); mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */ mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */ normalize_v3(onor); @@ -3266,7 +3273,7 @@ static void BKE_brush_weight_get(PEData *data, float UNUSED(mat[4][4]), float UN PTCacheEdit *edit = data->edit; ParticleSystem *psys = edit->psys; - ParticleData *pa= psys->particles + point_index; + ParticleData *pa = psys->particles + point_index; pa->hair[key_index].weight = data->weightfac; (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; @@ -3278,7 +3285,7 @@ static void brush_smooth_get(PEData *data, float mat[4][4], float UNUSED(imat[4] if (key_index) { float dvec[3]; - sub_v3_v3v3(dvec, key->co, (key-1)->co); + sub_v3_v3v3(dvec, key->co, (key - 1)->co); mul_mat3_m4_v3(mat, dvec); add_v3_v3(data->vec, dvec); data->tot++; @@ -3293,7 +3300,7 @@ static void brush_smooth_do(PEData *data, float UNUSED(mat[4][4]), float imat[4] copy_v3_v3(vec, data->vec); mul_mat3_m4_v3(imat, vec); - sub_v3_v3v3(dvec, key->co, (key-1)->co); + sub_v3_v3v3(dvec, key->co, (key - 1)->co); sub_v3_v3v3(dvec, vec, dvec); mul_v3_fl(dvec, data->smoothfac); @@ -3314,9 +3321,9 @@ static void intersect_dm_quad_weights(const float v1[3], const float v2[3], cons copy_v3_v3(vert[2], v3); copy_v3_v3(vert[3], v4); - co[0] = v1[0]*w[0] + v2[0]*w[1] + v3[0]*w[2] + v4[0]*w[3]; - co[1] = v1[1]*w[0] + v2[1]*w[1] + v3[1]*w[2] + v4[1]*w[3]; - co[2] = v1[2]*w[0] + v2[2]*w[1] + v3[2]*w[2] + v4[2]*w[3]; + co[0] = v1[0] * w[0] + v2[0] * w[1] + v3[0] * w[2] + v4[0] * w[3]; + co[1] = v1[1] * w[0] + v2[1] * w[1] + v3[1] * w[2] + v4[1] * w[3]; + co[2] = v1[2] * w[0] + v2[2] * w[1] + v3[2] * w[2] + v4[2] * w[3]; interp_weights_poly_v3(w, vert, 4, co); } @@ -3329,18 +3336,18 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm, float *face_minmax, float *pa_minmax, float radius, float *ipoint) { - MFace *mface= NULL; - MVert *mvert= NULL; - int i, totface, intersect=0; + MFace *mface = NULL; + MVert *mvert = NULL; + int i, totface, intersect = 0; float cur_d, cur_uv[2], v1[3], v2[3], v3[3], v4[3], min[3], max[3], p_min[3], p_max[3]; float cur_ipoint[3]; if (dm == NULL) { psys_disable_all(ob); - dm=mesh_get_derived_final(scene, ob, 0); + dm = mesh_get_derived_final(scene, ob, 0); if (dm == NULL) - dm=mesh_get_derived_deform(scene, ob, 0); + dm = mesh_get_derived_deform(scene, ob, 0); psys_enable_all(ob); @@ -3352,28 +3359,28 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm, DM_ensure_tessface(dm); - if (pa_minmax==0) { + if (pa_minmax == 0) { INIT_MINMAX(p_min, p_max); minmax_v3v3_v3(p_min, p_max, co1); minmax_v3v3_v3(p_min, p_max, co2); } else { copy_v3_v3(p_min, pa_minmax); - copy_v3_v3(p_max, pa_minmax+3); + copy_v3_v3(p_max, pa_minmax + 3); } - totface=dm->getNumTessFaces(dm); - mface=dm->getTessFaceDataArray(dm, CD_MFACE); - mvert=dm->getVertDataArray(dm, CD_MVERT); + totface = dm->getNumTessFaces(dm); + mface = dm->getTessFaceDataArray(dm, CD_MFACE); + mvert = dm->getVertDataArray(dm, CD_MVERT); /* lets intersect the faces */ - for (i=0; iv1); - copy_v3_v3(v2, vert_cos+3*mface->v2); - copy_v3_v3(v3, vert_cos+3*mface->v3); + copy_v3_v3(v1, vert_cos + 3 * mface->v1); + copy_v3_v3(v2, vert_cos + 3 * mface->v2); + copy_v3_v3(v3, vert_cos + 3 * mface->v3); if (mface->v4) - copy_v3_v3(v4, vert_cos+3*mface->v4); + copy_v3_v3(v4, vert_cos + 3 * mface->v4); } else { copy_v3_v3(v1, mvert[mface->v1].co); @@ -3383,68 +3390,68 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm, copy_v3_v3(v4, mvert[mface->v4].co); } - if (face_minmax==0) { + if (face_minmax == 0) { INIT_MINMAX(min, max); DO_MINMAX(v1, min, max); DO_MINMAX(v2, min, max); DO_MINMAX(v3, min, max); if (mface->v4) DO_MINMAX(v4, min, max); - if (isect_aabb_aabb_v3(min, max, p_min, p_max)==0) + if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) continue; } else { - copy_v3_v3(min, face_minmax+6*i); - copy_v3_v3(max, face_minmax+6*i+3); - if (isect_aabb_aabb_v3(min, max, p_min, p_max)==0) + copy_v3_v3(min, face_minmax + 6 * i); + copy_v3_v3(max, face_minmax + 6 * i + 3); + if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) continue; } - if (radius>0.0f) { + if (radius > 0.0f) { if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v2, v3, v1, &cur_d, cur_ipoint)) { - if (cur_d<*min_d) { - *min_d=cur_d; + if (cur_d < *min_d) { + *min_d = cur_d; copy_v3_v3(ipoint, cur_ipoint); - *min_face=i; - intersect=1; + *min_face = i; + intersect = 1; } } if (mface->v4) { if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v4, v1, v3, &cur_d, cur_ipoint)) { - if (cur_d<*min_d) { - *min_d=cur_d; + if (cur_d < *min_d) { + *min_d = cur_d; copy_v3_v3(ipoint, cur_ipoint); - *min_face=i; - intersect=1; + *min_face = i; + intersect = 1; } } } } else { if (isect_line_segment_tri_v3(co1, co2, v1, v2, v3, &cur_d, cur_uv)) { - if (cur_d<*min_d) { - *min_d=cur_d; + if (cur_d < *min_d) { + *min_d = cur_d; min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; min_w[1] = cur_uv[0]; min_w[2] = cur_uv[1]; min_w[3] = 0.0f; if (mface->v4) intersect_dm_quad_weights(v1, v2, v3, v4, min_w); - *min_face=i; - intersect=1; + *min_face = i; + intersect = 1; } } if (mface->v4) { if (isect_line_segment_tri_v3(co1, co2, v1, v3, v4, &cur_d, cur_uv)) { - if (cur_d<*min_d) { - *min_d=cur_d; + if (cur_d < *min_d) { + *min_d = cur_d; min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; min_w[1] = 0.0f; min_w[2] = cur_uv[0]; min_w[3] = cur_uv[1]; intersect_dm_quad_weights(v1, v2, v3, v4, min_w); - *min_face=i; - intersect=1; + *min_face = i; + intersect = 1; } } } @@ -3455,22 +3462,22 @@ static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm, static int brush_add(PEData *data, short number) { - Scene *scene= data->scene; - Object *ob= data->ob; + Scene *scene = data->scene; + Object *ob = data->ob; DerivedMesh *dm; PTCacheEdit *edit = data->edit; - ParticleSystem *psys= edit->psys; + ParticleSystem *psys = edit->psys; ParticleData *add_pars; - ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys); - ParticleSimulationData sim= {0}; - ParticleEditSettings *pset= PE_settings(scene); - int i, k, n= 0, totpart= psys->totpart; + ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); + ParticleSimulationData sim = {0}; + ParticleEditSettings *pset = PE_settings(scene); + int i, k, n = 0, totpart = psys->totpart; float mco[2]; float dmx, dmy; float co1[3], co2[3], min_d, imat[4][4]; float framestep, timestep; - short size= pset->brush[PE_BRUSH_ADD].size; - short size2= size*size; + short size = pset->brush[PE_BRUSH_ADD].size; + short size2 = size * size; RNG *rng; invert_m4_m4(imat, ob->obmat); @@ -3480,14 +3487,14 @@ static int brush_add(PEData *data, short number) add_pars = MEM_callocN(number * sizeof(ParticleData), "ParticleData add"); - rng = BLI_rng_new_srandom(psys->seed+data->mval[0]+data->mval[1]); + rng = BLI_rng_new_srandom(psys->seed + data->mval[0] + data->mval[1]); - sim.scene= scene; - sim.ob= ob; - sim.psys= psys; - sim.psmd= psmd; + sim.scene = scene; + sim.ob = ob; + sim.psys = psys; + sim.psmd = psmd; - timestep= psys_get_timestep(&sim); + timestep = psys_get_timestep(&sim); if (psys->part->use_modifier_stack || psmd->dm_final->deformedOnly) { dm = psmd->dm_final; @@ -3497,15 +3504,15 @@ static int brush_add(PEData *data, short number) } BLI_assert(dm); - for (i=0; i1) { + for (i = 0; i < number; i++) { + if (number > 1) { dmx = size; dmy = size; /* rejection sampling to get points in circle */ - while (dmx*dmx + dmy*dmy > size2) { - dmx= (2.0f*BLI_rng_get_float(rng) - 1.0f)*size; - dmy= (2.0f*BLI_rng_get_float(rng) - 1.0f)*size; + while (dmx * dmx + dmy * dmy > size2) { + dmx = (2.0f * BLI_rng_get_float(rng) - 1.0f) * size; + dmy = (2.0f * BLI_rng_get_float(rng) - 1.0f) * size; } } else { @@ -3519,7 +3526,7 @@ static int brush_add(PEData *data, short number) mul_m4_v3(imat, co1); mul_m4_v3(imat, co2); - min_d=2.0; + min_d = 2.0; /* warning, returns the derived mesh face */ if (particle_intersect_dm(scene, ob, dm, 0, co1, co2, &min_d, &add_pars[n].num_dmcache, add_pars[n].fuv, 0, 0, 0, 0)) { @@ -3531,8 +3538,8 @@ static int brush_add(PEData *data, short number) /* Final DM is not same topology as orig mesh, we have to map num_dmcache to real final dm. */ add_pars[n].num = add_pars[n].num_dmcache; add_pars[n].num_dmcache = psys_particle_dm_face_lookup( - psmd->dm_final, psmd->dm_deformed, - add_pars[n].num, add_pars[n].fuv, NULL); + psmd->dm_final, psmd->dm_deformed, + add_pars[n].num, add_pars[n].fuv, NULL); } else { add_pars[n].num = add_pars[n].num_dmcache; @@ -3544,11 +3551,11 @@ static int brush_add(PEData *data, short number) } } if (n) { - int newtotpart=totpart+n; + int newtotpart = totpart + n; float hairmat[4][4], cur_co[3]; - KDTree *tree=0; - ParticleData *pa, *new_pars = MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new"); - PTCacheEditPoint *point, *new_points = MEM_callocN(newtotpart*sizeof(PTCacheEditPoint), "PTCacheEditPoint array new"); + KDTree *tree = 0; + ParticleData *pa, *new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); + PTCacheEditPoint *point, *new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), "PTCacheEditPoint array new"); PTCacheEditKey *key; HairKey *hkey; @@ -3558,21 +3565,21 @@ static int brush_add(PEData *data, short number) /* change old arrays to new ones */ if (psys->particles) MEM_freeN(psys->particles); - psys->particles= new_pars; + psys->particles = new_pars; if (edit->points) MEM_freeN(edit->points); - edit->points= new_points; + edit->points = new_points; if (edit->mirror_cache) { MEM_freeN(edit->mirror_cache); - edit->mirror_cache= NULL; + edit->mirror_cache = NULL; } /* create tree for interpolation */ if (pset->flag & PE_INTERPOLATE_ADDED && psys->totpart) { - tree=BLI_kdtree_new(psys->totpart); + tree = BLI_kdtree_new(psys->totpart); - for (i=0, pa=psys->particles; iparticles; i < totpart; i++, pa++) { psys_particle_on_dm(psmd->dm_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, cur_co, 0, 0, 0, 0, 0); BLI_kdtree_insert(tree, i, cur_co); } @@ -3580,34 +3587,34 @@ static int brush_add(PEData *data, short number) BLI_kdtree_balance(tree); } - edit->totpoint= psys->totpart= newtotpart; + edit->totpoint = psys->totpart = newtotpart; /* create new elements */ pa = psys->particles + totpart; point = edit->points + totpart; - for (i=totpart; ihair= MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add"); - key= point->keys= MEM_callocN(pset->totaddkey * sizeof(PTCacheEditKey), "PTCacheEditKey add"); - point->totkey= pa->totkey= pset->totaddkey; + pa->hair = MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add"); + key = point->keys = MEM_callocN(pset->totaddkey * sizeof(PTCacheEditKey), "PTCacheEditKey add"); + point->totkey = pa->totkey = pset->totaddkey; - for (k=0, hkey=pa->hair; ktotkey; k++, hkey++, key++) { - key->co= hkey->co; - key->time= &hkey->time; + for (k = 0, hkey = pa->hair; k < pa->totkey; k++, hkey++, key++) { + key->co = hkey->co; + key->time = &hkey->time; if (!(psys->flag & PSYS_GLOBAL_HAIR)) key->flag |= PEK_USE_WCO; } - pa->size= 1.0f; + pa->size = 1.0f; initialize_particle(&sim, pa); reset_particle(&sim, pa, 0.0, 1.0); point->flag |= PEP_EDIT_RECALC; if (pe_x_mirror(ob)) point->flag |= PEP_TAG; /* signal for duplicate */ - framestep= pa->lifetime/(float)(pset->totaddkey-1); + framestep = pa->lifetime / (float)(pset->totaddkey - 1); if (tree) { ParticleData *ppa; @@ -3615,73 +3622,73 @@ static int brush_add(PEData *data, short number) ParticleKey key3[3]; KDTreeNearest ptn[3]; int w, maxw; - float maxd, totw=0.0, weight[3]; + float maxd, totw = 0.0, weight[3]; psys_particle_on_dm(psmd->dm_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co1, 0, 0, 0, 0, 0); maxw = BLI_kdtree_find_nearest_n(tree, co1, ptn, 3); - maxd= ptn[maxw-1].dist; + maxd = ptn[maxw - 1].dist; - for (w=0; w 0.0f) { - for (w=0; wparticles+ptn[0].index; + ppa = psys->particles + ptn[0].index; - for (k=0; ktotaddkey; k++) { - thkey= (HairKey *)pa->hair + k; - thkey->time= pa->time + k * framestep; + for (k = 0; k < pset->totaddkey; k++) { + thkey = (HairKey *)pa->hair + k; + thkey->time = pa->time + k * framestep; - key3[0].time= thkey->time/ 100.0f; + key3[0].time = thkey->time / 100.0f; psys_get_particle_on_path(&sim, ptn[0].index, key3, 0); mul_v3_fl(key3[0].co, weight[0]); /* TODO: interpolating the weight would be nicer */ - thkey->weight= (ppa->hair+MIN2(k, ppa->totkey-1))->weight; + thkey->weight = (ppa->hair + MIN2(k, ppa->totkey - 1))->weight; - if (maxw>1) { - key3[1].time= key3[0].time; + if (maxw > 1) { + key3[1].time = key3[0].time; psys_get_particle_on_path(&sim, ptn[1].index, &key3[1], 0); mul_v3_fl(key3[1].co, weight[1]); add_v3_v3(key3[0].co, key3[1].co); - if (maxw>2) { - key3[2].time= key3[0].time; + if (maxw > 2) { + key3[2].time = key3[0].time; psys_get_particle_on_path(&sim, ptn[2].index, &key3[2], 0); mul_v3_fl(key3[2].co, weight[2]); add_v3_v3(key3[0].co, key3[2].co); } } - if (k==0) + if (k == 0) sub_v3_v3v3(co1, pa->state.co, key3[0].co); add_v3_v3v3(thkey->co, key3[0].co, co1); - thkey->time= key3[0].time; + thkey->time = key3[0].time; } } else { - for (k=0, hkey=pa->hair; ktotaddkey; k++, hkey++) { + for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { madd_v3_v3v3fl(hkey->co, pa->state.co, pa->state.vel, k * framestep * timestep); hkey->time += k * framestep; - hkey->weight = 1.f - (float)k/(float)(pset->totaddkey-1); + hkey->weight = 1.f - (float)k / (float)(pset->totaddkey - 1); } } - for (k=0, hkey=pa->hair; ktotaddkey; k++, hkey++) { + for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, pa, hairmat); invert_m4_m4(imat, hairmat); mul_m4_v3(imat, hkey->co); @@ -3717,11 +3724,11 @@ typedef struct BrushEdit { static int brush_edit_init(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= CTX_data_active_object(C); - ParticleEditSettings *pset= PE_settings(scene); - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); - ARegion *ar= CTX_wm_region(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + ParticleEditSettings *pset = PE_settings(scene); + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); + ARegion *ar = CTX_wm_region(C); BrushEdit *bedit; float min[3], max[3]; @@ -3733,13 +3740,13 @@ static int brush_edit_init(bContext *C, wmOperator *op) PE_minmax(bmain, scene, min, max); mid_v3_v3v3(min, min, max); - bedit= MEM_callocN(sizeof(BrushEdit), "BrushEdit"); - bedit->first= 1; - op->customdata= bedit; + bedit = MEM_callocN(sizeof(BrushEdit), "BrushEdit"); + bedit->first = 1; + op->customdata = bedit; - bedit->scene= scene; - bedit->ob= ob; - bedit->edit= edit; + bedit->scene = scene; + bedit->ob = ob; + bedit->edit = edit; bedit->zfac = ED_view3d_calc_zfac(ar->regiondata, min, NULL); @@ -3752,17 +3759,17 @@ static int brush_edit_init(bContext *C, wmOperator *op) static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) { Main *bmain = CTX_data_main(C); - BrushEdit *bedit= op->customdata; - Scene *scene= bedit->scene; - Object *ob= bedit->ob; - PTCacheEdit *edit= bedit->edit; - ParticleEditSettings *pset= PE_settings(scene); - ParticleSystemModifierData *psmd= edit->psys ? psys_get_modifier(ob, edit->psys) : NULL; - ParticleBrushData *brush= &pset->brush[pset->brushtype]; - ARegion *ar= CTX_wm_region(C); + BrushEdit *bedit = op->customdata; + Scene *scene = bedit->scene; + Object *ob = bedit->ob; + PTCacheEdit *edit = bedit->edit; + ParticleEditSettings *pset = PE_settings(scene); + ParticleSystemModifierData *psmd = edit->psys ? psys_get_modifier(ob, edit->psys) : NULL; + ParticleBrushData *brush = &pset->brush[pset->brushtype]; + ARegion *ar = CTX_wm_region(C); float vec[3], mousef[2]; int mval[2]; - int flip, mouse[2], removed= 0, added=0, selected= 0, tot_steps= 1, step= 1; + int flip, mouse[2], removed = 0, added = 0, selected = 0, tot_steps = 1, step = 1; float dx, dy, dmax; int lock_root = pset->flag & PE_LOCK_FIRST; @@ -3772,15 +3779,15 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) RNA_float_get_array(itemptr, "mouse", mousef); mouse[0] = mousef[0]; mouse[1] = mousef[1]; - flip= RNA_boolean_get(itemptr, "pen_flip"); + flip = RNA_boolean_get(itemptr, "pen_flip"); if (bedit->first) { bedit->lastmouse[0] = mouse[0]; bedit->lastmouse[1] = mouse[1]; } - dx= mouse[0] - bedit->lastmouse[0]; - dy= mouse[1] - bedit->lastmouse[1]; + dx = mouse[0] - bedit->lastmouse[0]; + dy = mouse[1] - bedit->lastmouse[1]; mval[0] = mouse[0]; mval[1] = mouse[1]; @@ -3793,38 +3800,38 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) if (((pset->brushtype == PE_BRUSH_ADD) ? (sqrtf(dx * dx + dy * dy) > pset->brush[PE_BRUSH_ADD].step) : (dx != 0 || dy != 0)) || bedit->first) { - PEData data= bedit->data; + PEData data = bedit->data; view3d_operator_needs_opengl(C); - selected= (short)count_selected_keys(scene, edit); + selected = (short)count_selected_keys(scene, edit); dmax = max_ff(fabsf(dx), fabsf(dy)); - tot_steps = dmax/(0.2f * pe_brush_size_get(scene, brush)) + 1; + tot_steps = dmax / (0.2f * pe_brush_size_get(scene, brush)) + 1; dx /= (float)tot_steps; dy /= (float)tot_steps; - for (step = 1; step<=tot_steps; step++) { - mval[0] = bedit->lastmouse[0] + step*dx; - mval[1] = bedit->lastmouse[1] + step*dy; + for (step = 1; step <= tot_steps; step++) { + mval[0] = bedit->lastmouse[0] + step * dx; + mval[1] = bedit->lastmouse[1] + step * dy; switch (pset->brushtype) { case PE_BRUSH_COMB: { const float mval_f[2] = {dx, dy}; - data.mval= mval; - data.rad= pe_brush_size_get(scene, brush); + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); - data.combfac= (brush->strength - 0.5f) * 2.0f; + data.combfac = (brush->strength - 0.5f) * 2.0f; if (data.combfac < 0.0f) - data.combfac= 1.0f - 9.0f * data.combfac; + data.combfac = 1.0f - 9.0f * data.combfac; else - data.combfac= 1.0f - data.combfac; + data.combfac = 1.0f - data.combfac; invert_m4_m4(ob->imat, ob->obmat); ED_view3d_win_to_delta(ar, mval_f, vec, bedit->zfac); - data.dvec= vec; + data.dvec = vec; foreach_mouse_hit_key(&data, brush_comb, selected); break; @@ -3832,35 +3839,35 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) case PE_BRUSH_CUT: { if (edit->psys && edit->pathcache) { - data.mval= mval; - data.rad= pe_brush_size_get(scene, brush); - data.cutfac= brush->strength; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + data.cutfac = brush->strength; if (selected) foreach_selected_point(&data, brush_cut); else foreach_point(&data, brush_cut); - removed= remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); + removed = remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); if (pset->flag & PE_KEEP_LENGTHS) recalc_lengths(edit); } else - removed= 0; + removed = 0; break; } case PE_BRUSH_LENGTH: { - data.mval= mval; + data.mval = mval; - data.rad= pe_brush_size_get(scene, brush); - data.growfac= brush->strength / 50.0f; + data.rad = pe_brush_size_get(scene, brush); + data.growfac = brush->strength / 50.0f; if (brush->invert ^ flip) - data.growfac= 1.0f - data.growfac; + data.growfac = 1.0f - data.growfac; else - data.growfac= 1.0f + data.growfac; + data.growfac = 1.0f + data.growfac; foreach_mouse_hit_point(&data, brush_length, selected); @@ -3871,18 +3878,18 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) case PE_BRUSH_PUFF: { if (edit->psys) { - data.dm= psmd->dm_final; - data.mval= mval; - data.rad= pe_brush_size_get(scene, brush); - data.select= selected; + data.dm = psmd->dm_final; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + data.select = selected; - data.pufffac= (brush->strength - 0.5f) * 2.0f; + data.pufffac = (brush->strength - 0.5f) * 2.0f; if (data.pufffac < 0.0f) - data.pufffac= 1.0f - 9.0f * data.pufffac; + data.pufffac = 1.0f - 9.0f * data.pufffac; else - data.pufffac= 1.0f - data.pufffac; + data.pufffac = 1.0f - data.pufffac; - data.invert= (brush->invert ^ flip); + data.invert = (brush->invert ^ flip); invert_m4_m4(ob->imat, ob->obmat); foreach_mouse_hit_point(&data, brush_puff, selected); @@ -3891,27 +3898,27 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) } case PE_BRUSH_ADD: { - if (edit->psys && edit->psys->part->from==PART_FROM_FACE) { - data.mval= mval; + if (edit->psys && edit->psys->part->from == PART_FROM_FACE) { + data.mval = mval; - added= brush_add(&data, brush->count); + added = brush_add(&data, brush->count); if (pset->flag & PE_KEEP_LENGTHS) recalc_lengths(edit); } else - added= 0; + added = 0; break; } case PE_BRUSH_SMOOTH: { - data.mval= mval; - data.rad= pe_brush_size_get(scene, brush); + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); data.vec[0] = data.vec[1] = data.vec[2] = 0.0f; - data.tot= 0; + data.tot = 0; - data.smoothfac= brush->strength; + data.smoothfac = brush->strength; invert_m4_m4(ob->imat, ob->obmat); @@ -3927,9 +3934,9 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) case PE_BRUSH_WEIGHT: { if (edit->psys) { - data.dm= psmd->dm_final; - data.mval= mval; - data.rad= pe_brush_size_get(scene, brush); + data.dm = psmd->dm_final; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); data.weightfac = brush->strength; /* note that this will never be zero */ @@ -3939,7 +3946,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) break; } } - if ((pset->flag & PE_KEEP_LENGTHS)==0) + if ((pset->flag & PE_KEEP_LENGTHS) == 0) recalc_lengths(edit); if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_CUT) && (added || removed)) { @@ -3955,16 +3962,16 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) } if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); } else { DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); } bedit->lastmouse[0] = mouse[0]; bedit->lastmouse[1] = mouse[1]; - bedit->first= 0; + bedit->first = 0; } pset->flag |= lock_root; @@ -3972,7 +3979,7 @@ static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) static void brush_edit_exit(wmOperator *op) { - BrushEdit *bedit= op->customdata; + BrushEdit *bedit = op->customdata; MEM_freeN(bedit); } @@ -3982,7 +3989,7 @@ static int brush_edit_exec(bContext *C, wmOperator *op) if (!brush_edit_init(C, op)) return OPERATOR_CANCELLED; - RNA_BEGIN (op->ptr, itemptr, "stroke") + RNA_BEGIN(op->ptr, itemptr, "stroke") { brush_edit_apply(C, op, &itemptr); } @@ -4061,7 +4068,7 @@ void PARTICLE_OT_brush_edit(wmOperatorType *ot) ot->poll = PE_poll_view3d; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING; /* properties */ PropertyRNA *prop; @@ -4071,7 +4078,7 @@ void PARTICLE_OT_brush_edit(wmOperatorType *ot) /*********************** cut shape ***************************/ -static int shape_cut_poll(bContext *C) +static bool shape_cut_poll(bContext *C) { if (PE_hair_poll(C)) { Scene *scene = CTX_data_scene(C); @@ -4111,8 +4118,8 @@ static bool shape_cut_test_point(PEData *data, ParticleCacheKey *key) userdata.num_hits = 0; BLI_bvhtree_ray_cast_all( - shape_bvh->tree, key->co, dir, 0.0f, BVH_RAYCAST_DIST_MAX, - point_inside_bvh_cb, &userdata); + shape_bvh->tree, key->co, dir, 0.0f, BVH_RAYCAST_DIST_MAX, + point_inside_bvh_cb, &userdata); /* for any point inside a watertight mesh the number of hits is uneven */ return (userdata.num_hits % 2) == 1; @@ -4147,7 +4154,7 @@ static void shape_cut(PEData *data, int pa_index) float dir[3]; float len; - sub_v3_v3v3(dir, (key+1)->co, key->co); + sub_v3_v3v3(dir, (key + 1)->co, key->co); len = normalize_v3(dir); memset(&hit, 0, sizeof(hit)); @@ -4220,11 +4227,11 @@ static int shape_cut_exec(bContext *C, wmOperator *UNUSED(op)) PE_update_object(bmain, scene, ob, 1); if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); } else { DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); } PE_free_shape_tree(&data); @@ -4247,43 +4254,43 @@ void PARTICLE_OT_shape_cut(wmOperatorType *ot) ot->poll = shape_cut_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ utilities ******************************/ int PE_minmax(Main *bmain, Scene *scene, float min[3], float max[3]) { - Object *ob= OBACT; - PTCacheEdit *edit= PE_get_current(bmain, scene, ob); + Object *ob = OBACT; + PTCacheEdit *edit = PE_get_current(bmain, scene, ob); ParticleSystem *psys; ParticleSystemModifierData *psmd = NULL; POINT_P; KEY_K; float co[3], mat[4][4]; - int ok= 0; + int ok = 0; if (!edit) return ok; if ((psys = edit->psys)) - psmd= psys_get_modifier(ob, psys); + psmd = psys_get_modifier(ob, psys); else unit_m4(mat); LOOP_VISIBLE_POINTS { if (psys) - psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles+p, mat); + psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + p, mat); LOOP_SELECTED_KEYS { copy_v3_v3(co, key->co); mul_m4_v3(mat, co); DO_MINMAX(co, min, max); - ok= 1; + ok = 1; } } if (!ok) { BKE_object_minmax(ob, min, max, true); - ok= 1; + ok = 1; } return ok; @@ -4316,15 +4323,15 @@ void PE_create_particle_edit(Main *bmain, Scene *scene, Object *ob, PointCache * if (!edit) { totpoint = psys ? psys->totpart : (int)((PTCacheMem *)cache->mem_cache.first)->totpoint; - edit= MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit"); - edit->points=MEM_callocN(totpoint*sizeof(PTCacheEditPoint), "PTCacheEditPoints"); + edit = MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit"); + edit->points = MEM_callocN(totpoint * sizeof(PTCacheEditPoint), "PTCacheEditPoints"); edit->totpoint = totpoint; if (psys && !cache) { - psys->edit= edit; + psys->edit = edit; edit->psys = psys; - psys->free_edit= PE_free_ptcache_edit; + psys->free_edit = PE_free_ptcache_edit; edit->pathcache = NULL; BLI_listbase_clear(&edit->pathcachebufs); @@ -4332,14 +4339,14 @@ void PE_create_particle_edit(Main *bmain, Scene *scene, Object *ob, PointCache * pa = psys->particles; LOOP_POINTS { point->totkey = pa->totkey; - point->keys= MEM_callocN(point->totkey*sizeof(PTCacheEditKey), "ParticleEditKeys"); + point->keys = MEM_callocN(point->totkey * sizeof(PTCacheEditKey), "ParticleEditKeys"); point->flag |= PEP_EDIT_RECALC; hkey = pa->hair; LOOP_KEYS { - key->co= hkey->co; - key->time= &hkey->time; - key->flag= hkey->editflag; + key->co = hkey->co; + key->time = &hkey->time; + key->flag = hkey->editflag; if (!(psys->flag & PSYS_GLOBAL_HAIR)) { key->flag |= PEK_USE_WCO; hkey->editflag |= PEK_USE_WCO; @@ -4353,22 +4360,22 @@ void PE_create_particle_edit(Main *bmain, Scene *scene, Object *ob, PointCache * } else { PTCacheMem *pm; - int totframe=0; + int totframe = 0; - cache->edit= edit; - cache->free_edit= PE_free_ptcache_edit; + cache->edit = edit; + cache->free_edit = PE_free_ptcache_edit; edit->psys = NULL; - for (pm=cache->mem_cache.first; pm; pm=pm->next) + for (pm = cache->mem_cache.first; pm; pm = pm->next) totframe++; - for (pm=cache->mem_cache.first; pm; pm=pm->next) { + for (pm = cache->mem_cache.first; pm; pm = pm->next) { LOOP_POINTS { if (BKE_ptcache_mem_pointers_seek(p, pm) == 0) continue; if (!point->totkey) { - key = point->keys = MEM_callocN(totframe*sizeof(PTCacheEditKey), "ParticleEditKeys"); + key = point->keys = MEM_callocN(totframe * sizeof(PTCacheEditKey), "ParticleEditKeys"); point->flag |= PEP_EDIT_RECALC; } else @@ -4397,7 +4404,7 @@ void PE_create_particle_edit(Main *bmain, Scene *scene, Object *ob, PointCache * } } -static int particle_edit_toggle_poll(bContext *C) +static bool particle_edit_toggle_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -4430,7 +4437,7 @@ static int particle_edit_toggle_exec(bContext *C, wmOperator *op) if (!is_mode_set) { PTCacheEdit *edit; ob->mode |= mode_flag; - edit= PE_create_current(bmain, scene, ob); + edit = PE_create_current(bmain, scene, ob); /* mesh may have changed since last entering editmode. * note, this may have run before if the edit data was just created, so could avoid this and speed up a little */ @@ -4438,12 +4445,12 @@ static int particle_edit_toggle_exec(bContext *C, wmOperator *op) recalc_emitter_field(ob, edit->psys); toggle_particle_cursor(C, 1); - WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_PARTICLE, NULL); + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_PARTICLE, NULL); } else { ob->mode &= ~mode_flag; toggle_particle_cursor(C, 0); - WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_OBJECT, NULL); + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); } DAG_id_tag_update(&ob->id, OB_RECALC_DATA); @@ -4463,7 +4470,7 @@ void PARTICLE_OT_particle_edit_toggle(wmOperatorType *ot) ot->poll = particle_edit_toggle_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } @@ -4471,7 +4478,7 @@ void PARTICLE_OT_particle_edit_toggle(wmOperatorType *ot) static int clear_edited_exec(bContext *C, wmOperator *UNUSED(op)) { - Object *ob= CTX_data_active_object(C); + Object *ob = CTX_data_active_object(C); ParticleSystem *psys = psys_get_current(ob); if (psys->edit) { @@ -4486,7 +4493,7 @@ static int clear_edited_exec(bContext *C, wmOperator *UNUSED(op)) psys->flag &= ~PSYS_EDITED; psys_reset(psys, PSYS_RESET_DEPSGRAPH); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); } } @@ -4494,7 +4501,7 @@ static int clear_edited_exec(bContext *C, wmOperator *UNUSED(op)) psys->recalc |= PSYS_RECALC_RESET; psys->flag &= ~PSYS_GLOBAL_HAIR; psys->flag &= ~PSYS_EDITED; - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); } @@ -4519,7 +4526,7 @@ void PARTICLE_OT_edited_clear(wmOperatorType *ot) ot->invoke = clear_edited_invoke; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ Unify length operator ************************/ @@ -4608,11 +4615,11 @@ static int unify_length_exec(bContext *C, wmOperator *UNUSED(op)) PE_update_object(bmain, scene, ob, 1); if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); } else { DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_MODIFIER, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); } return OPERATOR_FINISHED; @@ -4630,6 +4637,5 @@ void PARTICLE_OT_unify_length(struct wmOperatorType *ot) ot->poll = PE_poll_view3d; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/physics/particle_edit_undo.c b/source/blender/editors/physics/particle_edit_undo.c index 3d17b1a20c18..1b4aeabc71b6 100644 --- a/source/blender/editors/physics/particle_edit_undo.c +++ b/source/blender/editors/physics/particle_edit_undo.c @@ -70,15 +70,15 @@ static void undoptcache_from_editcache(PTCacheUndo *undo, PTCacheEdit *edit) size_t mem_used_prev = MEM_get_memory_in_use(); - undo->totpoint= edit->totpoint; + undo->totpoint = edit->totpoint; if (edit->psys) { ParticleData *pa; - pa= undo->particles= MEM_dupallocN(edit->psys->particles); + pa = undo->particles = MEM_dupallocN(edit->psys->particles); - for (i=0; itotpoint; i++, pa++) { - pa->hair= MEM_dupallocN(pa->hair); + for (i = 0; i < edit->totpoint; i++, pa++) { + pa->hair = MEM_dupallocN(pa->hair); } undo->psys_flag = edit->psys->flag; @@ -89,18 +89,18 @@ static void undoptcache_from_editcache(PTCacheUndo *undo, PTCacheEdit *edit) BLI_duplicatelist(&undo->mem_cache, &edit->pid.cache->mem_cache); pm = undo->mem_cache.first; - for (; pm; pm=pm->next) { - for (i=0; inext) { + for (i = 0; i < BPHYS_TOT_DATA; i++) { pm->data[i] = MEM_dupallocN(pm->data[i]); } } } - point= undo->points = MEM_dupallocN(edit->points); + point = undo->points = MEM_dupallocN(edit->points); undo->totpoint = edit->totpoint; - for (i=0; itotpoint; i++, point++) { - point->keys= MEM_dupallocN(point->keys); + for (i = 0; i < edit->totpoint; i++, point++) { + point->keys = MEM_dupallocN(point->keys); /* no need to update edit key->co & key->time pointers here */ } @@ -133,28 +133,28 @@ static void undoptcache_to_editcache(PTCacheUndo *undo, PTCacheEdit *edit) } if (edit->mirror_cache) { MEM_freeN(edit->mirror_cache); - edit->mirror_cache= NULL; + edit->mirror_cache = NULL; } - edit->points= MEM_dupallocN(undo->points); + edit->points = MEM_dupallocN(undo->points); edit->totpoint = undo->totpoint; LOOP_POINTS { - point->keys= MEM_dupallocN(point->keys); + point->keys = MEM_dupallocN(point->keys); } if (psys) { - psys->particles= MEM_dupallocN(undo->particles); + psys->particles = MEM_dupallocN(undo->particles); - psys->totpart= undo->totpoint; + psys->totpart = undo->totpoint; LOOP_POINTS { pa = psys->particles + p; - hkey= pa->hair = MEM_dupallocN(pa->hair); + hkey = pa->hair = MEM_dupallocN(pa->hair); LOOP_KEYS { - key->co= hkey->co; - key->time= &hkey->time; + key->co = hkey->co; + key->time = &hkey->time; hkey++; } } @@ -171,7 +171,7 @@ static void undoptcache_to_editcache(PTCacheUndo *undo, PTCacheEdit *edit) pm = edit->pid.cache->mem_cache.first; - for (; pm; pm=pm->next) { + for (; pm; pm = pm->next) { for (i = 0; i < BPHYS_TOT_DATA; i++) { pm->data[i] = MEM_dupallocN(pm->data[i]); } @@ -197,7 +197,7 @@ static void undoptcache_free_data(PTCacheUndo *undo) PTCacheEditPoint *point; int i; - for (i = 0, point=undo->points; i < undo->totpoint; i++, point++) { + for (i = 0, point = undo->points; i < undo->totpoint; i++, point++) { if (undo->particles && (undo->particles + i)->hair) { MEM_freeN((undo->particles + i)->hair); } diff --git a/source/blender/editors/physics/particle_edit_utildefines.h b/source/blender/editors/physics/particle_edit_utildefines.h index 7608b8854594..1084bb9742ae 100644 --- a/source/blender/editors/physics/particle_edit_utildefines.h +++ b/source/blender/editors/physics/particle_edit_utildefines.h @@ -32,19 +32,19 @@ #ifndef __PARTICLE_EDIT_UTILDEFNIES_H__ #define __PARTICLE_EDIT_UTILDEFNIES_H__ -#define KEY_K PTCacheEditKey *key; int k -#define POINT_P PTCacheEditPoint *point; int p -#define LOOP_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) -#define LOOP_VISIBLE_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) if (!(point->flag & PEP_HIDE)) -#define LOOP_SELECTED_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) if (point_is_selected(point)) -#define LOOP_UNSELECTED_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) if (!point_is_selected(point)) -#define LOOP_EDITED_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC) -#define LOOP_TAGGED_POINTS for (p=0, point=edit->points; ptotpoint; p++, point++) if (point->flag & PEP_TAG) -#define LOOP_KEYS for (k=0, key=point->keys; ktotkey; k++, key++) -#define LOOP_VISIBLE_KEYS for (k=0, key=point->keys; ktotkey; k++, key++) if (!(key->flag & PEK_HIDE)) -#define LOOP_SELECTED_KEYS for (k=0, key=point->keys; ktotkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE)) -#define LOOP_TAGGED_KEYS for (k=0, key=point->keys; ktotkey; k++, key++) if (key->flag & PEK_TAG) +#define KEY_K PTCacheEditKey *key; int k +#define POINT_P PTCacheEditPoint *point; int p +#define LOOP_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) +#define LOOP_VISIBLE_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE)) +#define LOOP_SELECTED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point_is_selected(point)) +#define LOOP_UNSELECTED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (!point_is_selected(point)) +#define LOOP_EDITED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC) +#define LOOP_TAGGED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point->flag & PEP_TAG) +#define LOOP_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) +#define LOOP_VISIBLE_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if (!(key->flag & PEK_HIDE)) +#define LOOP_SELECTED_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE)) +#define LOOP_TAGGED_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if (key->flag & PEK_TAG) -#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co) +#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co) #endif /* __PARTICLE_EDIT_UTILDEFNIES_H__ */ diff --git a/source/blender/editors/physics/particle_object.c b/source/blender/editors/physics/particle_object.c index 873ea196c350..e6b8ac596e9c 100644 --- a/source/blender/editors/physics/particle_object.c +++ b/source/blender/editors/physics/particle_object.c @@ -78,7 +78,7 @@ static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0 static int particle_system_add_exec(bContext *C, wmOperator *UNUSED(op)) { Main *bmain = CTX_data_main(C); - Object *ob= ED_object_context(C); + Object *ob = ED_object_context(C); Scene *scene = CTX_data_scene(C); if (!scene || !ob) @@ -86,8 +86,8 @@ static int particle_system_add_exec(bContext *C, wmOperator *UNUSED(op)) object_add_particle_system(bmain, scene, ob, NULL); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); return OPERATOR_FINISHED; } @@ -104,7 +104,7 @@ void OBJECT_OT_particle_system_add(wmOperatorType *ot) ot->exec = particle_system_add_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op)) @@ -126,13 +126,13 @@ static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op)) if (mode_orig & OB_MODE_PARTICLE_EDIT) { if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) { if (scene->basact && scene->basact->object == ob) { - WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_OBJECT, NULL); + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); } } } - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); return OPERATOR_FINISHED; } @@ -149,12 +149,12 @@ void OBJECT_OT_particle_system_remove(wmOperatorType *ot) ot->exec = particle_system_remove_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** new particle settings operator *********************/ -static int psys_poll(bContext *C) +static bool psys_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); return (ptr.data != NULL); @@ -162,7 +162,7 @@ static int psys_poll(bContext *C) static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain= CTX_data_main(C); + Main *bmain = CTX_data_main(C); ParticleSystem *psys; ParticleSettings *part = NULL; Object *ob; @@ -174,11 +174,11 @@ static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op)) /* add or copy particle setting */ if (psys->part) - part= BKE_particlesettings_copy(bmain, psys->part); + part = BKE_particlesettings_copy(bmain, psys->part); else - part= BKE_particlesettings_add(bmain, "ParticleSettings"); + part = BKE_particlesettings_add(bmain, "ParticleSettings"); - ob= ptr.id.data; + ob = ptr.id.data; if (psys->part) id_us_min(&psys->part->id); @@ -190,7 +190,7 @@ static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op)) DAG_relations_tag_update(bmain); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); return OPERATOR_FINISHED; } @@ -207,7 +207,7 @@ void PARTICLE_OT_new(wmOperatorType *ot) ot->poll = psys_poll; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** keyed particle target operators *********************/ @@ -216,7 +216,7 @@ static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) { Main *bmain = CTX_data_main(C); PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; Object *ob = ptr.id.data; ParticleTarget *pt; @@ -225,7 +225,7 @@ static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; pt = psys->targets.first; - for (; pt; pt=pt->next) + for (; pt; pt = pt->next) pt->flag &= ~PTARGET_CURRENT; pt = MEM_callocN(sizeof(ParticleTarget), "keyed particle target"); @@ -238,7 +238,7 @@ static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) DAG_relations_tag_update(bmain); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); return OPERATOR_FINISHED; } @@ -254,14 +254,14 @@ void PARTICLE_OT_new_target(wmOperatorType *ot) ot->exec = new_particle_target_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) { Main *bmain = CTX_data_main(C); PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; Object *ob = ptr.id.data; ParticleTarget *pt; @@ -270,7 +270,7 @@ static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; pt = psys->targets.first; - for (; pt; pt=pt->next) { + for (; pt; pt = pt->next) { if (pt->flag & PTARGET_CURRENT) { BLI_remlink(&psys->targets, pt); MEM_freeN(pt); @@ -286,7 +286,7 @@ static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) DAG_relations_tag_update(bmain); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); return OPERATOR_FINISHED; } @@ -302,7 +302,7 @@ void PARTICLE_OT_target_remove(wmOperatorType *ot) ot->exec = remove_particle_target_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up particle target operator *********************/ @@ -310,7 +310,7 @@ void PARTICLE_OT_target_remove(wmOperatorType *ot) static int target_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; Object *ob = ptr.id.data; ParticleTarget *pt; @@ -318,13 +318,13 @@ static int target_move_up_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; pt = psys->targets.first; - for (; pt; pt=pt->next) { + for (; pt; pt = pt->next) { if (pt->flag & PTARGET_CURRENT && pt->prev) { BLI_remlink(&psys->targets, pt); BLI_insertlinkbefore(&psys->targets, pt->prev, pt); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); break; } } @@ -341,7 +341,7 @@ void PARTICLE_OT_target_move_up(wmOperatorType *ot) ot->exec = target_move_up_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move down particle target operator *********************/ @@ -349,20 +349,20 @@ void PARTICLE_OT_target_move_up(wmOperatorType *ot) static int target_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; Object *ob = ptr.id.data; ParticleTarget *pt; if (!psys) return OPERATOR_CANCELLED; pt = psys->targets.first; - for (; pt; pt=pt->next) { + for (; pt; pt = pt->next) { if (pt->flag & PTARGET_CURRENT && pt->next) { BLI_remlink(&psys->targets, pt); BLI_insertlinkafter(&psys->targets, pt->next, pt); DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); break; } } @@ -379,7 +379,7 @@ void PARTICLE_OT_target_move_down(wmOperatorType *ot) ot->exec = target_move_down_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up particle dupliweight operator *********************/ @@ -387,7 +387,7 @@ void PARTICLE_OT_target_move_down(wmOperatorType *ot) static int dupliob_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; ParticleSettings *part; ParticleDupliWeight *dw; @@ -395,12 +395,12 @@ static int dupliob_move_up_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; part = psys->part; - for (dw=part->dupliweights.first; dw; dw=dw->next) { + for (dw = part->dupliweights.first; dw; dw = dw->next) { if (dw->flag & PART_DUPLIW_CURRENT && dw->prev) { BLI_remlink(&part->dupliweights, dw); BLI_insertlinkbefore(&part->dupliweights, dw->prev, dw); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); break; } } @@ -417,7 +417,7 @@ void PARTICLE_OT_dupliob_move_up(wmOperatorType *ot) ot->exec = dupliob_move_up_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** particle dupliweight operators *********************/ @@ -425,21 +425,21 @@ void PARTICLE_OT_dupliob_move_up(wmOperatorType *ot) static int copy_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; ParticleSettings *part; ParticleDupliWeight *dw; if (!psys) return OPERATOR_CANCELLED; part = psys->part; - for (dw=part->dupliweights.first; dw; dw=dw->next) { + for (dw = part->dupliweights.first; dw; dw = dw->next) { if (dw->flag & PART_DUPLIW_CURRENT) { dw->flag &= ~PART_DUPLIW_CURRENT; dw = MEM_dupallocN(dw); dw->flag |= PART_DUPLIW_CURRENT; BLI_addhead(&part->dupliweights, dw); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); break; } } @@ -458,13 +458,13 @@ void PARTICLE_OT_dupliob_copy(wmOperatorType *ot) ot->exec = copy_particle_dupliob_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; ParticleSettings *part; ParticleDupliWeight *dw; @@ -472,7 +472,7 @@ static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; part = psys->part; - for (dw=part->dupliweights.first; dw; dw=dw->next) { + for (dw = part->dupliweights.first; dw; dw = dw->next) { if (dw->flag & PART_DUPLIW_CURRENT) { BLI_remlink(&part->dupliweights, dw); MEM_freeN(dw); @@ -485,7 +485,7 @@ static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) if (dw) dw->flag |= PART_DUPLIW_CURRENT; - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); return OPERATOR_FINISHED; } @@ -501,7 +501,7 @@ void PARTICLE_OT_dupliob_remove(wmOperatorType *ot) ot->exec = remove_particle_dupliob_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move down particle dupliweight operator *********************/ @@ -509,7 +509,7 @@ void PARTICLE_OT_dupliob_remove(wmOperatorType *ot) static int dupliob_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys= ptr.data; + ParticleSystem *psys = ptr.data; ParticleSettings *part; ParticleDupliWeight *dw; @@ -517,12 +517,12 @@ static int dupliob_move_down_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_CANCELLED; part = psys->part; - for (dw=part->dupliweights.first; dw; dw=dw->next) { + for (dw = part->dupliweights.first; dw; dw = dw->next) { if (dw->flag & PART_DUPLIW_CURRENT && dw->next) { BLI_remlink(&part->dupliweights, dw); BLI_insertlinkafter(&part->dupliweights, dw->next, dw); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); break; } } @@ -539,7 +539,7 @@ void PARTICLE_OT_dupliob_move_down(wmOperatorType *ot) ot->exec = dupliob_move_down_exec; /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ connect/disconnect hair operators *********************/ @@ -547,7 +547,7 @@ void PARTICLE_OT_dupliob_move_down(wmOperatorType *ot) static void disconnect_hair(Main *bmain, Scene *scene, Object *ob, ParticleSystem *psys) { ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); - ParticleEditSettings *pset= PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); ParticleData *pa; PTCacheEdit *edit; PTCacheEditPoint *point; @@ -563,9 +563,9 @@ static void disconnect_hair(Main *bmain, Scene *scene, Object *ob, ParticleSyste return; edit = psys->edit; - point= edit ? edit->points : NULL; + point = edit ? edit->points : NULL; - for (i=0, pa=psys->particles; itotpart; i++, pa++) { + for (i = 0, pa = psys->particles; i < psys->totpart; i++, pa++) { if (point) { ekey = point->keys; point++; @@ -573,7 +573,7 @@ static void disconnect_hair(Main *bmain, Scene *scene, Object *ob, ParticleSyste psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, pa, hairmat); - for (k=0, key=pa->hair; ktotkey; k++, key++) { + for (k = 0, key = pa->hair; k < pa->totkey; k++, key++) { mul_m4_v3(hairmat, key->co); if (ekey) { @@ -596,16 +596,16 @@ static void disconnect_hair(Main *bmain, Scene *scene, Object *ob, ParticleSyste static int disconnect_hair_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= ED_object_context(C); - ParticleSystem *psys= NULL; + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_context(C); + ParticleSystem *psys = NULL; const bool all = RNA_boolean_get(op->ptr, "all"); if (!ob) return OPERATOR_CANCELLED; if (all) { - for (psys=ob->particlesystem.first; psys; psys=psys->next) { + for (psys = ob->particlesystem.first; psys; psys = psys->next) { disconnect_hair(bmain, scene, ob, psys); } } @@ -615,7 +615,7 @@ static int disconnect_hair_exec(bContext *C, wmOperator *op) } DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); return OPERATOR_FINISHED; } @@ -645,7 +645,7 @@ static bool remap_hair_emitter(Main *bmain, Scene *scene, Object *ob, ParticleSy ParticleData *pa, *tpa; PTCacheEditPoint *edit_point; PTCacheEditKey *ekey; - BVHTreeFromMesh bvhtree= {NULL}; + BVHTreeFromMesh bvhtree = {NULL}; MFace *mface = NULL, *mf; MEdge *medge = NULL, *me; MVert *mvert; @@ -690,7 +690,7 @@ static bool remap_hair_emitter(Main *bmain, Scene *scene, Object *ob, ParticleSy mvert = dm->getVertArray(dm); /* convert to global coordinates */ - for (i=0; igetNumTessFaces(dm) != 0) { @@ -782,7 +782,7 @@ static bool remap_hair_emitter(Main *bmain, Scene *scene, Object *ob, ParticleSy sub_v3_v3v3(offset, nearest.co, from_co); if (edit_point) { - for (k=0, key=pa->hair, tkey=tpa->hair, ekey = edit_point->keys; ktotkey; k++, key++, tkey++, ekey++) { + for (k = 0, key = pa->hair, tkey = tpa->hair, ekey = edit_point->keys; k < tpa->totkey; k++, key++, tkey++, ekey++) { float co_orig[3]; if (from_global) @@ -801,7 +801,7 @@ static bool remap_hair_emitter(Main *bmain, Scene *scene, Object *ob, ParticleSy edit_point++; } else { - for (k=0, key=pa->hair, tkey=tpa->hair; ktotkey; k++, key++, tkey++) { + for (k = 0, key = pa->hair, tkey = tpa->hair; k < tpa->totkey; k++, key++, tkey++) { float co_orig[3]; if (from_global) @@ -845,9 +845,9 @@ static bool connect_hair(Main *bmain, Scene *scene, Object *ob, ParticleSystem * static int connect_hair_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); - Scene *scene= CTX_data_scene(C); - Object *ob= ED_object_context(C); - ParticleSystem *psys= NULL; + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_context(C); + ParticleSystem *psys = NULL; const bool all = RNA_boolean_get(op->ptr, "all"); bool any_connected = false; @@ -855,7 +855,7 @@ static int connect_hair_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; if (all) { - for (psys=ob->particlesystem.first; psys; psys=psys->next) { + for (psys = ob->particlesystem.first; psys; psys = psys->next) { any_connected |= connect_hair(bmain, scene, ob, psys); } } @@ -871,7 +871,7 @@ static int connect_hair_exec(bContext *C, wmOperator *op) } DAG_id_tag_update(&ob->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); return OPERATOR_FINISHED; } @@ -922,7 +922,7 @@ static void copy_particle_edit(Main *bmain, Scene *scene, Object *ob, ParticleSy LOOP_POINTS { HairKey *hkey = pa->hair; - point->keys= MEM_dupallocN(point->keys); + point->keys = MEM_dupallocN(point->keys); LOOP_KEYS { key->co = hkey->co; key->time = &hkey->time; @@ -1004,7 +1004,7 @@ static bool copy_particle_systems_to_object(Main *bmain, #define PSYS_FROM_NEXT(cur) (single_psys_from ? NULL : (cur)->next) totpsys = single_psys_from ? 1 : BLI_listbase_count(&ob_from->particlesystem); - tmp_psys = MEM_mallocN(sizeof(ParticleSystem*) * totpsys, "temporary particle system array"); + tmp_psys = MEM_mallocN(sizeof(ParticleSystem *) * totpsys, "temporary particle system array"); cdmask = 0; for (psys_from = PSYS_FROM_FIRST, i = 0; @@ -1070,7 +1070,7 @@ static bool copy_particle_systems_to_object(Main *bmain, psys; psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i) { - float (*from_mat)[4], (*to_mat)[4]; + float(*from_mat)[4], (*to_mat)[4]; switch (space) { case PAR_COPY_SPACE_OBJECT: @@ -1089,8 +1089,8 @@ static bool copy_particle_systems_to_object(Main *bmain, } if (ob_from != ob_to) { remap_hair_emitter( - bmain, scene, ob_from, psys_from, ob_to, psys, psys->edit, - from_mat, to_mat, psys_from->flag & PSYS_GLOBAL_HAIR, psys->flag & PSYS_GLOBAL_HAIR); + bmain, scene, ob_from, psys_from, ob_to, psys, psys->edit, + from_mat, to_mat, psys_from->flag & PSYS_GLOBAL_HAIR, psys->flag & PSYS_GLOBAL_HAIR); } /* tag for recalc */ @@ -1105,7 +1105,7 @@ static bool copy_particle_systems_to_object(Main *bmain, return true; } -static int copy_particle_systems_poll(bContext *C) +static bool copy_particle_systems_poll(bContext *C) { Object *ob; if (!ED_operator_object_active_editable(C)) @@ -1182,7 +1182,7 @@ void PARTICLE_OT_copy_particle_systems(wmOperatorType *ot) RNA_def_boolean(ot->srna, "use_active", false, "Use Active", "Use the active particle system from the context"); } -static int duplicate_particle_systems_poll(bContext *C) +static bool duplicate_particle_systems_poll(bContext *C) { if (!ED_operator_object_active_editable(C)) { return false; diff --git a/source/blender/editors/physics/physics_fluid.c b/source/blender/editors/physics/physics_fluid.c index c740fc0667e5..1cd2528b3ca5 100644 --- a/source/blender/editors/physics/physics_fluid.c +++ b/source/blender/editors/physics/physics_fluid.c @@ -430,7 +430,7 @@ static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), Fluid for (fobj=fobjects->first; fobj; fobj=fobj->next) { Object *ob = fobj->object; FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - float active= (float) ((fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE) > 0 ? 1 : 0); + float active = (float) ((fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE) ? 1 : 0); float rot_d[3] = {0.f, 0.f, 0.f}, old_rot[3] = {0.f, 0.f, 0.f}; if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) @@ -1118,4 +1118,3 @@ void FLUID_OT_bake(wmOperatorType *ot) ot->exec = fluid_bake_exec; ot->poll = ED_operator_object_active_editable; } - diff --git a/source/blender/editors/physics/physics_ops.c b/source/blender/editors/physics/physics_ops.c index 7b86cb63f31f..910e461435c2 100644 --- a/source/blender/editors/physics/physics_ops.c +++ b/source/blender/editors/physics/physics_ops.c @@ -112,7 +112,7 @@ static void keymap_particle(wmKeyConfig *keyconf) wmKeyMapItem *kmi; wmKeyMap *keymap; - keymap = WM_keymap_find(keyconf, "Particle", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Particle", 0, 0); keymap->poll = PE_poll; kmi = WM_keymap_add_item(keymap, "PARTICLE_OT_select_all", AKEY, KM_PRESS, 0, 0); @@ -221,7 +221,7 @@ static void operatortypes_dynamicpaint(void) //static void keymap_pointcache(wmWindowManager *wm) //{ -// wmKeyMap *keymap = WM_keymap_find(wm, "Pointcache", 0, 0); +// wmKeyMap *keymap = WM_keymap_ensure(wm, "Pointcache", 0, 0); // // WM_keymap_add_item(keymap, "PHYSICS_OT_bake_all", AKEY, KM_PRESS, 0, 0); // WM_keymap_add_item(keymap, "PHYSICS_OT_free_all", PADPLUSKEY, KM_PRESS, KM_CTRL, 0); @@ -245,6 +245,3 @@ void ED_keymap_physics(wmKeyConfig *keyconf) keymap_particle(keyconf); //keymap_pointcache(keyconf); } - - - diff --git a/source/blender/editors/physics/physics_pointcache.c b/source/blender/editors/physics/physics_pointcache.c index 5205463b5ab3..51c5955d5079 100644 --- a/source/blender/editors/physics/physics_pointcache.c +++ b/source/blender/editors/physics/physics_pointcache.c @@ -56,12 +56,12 @@ #include "physics_intern.h" -static int ptcache_bake_all_poll(bContext *C) +static bool ptcache_bake_all_poll(bContext *C) { return CTX_data_scene(C) != NULL; } -static int ptcache_poll(bContext *C) +static bool ptcache_poll(bContext *C) { PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); return (ptr.data && ptr.id.data); @@ -469,4 +469,3 @@ void PTCACHE_OT_remove(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; } - diff --git a/source/blender/editors/physics/rigidbody_constraint.c b/source/blender/editors/physics/rigidbody_constraint.c index 85478673f96b..0c612cc58557 100644 --- a/source/blender/editors/physics/rigidbody_constraint.c +++ b/source/blender/editors/physics/rigidbody_constraint.c @@ -59,7 +59,7 @@ /* ********************************************** */ /* Helper API's for RigidBody Constraint Editing */ -static int ED_operator_rigidbody_con_active_poll(bContext *C) +static bool ED_operator_rigidbody_con_active_poll(bContext *C) { if (ED_operator_object_active_editable(C)) { Object *ob = CTX_data_active_object(C); diff --git a/source/blender/editors/physics/rigidbody_object.c b/source/blender/editors/physics/rigidbody_object.c index fa7298489b11..ec6de52ebc18 100644 --- a/source/blender/editors/physics/rigidbody_object.c +++ b/source/blender/editors/physics/rigidbody_object.c @@ -65,7 +65,7 @@ /* ********************************************** */ /* Helper API's for RigidBody Objects Editing */ -static int ED_operator_rigidbody_active_poll(bContext *C) +static bool ED_operator_rigidbody_active_poll(bContext *C) { if (ED_operator_object_active_editable(C)) { Object *ob = ED_object_active_context(C); @@ -75,7 +75,7 @@ static int ED_operator_rigidbody_active_poll(bContext *C) return 0; } -static int ED_operator_rigidbody_add_poll(bContext *C) +static bool ED_operator_rigidbody_add_poll(bContext *C) { if (ED_operator_object_active_editable(C)) { Object *ob = ED_object_active_context(C); diff --git a/source/blender/editors/physics/rigidbody_world.c b/source/blender/editors/physics/rigidbody_world.c index 8d5258a7522a..fe2be86dd98b 100644 --- a/source/blender/editors/physics/rigidbody_world.c +++ b/source/blender/editors/physics/rigidbody_world.c @@ -58,12 +58,12 @@ /* API */ /* check if there is an active rigid body world */ -static int ED_rigidbody_world_active_poll(bContext *C) +static bool ED_rigidbody_world_active_poll(bContext *C) { Scene *scene = CTX_data_scene(C); return (scene && scene->rigidbody_world); } -static int ED_rigidbody_world_add_poll(bContext *C) +static bool ED_rigidbody_world_add_poll(bContext *C) { Scene *scene = CTX_data_scene(C); return (scene && scene->rigidbody_world == NULL); diff --git a/source/blender/editors/render/render_intern.h b/source/blender/editors/render/render_intern.h index 2ffa6cadb3a3..a00ab7423862 100644 --- a/source/blender/editors/render/render_intern.h +++ b/source/blender/editors/render/render_intern.h @@ -103,4 +103,3 @@ void RENDER_OT_view_cancel(struct wmOperatorType *ot); void RENDER_OT_opengl(struct wmOperatorType *ot); #endif /* __RENDER_INTERN_H__ */ - diff --git a/source/blender/editors/render/render_ops.c b/source/blender/editors/render/render_ops.c index 9a2549fca81d..af3786a73f72 100644 --- a/source/blender/editors/render/render_ops.c +++ b/source/blender/editors/render/render_ops.c @@ -98,4 +98,3 @@ void ED_operatortypes_render(void) /* render_opengl.c */ WM_operatortype_append(RENDER_OT_opengl); } - diff --git a/source/blender/editors/render/render_preview.c b/source/blender/editors/render/render_preview.c index 808e36a0d904..e1042f17229f 100644 --- a/source/blender/editors/render/render_preview.c +++ b/source/blender/editors/render/render_preview.c @@ -1306,4 +1306,3 @@ void ED_preview_kill_jobs(wmWindowManager *wm, Main *bmain) ED_viewport_render_kill_jobs(wm, bmain, false); } - diff --git a/source/blender/editors/render/render_shading.c b/source/blender/editors/render/render_shading.c index 2083317f6a77..5b198774b715 100644 --- a/source/blender/editors/render/render_shading.c +++ b/source/blender/editors/render/render_shading.c @@ -682,7 +682,7 @@ void SCENE_OT_render_layer_remove(wmOperatorType *ot) /********************** render view operators *********************/ -static int render_view_remove_poll(bContext *C) +static bool render_view_remove_poll(bContext *C) { Scene *scene = CTX_data_scene(C); @@ -760,7 +760,7 @@ static bool freestyle_linestyle_check_report(FreestyleLineSet *lineset, ReportLi return true; } -static int freestyle_active_module_poll(bContext *C) +static bool freestyle_active_module_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "freestyle_module", &RNA_FreestyleModuleSettings); FreestyleModuleConfig *module = ptr.data; @@ -893,7 +893,7 @@ void SCENE_OT_freestyle_lineset_add(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; } -static int freestyle_active_lineset_poll(bContext *C) +static bool freestyle_active_lineset_poll(bContext *C) { Scene *scene = CTX_data_scene(C); SceneRenderLayer *srl = BLI_findlink(&scene->r.layers, scene->r.actlay); @@ -1585,7 +1585,7 @@ static int envmap_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED return OPERATOR_RUNNING_MODAL; } -static int envmap_save_poll(bContext *C) +static bool envmap_save_poll(bContext *C) { Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data; @@ -1639,7 +1639,7 @@ static int envmap_clear_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int envmap_clear_poll(bContext *C) +static bool envmap_clear_poll(bContext *C) { Tex *tex = CTX_data_pointer_get_type(C, "texture", &RNA_Texture).data; @@ -1858,7 +1858,7 @@ static int copy_mtex_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int copy_mtex_poll(bContext *C) +static bool copy_mtex_poll(bContext *C) { ID *id = CTX_data_pointer_get_type(C, "texture_slot", &RNA_TextureSlot).id.data; @@ -1926,4 +1926,3 @@ void TEXTURE_OT_slot_paste(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; } - diff --git a/source/blender/editors/render/render_view.c b/source/blender/editors/render/render_view.c index ffb982ce8c2e..c43083a16168 100644 --- a/source/blender/editors/render/render_view.c +++ b/source/blender/editors/render/render_view.c @@ -350,4 +350,3 @@ void RENDER_OT_view_show(struct wmOperatorType *ot) ot->invoke = render_view_show_invoke; ot->poll = ED_operator_screenactive; } - diff --git a/source/blender/editors/screen/area.c b/source/blender/editors/screen/area.c index 6e4cbf27e287..5b6a81328fa4 100644 --- a/source/blender/editors/screen/area.c +++ b/source/blender/editors/screen/area.c @@ -1375,7 +1375,7 @@ static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ListBase *hand /* XXX it would be good to have boundbox checks for some of these... */ if (flag & ED_KEYMAP_UI) { - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "User Interface", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "User Interface", 0, 0); WM_event_add_keymap_handler(handlers, keymap); /* user interface widgets */ @@ -1383,12 +1383,12 @@ static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ListBase *hand } if (flag & ED_KEYMAP_VIEW2D) { /* 2d-viewport handling+manipulation */ - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "View2D", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "View2D", 0, 0); WM_event_add_keymap_handler(handlers, keymap); } if (flag & ED_KEYMAP_MARKERS) { /* time-markers */ - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "Markers", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Markers", 0, 0); /* time space only has this keymap, the others get a boundbox restricted map */ if (sa->spacetype != SPACE_TIME) { @@ -1406,12 +1406,12 @@ static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ListBase *hand } if (flag & ED_KEYMAP_ANIMATION) { /* frame changing and timeline operators (for time spaces) */ - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "Animation", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Animation", 0, 0); WM_event_add_keymap_handler(handlers, keymap); } if (flag & ED_KEYMAP_FRAMES) { /* frame changing/jumping (for all spaces) */ - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "Frames", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Frames", 0, 0); WM_event_add_keymap_handler(handlers, keymap); } if (flag & ED_KEYMAP_GPENCIL) { @@ -1423,15 +1423,15 @@ static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ListBase *hand * For now, it's easier to just include both, * since you hardly want one without the other. */ - wmKeyMap *keymap_general = WM_keymap_find(wm->defaultconf, "Grease Pencil", 0, 0); - wmKeyMap *keymap_edit = WM_keymap_find(wm->defaultconf, "Grease Pencil Stroke Edit Mode", 0, 0); + wmKeyMap *keymap_general = WM_keymap_ensure(wm->defaultconf, "Grease Pencil", 0, 0); + wmKeyMap *keymap_edit = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Edit Mode", 0, 0); WM_event_add_keymap_handler(handlers, keymap_general); WM_event_add_keymap_handler(handlers, keymap_edit); } if (flag & ED_KEYMAP_HEADER) { /* standard keymap for headers regions */ - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "Header", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Header", 0, 0); WM_event_add_keymap_handler(handlers, keymap); } } @@ -2024,7 +2024,7 @@ void ED_region_panels_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy); - keymap = WM_keymap_find(wm->defaultconf, "View2D Buttons List", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "View2D Buttons List", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } diff --git a/source/blender/editors/screen/screen_context.c b/source/blender/editors/screen/screen_context.c index b90430f27e22..a61b71beff1b 100644 --- a/source/blender/editors/screen/screen_context.c +++ b/source/blender/editors/screen/screen_context.c @@ -638,4 +638,3 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult return -1; /* found but not available */ } - diff --git a/source/blender/editors/screen/screen_draw.c b/source/blender/editors/screen/screen_draw.c index 12f45faee942..682a7a1f8601 100644 --- a/source/blender/editors/screen/screen_draw.c +++ b/source/blender/editors/screen/screen_draw.c @@ -352,4 +352,3 @@ void ED_screen_draw_split_preview(ScrArea *sa, const int dir, const float fac) glEnd(); glDisable(GL_BLEND); } - diff --git a/source/blender/editors/screen/screen_edit.c b/source/blender/editors/screen/screen_edit.c index 0e32ec3c34f9..e4d748afecf9 100644 --- a/source/blender/editors/screen/screen_edit.c +++ b/source/blender/editors/screen/screen_edit.c @@ -1063,7 +1063,7 @@ static void screen_cursor_set(wmWindow *win, const wmEvent *event) ScrArea *sa; for (sa = win->screen->areabase.first; sa; sa = sa->next) - if ((az = is_in_area_actionzone(sa, &event->x))) + if ((az = ED_area_actionzone_find_xy(sa, &event->x))) break; if (sa) { @@ -1104,10 +1104,13 @@ void ED_screen_set_subwinactive(bContext *C, const wmEvent *event) int oldswin = scr->subwinactive; for (sa = scr->areabase.first; sa; sa = sa->next) { - if (event->x > sa->totrct.xmin && event->x < sa->totrct.xmax) - if (event->y > sa->totrct.ymin && event->y < sa->totrct.ymax) - if (NULL == is_in_area_actionzone(sa, &event->x)) + if (event->x > sa->totrct.xmin && event->x < sa->totrct.xmax) { + if (event->y > sa->totrct.ymin && event->y < sa->totrct.ymax) { + if (NULL == ED_area_actionzone_refresh_xy(sa, &event->x)) { break; + } + } + } } if (sa) { /* make overlap active when mouse over */ @@ -1166,7 +1169,7 @@ int ED_screen_area_active(const bContext *C) ScrArea *sa = CTX_wm_area(C); if (win && sc && sa) { - AZone *az = is_in_area_actionzone(sa, &win->eventstate->x); + AZone *az = ED_area_actionzone_find_xy(sa, &win->eventstate->x); ARegion *ar; if (az && az->type == AZONE_REGION) @@ -1444,6 +1447,10 @@ bool ED_screen_delete_scene(bContext *C, Scene *scene) Main *bmain = CTX_data_main(C); Scene *newscene; + /* kill running jobs */ + wmWindowManager *wm = CTX_wm_manager(C); + WM_jobs_kill_type(wm, scene, WM_JOB_TYPE_ANY); + if (scene->id.prev) newscene = scene->id.prev; else if (scene->id.next) diff --git a/source/blender/editors/screen/screen_intern.h b/source/blender/editors/screen/screen_intern.h index 436fa9bcd05d..a7cd97139734 100644 --- a/source/blender/editors/screen/screen_intern.h +++ b/source/blender/editors/screen/screen_intern.h @@ -61,7 +61,8 @@ ScrEdge *screen_find_active_scredge(bScreen *sc, const int winsize_x, const int winsize_y, const int mx, const int my); -struct AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2]); +struct AZone *ED_area_actionzone_find_xy(ScrArea *sa, const int xy[2]); +struct AZone *ED_area_actionzone_refresh_xy(ScrArea *sa, const int xy[2]); /* screen_context.c */ int ed_screen_context( @@ -71,7 +72,6 @@ extern const char *screen_context_dir[]; /* doc access */ /* screendump.c */ void SCREEN_OT_screenshot(struct wmOperatorType *ot); -void SCREEN_OT_screencast(struct wmOperatorType *ot); /* screen_ops.c */ void region_blend_start(struct bContext *C, struct ScrArea *sa, struct ARegion *ar); diff --git a/source/blender/editors/screen/screen_ops.c b/source/blender/editors/screen/screen_ops.c index e76ef3faa59a..d3d486405c5a 100644 --- a/source/blender/editors/screen/screen_ops.c +++ b/source/blender/editors/screen/screen_ops.c @@ -95,7 +95,7 @@ /** \name Public Poll API * \{ */ -int ED_operator_regionactive(bContext *C) +bool ED_operator_regionactive(bContext *C) { if (CTX_wm_window(C) == NULL) return 0; if (CTX_wm_screen(C) == NULL) return 0; @@ -103,7 +103,7 @@ int ED_operator_regionactive(bContext *C) return 1; } -int ED_operator_areaactive(bContext *C) +bool ED_operator_areaactive(bContext *C) { if (CTX_wm_window(C) == NULL) return 0; if (CTX_wm_screen(C) == NULL) return 0; @@ -111,7 +111,7 @@ int ED_operator_areaactive(bContext *C) return 1; } -int ED_operator_screenactive(bContext *C) +bool ED_operator_screenactive(bContext *C) { if (CTX_wm_window(C) == NULL) return 0; if (CTX_wm_screen(C) == NULL) return 0; @@ -119,7 +119,7 @@ int ED_operator_screenactive(bContext *C) } /* XXX added this to prevent anim state to change during renders */ -static int ED_operator_screenactive_norender(bContext *C) +static bool ED_operator_screenactive_norender(bContext *C) { if (G.is_rendering) return 0; if (CTX_wm_window(C) == NULL) return 0; @@ -128,7 +128,7 @@ static int ED_operator_screenactive_norender(bContext *C) } /* when mouse is over area-edge */ -int ED_operator_screen_mainwinactive(bContext *C) +bool ED_operator_screen_mainwinactive(bContext *C) { bScreen *screen; if (CTX_wm_window(C) == NULL) return 0; @@ -138,7 +138,7 @@ int ED_operator_screen_mainwinactive(bContext *C) return 1; } -int ED_operator_scene(bContext *C) +bool ED_operator_scene(bContext *C) { Scene *scene = CTX_data_scene(C); if (scene) @@ -146,7 +146,7 @@ int ED_operator_scene(bContext *C) return 0; } -int ED_operator_scene_editable(bContext *C) +bool ED_operator_scene_editable(bContext *C) { Scene *scene = CTX_data_scene(C); if (scene && !ID_IS_LINKED(scene)) @@ -154,7 +154,7 @@ int ED_operator_scene_editable(bContext *C) return 0; } -int ED_operator_objectmode(bContext *C) +bool ED_operator_objectmode(bContext *C) { Scene *scene = CTX_data_scene(C); Object *obact = CTX_data_active_object(C); @@ -181,12 +181,12 @@ static bool ed_spacetype_test(bContext *C, int type) return 0; } -int ED_operator_view3d_active(bContext *C) +bool ED_operator_view3d_active(bContext *C) { return ed_spacetype_test(C, SPACE_VIEW3D); } -int ED_operator_region_view3d_active(bContext *C) +bool ED_operator_region_view3d_active(bContext *C) { if (CTX_wm_region_view3d(C)) return true; @@ -196,7 +196,7 @@ int ED_operator_region_view3d_active(bContext *C) } /* generic for any view2d which uses anim_ops */ -int ED_operator_animview_active(bContext *C) +bool ED_operator_animview_active(bContext *C) { if (ED_operator_areaactive(C)) { SpaceLink *sl = (SpaceLink *)CTX_wm_space_data(C); @@ -208,17 +208,17 @@ int ED_operator_animview_active(bContext *C) return 0; } -int ED_operator_timeline_active(bContext *C) +bool ED_operator_timeline_active(bContext *C) { return ed_spacetype_test(C, SPACE_TIME); } -int ED_operator_outliner_active(bContext *C) +bool ED_operator_outliner_active(bContext *C) { return ed_spacetype_test(C, SPACE_OUTLINER); } -int ED_operator_outliner_active_no_editobject(bContext *C) +bool ED_operator_outliner_active_no_editobject(bContext *C) { if (ed_spacetype_test(C, SPACE_OUTLINER)) { Object *ob = ED_object_active_context(C); @@ -231,22 +231,22 @@ int ED_operator_outliner_active_no_editobject(bContext *C) return 0; } -int ED_operator_file_active(bContext *C) +bool ED_operator_file_active(bContext *C) { return ed_spacetype_test(C, SPACE_FILE); } -int ED_operator_action_active(bContext *C) +bool ED_operator_action_active(bContext *C) { return ed_spacetype_test(C, SPACE_ACTION); } -int ED_operator_buttons_active(bContext *C) +bool ED_operator_buttons_active(bContext *C) { return ed_spacetype_test(C, SPACE_BUTS); } -int ED_operator_node_active(bContext *C) +bool ED_operator_node_active(bContext *C) { SpaceNode *snode = CTX_wm_space_node(C); @@ -256,7 +256,7 @@ int ED_operator_node_active(bContext *C) return 0; } -int ED_operator_node_editable(bContext *C) +bool ED_operator_node_editable(bContext *C) { SpaceNode *snode = CTX_wm_space_node(C); @@ -266,80 +266,80 @@ int ED_operator_node_editable(bContext *C) return 0; } -int ED_operator_graphedit_active(bContext *C) +bool ED_operator_graphedit_active(bContext *C) { return ed_spacetype_test(C, SPACE_IPO); } -int ED_operator_sequencer_active(bContext *C) +bool ED_operator_sequencer_active(bContext *C) { return ed_spacetype_test(C, SPACE_SEQ); } -int ED_operator_sequencer_active_editable(bContext *C) +bool ED_operator_sequencer_active_editable(bContext *C) { return ed_spacetype_test(C, SPACE_SEQ) && ED_operator_scene_editable(C); } -int ED_operator_image_active(bContext *C) +bool ED_operator_image_active(bContext *C) { return ed_spacetype_test(C, SPACE_IMAGE); } -int ED_operator_nla_active(bContext *C) +bool ED_operator_nla_active(bContext *C) { return ed_spacetype_test(C, SPACE_NLA); } -int ED_operator_logic_active(bContext *C) +bool ED_operator_logic_active(bContext *C) { return ed_spacetype_test(C, SPACE_LOGIC); } -int ED_operator_info_active(bContext *C) +bool ED_operator_info_active(bContext *C) { return ed_spacetype_test(C, SPACE_INFO); } -int ED_operator_console_active(bContext *C) +bool ED_operator_console_active(bContext *C) { return ed_spacetype_test(C, SPACE_CONSOLE); } -static int ed_object_hidden(Object *ob) +static bool ed_object_hidden(Object *ob) { /* if hidden but in edit mode, we still display, can happen with animation */ return ((ob->restrictflag & OB_RESTRICT_VIEW) && !(ob->mode & OB_MODE_EDIT)); } -int ED_operator_object_active(bContext *C) +bool ED_operator_object_active(bContext *C) { Object *ob = ED_object_active_context(C); return ((ob != NULL) && !ed_object_hidden(ob)); } -int ED_operator_object_active_editable(bContext *C) +bool ED_operator_object_active_editable(bContext *C) { Object *ob = ED_object_active_context(C); return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob)); } -int ED_operator_object_active_editable_mesh(bContext *C) +bool ED_operator_object_active_editable_mesh(bContext *C) { Object *ob = ED_object_active_context(C); return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) && (ob->type == OB_MESH) && !ID_IS_LINKED(ob->data)); } -int ED_operator_object_active_editable_font(bContext *C) +bool ED_operator_object_active_editable_font(bContext *C) { Object *ob = ED_object_active_context(C); return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) && (ob->type == OB_FONT)); } -int ED_operator_editmesh(bContext *C) +bool ED_operator_editmesh(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_MESH) @@ -347,12 +347,12 @@ int ED_operator_editmesh(bContext *C) return 0; } -int ED_operator_editmesh_view3d(bContext *C) +bool ED_operator_editmesh_view3d(bContext *C) { return ED_operator_editmesh(C) && ED_operator_view3d_active(C); } -int ED_operator_editmesh_region_view3d(bContext *C) +bool ED_operator_editmesh_region_view3d(bContext *C) { if (ED_operator_editmesh(C) && CTX_wm_region_view3d(C)) return 1; @@ -361,7 +361,7 @@ int ED_operator_editmesh_region_view3d(bContext *C) return 0; } -int ED_operator_editarmature(bContext *C) +bool ED_operator_editarmature(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_ARMATURE) @@ -376,7 +376,7 @@ int ED_operator_editarmature(bContext *C) * when it comes to transforming bones, but managing bones layers/groups * can be left for pose mode only. (not weight paint mode) */ -int ED_operator_posemode_exclusive(bContext *C) +bool ED_operator_posemode_exclusive(bContext *C) { Object *obact = CTX_data_active_object(C); @@ -394,7 +394,7 @@ int ED_operator_posemode_exclusive(bContext *C) /* allows for pinned pose objects to be used in the object buttons * and the non-active pose object to be used in the 3D view */ -int ED_operator_posemode_context(bContext *C) +bool ED_operator_posemode_context(bContext *C) { Object *obpose = ED_pose_object_from_context(C); @@ -407,7 +407,7 @@ int ED_operator_posemode_context(bContext *C) return 0; } -int ED_operator_posemode(bContext *C) +bool ED_operator_posemode(bContext *C) { Object *obact = CTX_data_active_object(C); @@ -423,7 +423,7 @@ int ED_operator_posemode(bContext *C) return 0; } -int ED_operator_posemode_local(bContext *C) +bool ED_operator_posemode_local(bContext *C) { if (ED_operator_posemode(C)) { Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C)); @@ -435,21 +435,21 @@ int ED_operator_posemode_local(bContext *C) } /* wrapper for ED_space_image_show_uvedit */ -int ED_operator_uvedit(bContext *C) +bool ED_operator_uvedit(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); Object *obedit = CTX_data_edit_object(C); return ED_space_image_show_uvedit(sima, obedit); } -int ED_operator_uvedit_space_image(bContext *C) +bool ED_operator_uvedit_space_image(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); Object *obedit = CTX_data_edit_object(C); return sima && ED_space_image_show_uvedit(sima, obedit); } -int ED_operator_uvmap(bContext *C) +bool ED_operator_uvmap(bContext *C) { Object *obedit = CTX_data_edit_object(C); BMEditMesh *em = NULL; @@ -465,7 +465,7 @@ int ED_operator_uvmap(bContext *C) return false; } -int ED_operator_editsurfcurve(bContext *C) +bool ED_operator_editsurfcurve(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && ELEM(obedit->type, OB_CURVE, OB_SURF)) @@ -473,7 +473,7 @@ int ED_operator_editsurfcurve(bContext *C) return 0; } -int ED_operator_editsurfcurve_region_view3d(bContext *C) +bool ED_operator_editsurfcurve_region_view3d(bContext *C) { if (ED_operator_editsurfcurve(C) && CTX_wm_region_view3d(C)) return 1; @@ -482,7 +482,7 @@ int ED_operator_editsurfcurve_region_view3d(bContext *C) return 0; } -int ED_operator_editcurve(bContext *C) +bool ED_operator_editcurve(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_CURVE) @@ -490,7 +490,7 @@ int ED_operator_editcurve(bContext *C) return 0; } -int ED_operator_editcurve_3d(bContext *C) +bool ED_operator_editcurve_3d(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_CURVE) { @@ -501,7 +501,7 @@ int ED_operator_editcurve_3d(bContext *C) return 0; } -int ED_operator_editsurf(bContext *C) +bool ED_operator_editsurf(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_SURF) @@ -509,7 +509,7 @@ int ED_operator_editsurf(bContext *C) return 0; } -int ED_operator_editfont(bContext *C) +bool ED_operator_editfont(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_FONT) @@ -517,7 +517,7 @@ int ED_operator_editfont(bContext *C) return 0; } -int ED_operator_editlattice(bContext *C) +bool ED_operator_editlattice(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_LATTICE) @@ -525,7 +525,7 @@ int ED_operator_editlattice(bContext *C) return 0; } -int ED_operator_editmball(bContext *C) +bool ED_operator_editmball(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_MBALL) @@ -533,7 +533,7 @@ int ED_operator_editmball(bContext *C) return 0; } -int ED_operator_mask(bContext *C) +bool ED_operator_mask(bContext *C) { ScrArea *sa = CTX_wm_area(C); if (sa && sa->spacedata.first) { @@ -567,7 +567,7 @@ int ED_operator_mask(bContext *C) /** \name Internal Screen Utilities * \{ */ -static int screen_active_editable(bContext *C) +static bool screen_active_editable(bContext *C) { if (ED_operator_screenactive(C)) { /* no full window splitting allowed */ @@ -631,7 +631,7 @@ typedef struct sActionzoneData { } sActionzoneData; /* quick poll to save operators to be created and handled */ -static int actionzone_area_poll(bContext *C) +static bool actionzone_area_poll(bContext *C) { wmWindow *win = CTX_wm_window(C); ScrArea *sa = CTX_wm_area(C); @@ -665,7 +665,7 @@ static void fullscreen_click_rcti_init(rcti *rect, const short x1, const short y BLI_rcti_init(rect, x, x + icon_size, y, y + icon_size); } -AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2]) +static AZone *area_actionzone_refresh_xy(ScrArea *sa, const int xy[2], const bool test_only) { AZone *az = NULL; @@ -673,49 +673,55 @@ AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2]) if (BLI_rcti_isect_pt_v(&az->rect, xy)) { if (az->type == AZONE_AREA) { /* no triangle intersect but a hotspot circle based on corner */ - int radius = (xy[0] - az->x1) * (xy[0] - az->x1) + (xy[1] - az->y1) * (xy[1] - az->y1); - - if (radius <= AZONESPOT * AZONESPOT) + int radius_sq = SQUARE(xy[0] - az->x1) + SQUARE(xy[1] - az->y1); + if (radius_sq <= SQUARE(AZONESPOT)) { break; + } } else if (az->type == AZONE_REGION) { break; } else if (az->type == AZONE_FULLSCREEN) { - int mouse_radius, spot_radius, fadein_radius, fadeout_radius; rcti click_rect; - fullscreen_click_rcti_init(&click_rect, az->x1, az->y1, az->x2, az->y2); + const bool click_isect = BLI_rcti_isect_pt_v(&click_rect, xy); - if (BLI_rcti_isect_pt_v(&click_rect, xy)) { - az->alpha = 1.0f; + if (test_only) { + if (click_isect) { + break; + } } else { - mouse_radius = (xy[0] - az->x2) * (xy[0] - az->x2) + (xy[1] - az->y2) * (xy[1] - az->y2); - spot_radius = AZONESPOT * AZONESPOT; - fadein_radius = AZONEFADEIN * AZONEFADEIN; - fadeout_radius = AZONEFADEOUT * AZONEFADEOUT; - - if (mouse_radius < spot_radius) { - az->alpha = 1.0f; - } - else if (mouse_radius < fadein_radius) { + if (click_isect) { az->alpha = 1.0f; } - else if (mouse_radius < fadeout_radius) { - az->alpha = 1.0f - ((float)(mouse_radius - fadein_radius)) / ((float)(fadeout_radius - fadein_radius)); - } else { - az->alpha = 0.0f; + const int mouse_sq = SQUARE(xy[0] - az->x2) + SQUARE(xy[1] - az->y2); + const int spot_sq = SQUARE(AZONESPOT); + const int fadein_sq = SQUARE(AZONEFADEIN); + const int fadeout_sq = SQUARE(AZONEFADEOUT); + + if (mouse_sq < spot_sq) { + az->alpha = 1.0f; + } + else if (mouse_sq < fadein_sq) { + az->alpha = 1.0f; + } + else if (mouse_sq < fadeout_sq) { + az->alpha = 1.0f - ((float)(mouse_sq - fadein_sq)) / ((float)(fadeout_sq - fadein_sq)); + } + else { + az->alpha = 0.0f; + } + + /* fade in/out but no click */ + az = NULL; } - /* fade in/out but no click */ - az = NULL; + /* XXX force redraw to show/hide the action zone */ + ED_area_tag_redraw(sa); + break; } - - /* XXX force redraw to show/hide the action zone */ - ED_area_tag_redraw(sa); - break; } } } @@ -723,6 +729,15 @@ AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2]) return az; } +AZone *ED_area_actionzone_find_xy(ScrArea *sa, const int xy[2]) +{ + return area_actionzone_refresh_xy(sa, xy, true); +} + +AZone *ED_area_actionzone_refresh_xy(ScrArea *sa, const int xy[2]) +{ + return area_actionzone_refresh_xy(sa, xy, false); +} static void actionzone_exit(wmOperator *op) { @@ -760,7 +775,7 @@ static void actionzone_apply(bContext *C, wmOperator *op, int type) static int actionzone_invoke(bContext *C, wmOperator *op, const wmEvent *event) { ScrArea *sa = CTX_wm_area(C); - AZone *az = is_in_area_actionzone(sa, &event->x); + AZone *az = ED_area_actionzone_find_xy(sa, &event->x); sActionzoneData *sad; /* quick escape */ @@ -817,7 +832,7 @@ static int actionzone_modal(bContext *C, wmOperator *op, const wmEvent *event) if (sad->az->type == AZONE_AREA) { /* once we drag outside the actionzone, register a gesture * check we're not on an edge so join finds the other area */ - is_gesture = ((is_in_area_actionzone(sad->sa1, &event->x) != sad->az) && + is_gesture = ((ED_area_actionzone_find_xy(sad->sa1, &event->x) != sad->az) && (screen_find_active_scredge(sc, winsize_x, winsize_y, event->x, event->y) == NULL)); } else { @@ -1640,8 +1655,11 @@ static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event) int dir; /* no full window splitting allowed */ - if (sc->state != SCREENNORMAL) - return OPERATOR_CANCELLED; + BLI_assert(sc->state == SCREENNORMAL); + + PropertyRNA *prop_dir = RNA_struct_find_property(op->ptr, "direction"); + PropertyRNA *prop_factor = RNA_struct_find_property(op->ptr, "factor"); + PropertyRNA *prop_cursor = RNA_struct_find_property(op->ptr, "cursor"); if (event->type == EVT_ACTIONZONE_AREA) { sActionzoneData *sad = event->customdata; @@ -1661,46 +1679,69 @@ static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event) /* prepare operator state vars */ if (sad->gesture_dir == 'n' || sad->gesture_dir == 's') { dir = 'h'; - RNA_float_set(op->ptr, "factor", ((float)(event->x - sad->sa1->v1->vec.x)) / (float)sad->sa1->winx); + RNA_property_float_set( + op->ptr, prop_factor, + ((float)(event->x - sad->sa1->v1->vec.x)) / (float)sad->sa1->winx); } else { dir = 'v'; - RNA_float_set(op->ptr, "factor", ((float)(event->y - sad->sa1->v1->vec.y)) / (float)sad->sa1->winy); + RNA_property_float_set( + op->ptr, prop_factor, + ((float)(event->y - sad->sa1->v1->vec.y)) / (float)sad->sa1->winy); } - RNA_enum_set(op->ptr, "direction", dir); + RNA_property_enum_set(op->ptr, prop_dir, dir); /* general init, also non-UI case, adds customdata, sets area and defaults */ - if (!area_split_init(C, op)) + if (!area_split_init(C, op)) { return OPERATOR_PASS_THROUGH; + } + } + else if (RNA_property_is_set(op->ptr, prop_dir)) { + ScrArea *sa = CTX_wm_area(C); + if (sa == NULL) { + return OPERATOR_CANCELLED; + } + dir = RNA_property_enum_get(op->ptr, prop_dir); + if (dir == 'h') { + RNA_property_float_set( + op->ptr, prop_factor, + ((float)(event->x - sa->v1->vec.x)) / (float)sa->winx); + } + else { + RNA_property_float_set( + op->ptr, prop_factor, + ((float)(event->y - sa->v1->vec.y)) / (float)sa->winy); + } + if (!area_split_init(C, op)) { + return OPERATOR_CANCELLED; + } } else { ScrEdge *actedge; - int x, y; + int event_co[2]; /* retrieve initial mouse coord, so we can find the active edge */ - if (RNA_struct_property_is_set(op->ptr, "mouse_x")) - x = RNA_int_get(op->ptr, "mouse_x"); - else - x = event->x; - - if (RNA_struct_property_is_set(op->ptr, "mouse_y")) - y = RNA_int_get(op->ptr, "mouse_y"); - else - y = event->x; + if (RNA_property_is_set(op->ptr, prop_cursor)) { + RNA_property_int_get_array(op->ptr, prop_cursor, event_co); + } + else { + copy_v2_v2_int(event_co, &event->x); + } - actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, x, y); - if (actedge == NULL) + actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, event_co[0], event_co[1]); + if (actedge == NULL) { return OPERATOR_CANCELLED; + } dir = scredge_is_horizontal(actedge) ? 'v' : 'h'; - RNA_enum_set(op->ptr, "direction", dir); + RNA_property_enum_set(op->ptr, prop_dir, dir); /* special case, adds customdata, sets defaults */ - if (!area_split_menu_init(C, op)) + if (!area_split_menu_init(C, op)) { return OPERATOR_CANCELLED; - + } } sd = (sAreaSplitData *)op->customdata; @@ -1898,8 +1939,7 @@ static void SCREEN_OT_area_split(wmOperatorType *ot) /* rna */ RNA_def_enum(ot->srna, "direction", prop_direction_items, 'h', "Direction", ""); RNA_def_float(ot->srna, "factor", 0.5f, 0.0, 1.0, "Factor", "", 0.0, 1.0); - RNA_def_int(ot->srna, "mouse_x", -100, INT_MIN, INT_MAX, "Mouse X", "", INT_MIN, INT_MAX); - RNA_def_int(ot->srna, "mouse_y", -100, INT_MIN, INT_MAX, "Mouse Y", "", INT_MIN, INT_MAX); + RNA_def_int_vector(ot->srna, "cursor", 2, NULL, INT_MIN, INT_MAX, "Cursor", "", INT_MIN, INT_MAX); } /** \} */ @@ -2950,8 +2990,7 @@ static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent uiItemFullO(layout, "SCREEN_OT_area_split", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr); /* store initial mouse cursor position */ - RNA_int_set(&ptr, "mouse_x", event->x); - RNA_int_set(&ptr, "mouse_y", event->y); + RNA_int_set_array(&ptr, "cursor", &event->x); uiItemFullO(layout, "SCREEN_OT_area_join", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr); /* mouse cursor on edge, '4' can fail on wide edges... */ @@ -4376,7 +4415,7 @@ static const EnumPropertyItem space_context_cycle_direction[] = { {0, NULL, 0, NULL, NULL} }; -static int space_context_cycle_poll(bContext *C) +static bool space_context_cycle_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); /* sa might be NULL if called out of window bounds */ @@ -4478,7 +4517,6 @@ void ED_operatortypes_screen(void) WM_operatortype_append(SCREEN_OT_back_to_previous); WM_operatortype_append(SCREEN_OT_spacedata_cleanup); WM_operatortype_append(SCREEN_OT_screenshot); - WM_operatortype_append(SCREEN_OT_screencast); WM_operatortype_append(SCREEN_OT_userpref_show); WM_operatortype_append(SCREEN_OT_region_blend); WM_operatortype_append(SCREEN_OT_space_context_cycle); @@ -4541,7 +4579,7 @@ static void keymap_modal_set(wmKeyConfig *keyconf) } -static int open_file_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool open_file_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_PATH) { if (drag->icon == ICON_FILE_BLEND) @@ -4566,7 +4604,7 @@ void ED_keymap_screen(wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* Screen Editing ------------------------------------------------ */ - keymap = WM_keymap_find(keyconf, "Screen Editing", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Screen Editing", 0, 0); RNA_int_set(WM_keymap_add_item(keymap, "SCREEN_OT_actionzone", LEFTMOUSE, KM_PRESS, 0, 0)->ptr, "modifier", 0); RNA_int_set(WM_keymap_add_item(keymap, "SCREEN_OT_actionzone", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0)->ptr, "modifier", 1); @@ -4589,12 +4627,12 @@ void ED_keymap_screen(wmKeyConfig *keyconf) /* Header Editing ------------------------------------------------ */ /* note: this is only used when the cursor is inside the header */ - keymap = WM_keymap_find(keyconf, "Header", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Header", 0, 0); WM_keymap_add_item(keymap, "SCREEN_OT_header_toolbox", RIGHTMOUSE, KM_PRESS, 0, 0); /* Screen General ------------------------------------------------ */ - keymap = WM_keymap_find(keyconf, "Screen", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Screen", 0, 0); /* standard timers */ WM_keymap_add_item(keymap, "SCREEN_OT_animation_step", TIMER0, KM_ANY, KM_ANY, 0); @@ -4610,7 +4648,6 @@ void ED_keymap_screen(wmKeyConfig *keyconf) RNA_boolean_set(kmi->ptr, "use_hide_panels", true); WM_keymap_add_item(keymap, "SCREEN_OT_screenshot", F3KEY, KM_PRESS, KM_CTRL, 0); - WM_keymap_add_item(keymap, "SCREEN_OT_screencast", F3KEY, KM_PRESS, KM_ALT, 0); kmi = WM_keymap_add_item(keymap, "SCREEN_OT_space_context_cycle", TABKEY, KM_PRESS, KM_CTRL, 0); RNA_enum_set(kmi->ptr, "direction", SPACE_CONTEXT_CYCLE_NEXT); @@ -4659,7 +4696,7 @@ void ED_keymap_screen(wmKeyConfig *keyconf) /* Anim Playback ------------------------------------------------ */ - keymap = WM_keymap_find(keyconf, "Frames", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Frames", 0, 0); /* frame offsets */ RNA_int_set(WM_keymap_add_item(keymap, "SCREEN_OT_frame_offset", UPARROWKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "delta", 10); @@ -4698,7 +4735,7 @@ void ED_keymap_screen(wmKeyConfig *keyconf) /* Alternative keys for animation and sequencer playing */ #if 0 /* XXX: disabled for restoring later... bad implementation */ - keymap = WM_keymap_find(keyconf, "Frames", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Frames", 0, 0); kmi = WM_keymap_add_item(keymap, "SCREEN_OT_animation_play", RIGHTARROWKEY, KM_PRESS, KM_ALT, 0); RNA_boolean_set(kmi->ptr, "cycle_speed", true); diff --git a/source/blender/editors/screen/screendump.c b/source/blender/editors/screen/screendump.c index ec01aceeb6c2..3ec2078a4d19 100644 --- a/source/blender/editors/screen/screendump.c +++ b/source/blender/editors/screen/screendump.c @@ -36,7 +36,6 @@ #include "BLI_blenlib.h" #include "BLI_utildefines.h" -#include "BLI_math.h" #include "IMB_imbuf_types.h" #include "IMB_imbuf.h" @@ -44,17 +43,14 @@ #include "DNA_scene_types.h" #include "DNA_screen_types.h" #include "DNA_space_types.h" -#include "DNA_userdef_types.h" #include "BKE_context.h" #include "BKE_global.h" #include "BKE_main.h" #include "BKE_image.h" #include "BKE_report.h" -#include "BKE_writeavi.h" #include "BIF_gl.h" -#include "BIF_glutil.h" #include "RNA_access.h" #include "RNA_define.h" @@ -64,9 +60,6 @@ #include "WM_types.h" #include "WM_api.h" -#include "PIL_time.h" - - #include "screen_intern.h" typedef struct ScreenshotData { @@ -232,7 +225,7 @@ static int screenshot_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED( char filepath[FILE_MAX] = "//screen"; if (G.relbase_valid) { BLI_strncpy(filepath, BKE_main_blendfile_path_from_global(), sizeof(filepath)); - BLI_replace_extension(filepath, sizeof(filepath), ""); /* strip '.blend' */ + BLI_path_extension_replace(filepath, sizeof(filepath), ""); /* strip '.blend' */ } RNA_string_set(op->ptr, "filepath", filepath); @@ -254,7 +247,7 @@ static void screenshot_cancel(bContext *UNUSED(C), wmOperator *op) screenshot_data_free(op); } -static bool screenshot_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop) +static bool screenshot_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop, void *UNUSED(user_data)) { const char *prop_id = RNA_property_identifier(prop); @@ -273,10 +266,10 @@ static void screenshot_draw(bContext *UNUSED(C), wmOperator *op) /* main draw call */ RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); - uiDefAutoButsRNA(layout, &ptr, screenshot_draw_check_prop, '\0'); + uiDefAutoButsRNA(layout, &ptr, screenshot_draw_check_prop, NULL, '\0'); } -static int screenshot_poll(bContext *C) +static bool screenshot_poll(bContext *C) { if (G.background) return false; @@ -305,259 +298,3 @@ void SCREEN_OT_screenshot(wmOperatorType *ot) RNA_def_boolean(ot->srna, "full", 1, "Full Screen", "Capture the whole window (otherwise only capture the active area)"); } - -/* *************** screenshot movie job ************************* */ - -typedef struct ScreenshotJob { - Main *bmain; - Scene *scene; - wmWindowManager *wm; - unsigned int *dumprect; - int x, y, dumpsx, dumpsy; - const short *stop; - const short *do_update; - ReportList reports; - - bMovieHandle *movie_handle; - void *movie_ctx; -} ScreenshotJob; - - -static void screenshot_freejob(void *sjv) -{ - ScreenshotJob *sj = sjv; - - if (sj->dumprect) - MEM_freeN(sj->dumprect); - - if (sj->movie_handle) { - bMovieHandle *mh = sj->movie_handle; - mh->end_movie(sj->movie_ctx); - mh->context_free(sj->movie_ctx); - } - - MEM_freeN(sj); -} - - -/* called before redraw notifiers, copies a new dumprect */ -static void screenshot_updatejob(void *sjv) -{ - ScreenshotJob *sj = sjv; - unsigned int *dumprect; - - if (sj->dumprect == NULL) { - dumprect = MEM_mallocN(sizeof(int) * sj->dumpsx * sj->dumpsy, "dumprect"); - screenshot_read_pixels(sj->x, sj->y, sj->dumpsx, sj->dumpsy, (unsigned char *)dumprect); - - sj->dumprect = dumprect; - } -} - - -/* only this runs inside thread */ -static void screenshot_startjob(void *sjv, short *stop, short *do_update, float *UNUSED(progress)) -{ - ScreenshotJob *sj = sjv; - RenderData rd = sj->scene->r; - bMovieHandle *mh = NULL; - - /* we need this as local variables for renderdata */ - rd.frs_sec = U.scrcastfps; - rd.frs_sec_base = 1.0f; - - if (BKE_imtype_is_movie(rd.im_format.imtype)) { - mh = BKE_movie_handle_get(sj->scene->r.im_format.imtype); - if (mh == NULL) { - printf("Movie format unsupported\n"); - return; - } - sj->movie_ctx = mh->context_create(); - sj->movie_handle = mh; - - if (!mh->start_movie(sj->movie_ctx, sj->scene, &rd, sj->dumpsx, sj->dumpsy, &sj->reports, false, "")) { - printf("screencast job stopped\n"); - return; - } - } - - sj->stop = stop; - sj->do_update = do_update; - - *do_update = true; /* wait for opengl rect */ - - while (*stop == 0) { - - if (sj->dumprect) { - - if (mh) { - if (mh->append_movie(sj->movie_ctx, &rd, rd.sfra, rd.cfra, (int *)sj->dumprect, - sj->dumpsx, sj->dumpsy, "", &sj->reports)) - { - BKE_reportf(&sj->reports, RPT_INFO, "Appended frame: %d", rd.cfra); - printf("Appended frame %d\n", rd.cfra); - } - else { - break; - } - } - else { - ImBuf *ibuf = IMB_allocImBuf(sj->dumpsx, sj->dumpsy, rd.im_format.planes, 0); - char name[FILE_MAX]; - int ok; - - BKE_image_path_from_imformat( - name, rd.pic, BKE_main_blendfile_path(sj->bmain), rd.cfra, - &rd.im_format, (rd.scemode & R_EXTENSION) != 0, true, NULL); - - ibuf->rect = sj->dumprect; - ok = BKE_imbuf_write(ibuf, name, &rd.im_format); - - if (ok == 0) { - printf("Write error: cannot save %s\n", name); - BKE_reportf(&sj->reports, RPT_INFO, "Write error: cannot save %s", name); - break; - } - else { - printf("Saved file: %s\n", name); - BKE_reportf(&sj->reports, RPT_INFO, "Saved file: %s", name); - } - - /* imbuf knows which rects are not part of ibuf */ - IMB_freeImBuf(ibuf); - } - - MEM_freeN(sj->dumprect); - sj->dumprect = NULL; - - *do_update = true; - - rd.cfra++; - - } - else - PIL_sleep_ms(U.scrcastwait); - } - - if (mh) { - mh->end_movie(sj->movie_ctx); - mh->context_free(sj->movie_ctx); - sj->movie_handle = NULL; - } - - BKE_report(&sj->reports, RPT_INFO, "Screencast job stopped"); -} - -/* Helper callback for drawing the cursor itself */ -static void screencast_draw_cursor(bContext *UNUSED(C), int x, int y, void *UNUSED(p_ptr)) -{ - - glPushMatrix(); - - glTranslatef((float)x, (float)y, 0.0f); - - - glEnable(GL_LINE_SMOOTH); - glEnable(GL_BLEND); - - glColor4ub(0, 0, 0, 32); - glutil_draw_filled_arc(0.0, M_PI * 2.0, 20, 40); - - glColor4ub(255, 255, 255, 128); - glutil_draw_lined_arc(0.0, M_PI * 2.0, 20, 40); - - glDisable(GL_BLEND); - glDisable(GL_LINE_SMOOTH); - - glPopMatrix(); -} - -/* Turn brush cursor in 3D view on/off */ -static void screencast_cursor_toggle(wmWindowManager *wm, short enable) -{ - static void *cursor = NULL; - - if (cursor && !enable) { - /* clear cursor */ - WM_paint_cursor_end(wm, cursor); - cursor = NULL; - } - else if (enable) { - /* enable cursor */ - cursor = WM_paint_cursor_activate(wm, NULL, screencast_draw_cursor, NULL); - } -} - -static void screenshot_endjob(void *sjv) -{ - ScreenshotJob *sj = sjv; - - screencast_cursor_toggle(sj->wm, 0); -} - - -static int screencast_exec(bContext *C, wmOperator *op) -{ - wmWindowManager *wm = CTX_wm_manager(C); - wmWindow *win = CTX_wm_window(C); - bScreen *screen = CTX_wm_screen(C); - wmJob *wm_job; - ScreenshotJob *sj; - - /* if called again, stop the running job */ - if (WM_jobs_test(wm, screen, WM_JOB_TYPE_SCREENCAST)) - WM_jobs_stop(wm, screen, screenshot_startjob); - - wm_job = WM_jobs_get(wm, win, screen, "Screencast", 0, WM_JOB_TYPE_SCREENCAST); - sj = MEM_callocN(sizeof(ScreenshotJob), "screenshot job"); - - /* setup sj */ - if (RNA_boolean_get(op->ptr, "full")) { - sj->x = 0; - sj->y = 0; - sj->dumpsx = WM_window_pixels_x(win); - sj->dumpsy = WM_window_pixels_y(win); - } - else { - ScrArea *curarea = CTX_wm_area(C); - sj->x = curarea->totrct.xmin; - sj->y = curarea->totrct.ymin; - sj->dumpsx = curarea->totrct.xmax - sj->x; - sj->dumpsy = curarea->totrct.ymax - sj->y; - } - sj->bmain = CTX_data_main(C); - sj->scene = CTX_data_scene(C); - sj->wm = wm; - - BKE_reports_init(&sj->reports, RPT_PRINT); - - /* setup job */ - WM_jobs_customdata_set(wm_job, sj, screenshot_freejob); - WM_jobs_timer(wm_job, 0.1, 0, NC_SCREEN | ND_SCREENCAST); - WM_jobs_callbacks(wm_job, screenshot_startjob, NULL, screenshot_updatejob, screenshot_endjob); - - WM_jobs_start(sj->wm, wm_job); - - screencast_cursor_toggle(sj->wm, 1); - - WM_event_add_notifier(C, NC_SCREEN | ND_SCREENCAST, screen); - - return OPERATOR_FINISHED; -} - -void SCREEN_OT_screencast(wmOperatorType *ot) -{ - ot->name = "Make Screencast"; - ot->idname = "SCREEN_OT_screencast"; - ot->description = "Capture a video of the active area or whole Blender window"; - - ot->invoke = WM_operator_confirm; - ot->exec = screencast_exec; - ot->poll = screenshot_poll; /* shared poll */ - - ot->flag = 0; - - RNA_def_property(ot->srna, "filepath", PROP_STRING, PROP_FILEPATH); - RNA_def_boolean(ot->srna, "full", 1, "Full Screen", - "Capture the whole window (otherwise only capture the active area)"); -} diff --git a/source/blender/editors/sculpt_paint/paint_cursor.c b/source/blender/editors/sculpt_paint/paint_cursor.c index 3c3b9e91ab96..f503ab372307 100644 --- a/source/blender/editors/sculpt_paint/paint_cursor.c +++ b/source/blender/editors/sculpt_paint/paint_cursor.c @@ -257,9 +257,10 @@ static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool prima int size; bool refresh; - eOverlayControlFlags invalid = (primary) ? (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) : - (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY); - + eOverlayControlFlags invalid = ( + (primary) ? + (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) : + (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY)); target = (primary) ? &primary_snap : &secondary_snap; refresh = @@ -495,9 +496,10 @@ static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom) -static int project_brush_radius(ViewContext *vc, - float radius, - const float location[3]) +static int project_brush_radius( + ViewContext *vc, + float radius, + const float location[3]) { float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2]; @@ -568,10 +570,8 @@ static bool sculpt_get_brush_geometry( if (hit) { Brush *brush = BKE_paint_brush(paint); - *pixel_radius = - project_brush_radius(vc, - BKE_brush_unprojected_radius_get(scene, brush), - location); + *pixel_radius = project_brush_radius( + vc, BKE_brush_unprojected_radius_get(scene, brush), location); if (*pixel_radius == 0) *pixel_radius = BKE_brush_size_get(scene, brush); @@ -590,15 +590,18 @@ static bool sculpt_get_brush_geometry( /* Draw an overlay that shows what effect the brush's texture will * have on brush strength */ -static void paint_draw_tex_overlay(UnifiedPaintSettings *ups, Brush *brush, - ViewContext *vc, int x, int y, float zoom, bool col, bool primary) +static void paint_draw_tex_overlay( + UnifiedPaintSettings *ups, Brush *brush, + ViewContext *vc, int x, int y, float zoom, bool col, bool primary) { rctf quad; /* check for overlay mode */ MTex *mtex = (primary) ? &brush->mtex : &brush->mask_mtex; - bool valid = (primary) ? (brush->overlay_flags & BRUSH_OVERLAY_PRIMARY) != 0 : - (brush->overlay_flags & BRUSH_OVERLAY_SECONDARY) != 0; + bool valid = ( + (primary) ? + (brush->overlay_flags & BRUSH_OVERLAY_PRIMARY) != 0 : + (brush->overlay_flags & BRUSH_OVERLAY_SECONDARY) != 0); int overlay_alpha = (primary) ? brush->texture_overlay_alpha : brush->mask_overlay_alpha; if (!(mtex->tex) || !((mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) || @@ -709,8 +712,9 @@ static void paint_draw_tex_overlay(UnifiedPaintSettings *ups, Brush *brush, /* Draw an overlay that shows what effect the brush's texture will * have on brush strength */ -static void paint_draw_cursor_overlay(UnifiedPaintSettings *ups, Brush *brush, - ViewContext *vc, int x, int y, float zoom) +static void paint_draw_cursor_overlay( + UnifiedPaintSettings *ups, Brush *brush, + ViewContext *vc, int x, int y, float zoom) { rctf quad; /* check for overlay mode */ @@ -779,8 +783,9 @@ static void paint_draw_cursor_overlay(UnifiedPaintSettings *ups, Brush *brush, } } -static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush, - ViewContext *vc, int x, int y, float zoom, ePaintMode mode) +static void paint_draw_alpha_overlay( + UnifiedPaintSettings *ups, Brush *brush, + ViewContext *vc, int x, int y, float zoom, ePaintMode mode) { /* color means that primary brush texture is colured and secondary is used for alpha/mask control */ bool col = ELEM(mode, ePaintTextureProjective, ePaintTexture2D, ePaintVertex) ? true : false; @@ -951,8 +956,9 @@ static void paint_draw_curve_cursor(Brush *brush) /* Special actions taken when paint cursor goes over mesh */ /* TODO: sculpt only for now */ -static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc, - const float location[3]) +static void paint_cursor_on_hit( + UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc, + const float location[3]) { float unprojected_radius, projected_radius; @@ -969,8 +975,8 @@ static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewCon } /* convert brush radius from 2D to 3D */ - unprojected_radius = paint_calc_object_space_radius(vc, location, - projected_radius); + unprojected_radius = paint_calc_object_space_radius( + vc, location, projected_radius); /* scale 3D brush radius by pressure */ if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) @@ -1103,7 +1109,7 @@ static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused)) /* Public API */ -void paint_cursor_start(bContext *C, int (*poll)(bContext *C)) +void paint_cursor_start(bContext *C, bool (*poll)(bContext *C)) { Paint *p = BKE_paint_get_active_from_context(C); @@ -1114,7 +1120,7 @@ void paint_cursor_start(bContext *C, int (*poll)(bContext *C)) BKE_paint_invalidate_overlay_all(); } -void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, int (*poll)(bContext *C)) +void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, bool (*poll)(bContext *C)) { if (p && !p->paint_cursor) p->paint_cursor = WM_paint_cursor_activate(wm, poll, paint_draw_cursor, NULL); diff --git a/source/blender/editors/sculpt_paint/paint_curve.c b/source/blender/editors/sculpt_paint/paint_curve.c index 44abdc34ffb9..0e56a1187e35 100644 --- a/source/blender/editors/sculpt_paint/paint_curve.c +++ b/source/blender/editors/sculpt_paint/paint_curve.c @@ -55,7 +55,7 @@ #define PAINT_CURVE_SELECT_THRESHOLD 40.0f #define PAINT_CURVE_POINT_SELECT(pcp, i) (*(&pcp->bez.f1 + i) = SELECT) -int paint_curve_poll(bContext *C) +bool paint_curve_poll(bContext *C) { Object *ob = CTX_data_active_object(C); Paint *p; @@ -603,8 +603,9 @@ static int paintcurve_slide_modal(bContext *C, wmOperator *op, const wmEvent *ev { ARegion *ar = CTX_wm_region(C); wmWindow *window = CTX_wm_window(C); - float diff[2] = {event->mval[0] - psd->initial_loc[0], - event->mval[1] - psd->initial_loc[1]}; + float diff[2] = { + event->mval[0] - psd->initial_loc[0], + event->mval[1] - psd->initial_loc[1]}; if (psd->select == 1) { int i; for (i = 0; i < 3; i++) diff --git a/source/blender/editors/sculpt_paint/paint_hide.c b/source/blender/editors/sculpt_paint/paint_hide.c index 0bec71f05660..01a54e4360df 100644 --- a/source/blender/editors/sculpt_paint/paint_hide.c +++ b/source/blender/editors/sculpt_paint/paint_hide.c @@ -71,10 +71,11 @@ #include /* return true if the element should be hidden/shown */ -static bool is_effected(PartialVisArea area, - float planes[4][4], - const float co[3], - const float mask) +static bool is_effected( + PartialVisArea area, + float planes[4][4], + const float co[3], + const float mask) { if (area == PARTIALVIS_ALL) return 1; @@ -88,12 +89,13 @@ static bool is_effected(PartialVisArea area, } } -static void partialvis_update_mesh(Object *ob, - PBVH *pbvh, - PBVHNode *node, - PartialVisAction action, - PartialVisArea area, - float planes[4][4]) +static void partialvis_update_mesh( + Object *ob, + PBVH *pbvh, + PBVHNode *node, + PartialVisAction action, + PartialVisArea area, + float planes[4][4]) { Mesh *me = ob->data; MVert *mvert; @@ -133,12 +135,13 @@ static void partialvis_update_mesh(Object *ob, /* Hide or show elements in multires grids with a special GridFlags * customdata layer. */ -static void partialvis_update_grids(Object *ob, - PBVH *pbvh, - PBVHNode *node, - PartialVisAction action, - PartialVisArea area, - float planes[4][4]) +static void partialvis_update_grids( + Object *ob, + PBVH *pbvh, + PBVHNode *node, + PartialVisAction action, + PartialVisArea area, + float planes[4][4]) { CCGElem **grids; CCGKey key; @@ -148,9 +151,10 @@ static void partialvis_update_grids(Object *ob, /* get PBVH data */ - BKE_pbvh_node_get_grids(pbvh, node, - &grid_indices, &totgrid, NULL, NULL, - &grids); + BKE_pbvh_node_get_grids( + pbvh, node, + &grid_indices, &totgrid, NULL, NULL, + &grids); grid_hidden = BKE_pbvh_grid_hidden(pbvh); BKE_pbvh_get_grid_key(pbvh, &key); @@ -165,8 +169,9 @@ static void partialvis_update_grids(Object *ob, switch (action) { case PARTIALVIS_HIDE: /* create grid flags data */ - gh = grid_hidden[g] = BLI_BITMAP_NEW(key.grid_area, - "partialvis_update_grids"); + gh = grid_hidden[g] = BLI_BITMAP_NEW( + key.grid_area, + "partialvis_update_grids"); break; case PARTIALVIS_SHOW: /* entire grid is visible, nothing to show */ @@ -192,8 +197,9 @@ static void partialvis_update_grids(Object *ob, /* skip grid element if not in the effected area */ if (is_effected(area, planes, co, mask)) { /* set or clear the hide flag */ - BLI_BITMAP_SET(gh, y * key.grid_size + x, - action == PARTIALVIS_HIDE); + BLI_BITMAP_SET( + gh, y * key.grid_size + x, + action == PARTIALVIS_HIDE); any_changed = true; } @@ -222,21 +228,21 @@ static void partialvis_update_grids(Object *ob, } } -static void partialvis_update_bmesh_verts(BMesh *bm, - GSet *verts, - PartialVisAction action, - PartialVisArea area, - float planes[4][4], - bool *any_changed, - bool *any_visible) +static void partialvis_update_bmesh_verts( + BMesh *bm, + GSet *verts, + PartialVisAction action, + PartialVisArea area, + float planes[4][4], + bool *any_changed, + bool *any_visible) { GSetIterator gs_iter; GSET_ITER (gs_iter, verts) { BMVert *v = BLI_gsetIterator_getKey(&gs_iter); - float *vmask = CustomData_bmesh_get(&bm->vdata, - v->head.data, - CD_PAINT_MASK); + float *vmask = CustomData_bmesh_get( + &bm->vdata, v->head.data, CD_PAINT_MASK); /* hide vertex if in the hide volume */ if (is_effected(area, planes, v->co, *vmask)) { @@ -266,12 +272,13 @@ static void partialvis_update_bmesh_faces(GSet *faces) } } -static void partialvis_update_bmesh(Object *ob, - PBVH *pbvh, - PBVHNode *node, - PartialVisAction action, - PartialVisArea area, - float planes[4][4]) +static void partialvis_update_bmesh( + Object *ob, + PBVH *pbvh, + PBVHNode *node, + PartialVisAction action, + PartialVisArea area, + float planes[4][4]) { BMesh *bm; GSet *unique, *other, *faces; @@ -284,21 +291,23 @@ static void partialvis_update_bmesh(Object *ob, sculpt_undo_push_node(ob, node, SCULPT_UNDO_HIDDEN); - partialvis_update_bmesh_verts(bm, - unique, - action, - area, - planes, - &any_changed, - &any_visible); - - partialvis_update_bmesh_verts(bm, - other, - action, - area, - planes, - &any_changed, - &any_visible); + partialvis_update_bmesh_verts( + bm, + unique, + action, + area, + planes, + &any_changed, + &any_visible); + + partialvis_update_bmesh_verts( + bm, + other, + action, + area, + planes, + &any_changed, + &any_visible); /* finally loop over node faces and tag the ones that are fully hidden */ partialvis_update_bmesh_faces(faces); @@ -317,9 +326,10 @@ static void rect_from_props(rcti *rect, PointerRNA *ptr) rect->ymax = RNA_int_get(ptr, "ymax"); } -static void clip_planes_from_rect(bContext *C, - float clip_planes[4][4], - const rcti *rect) +static void clip_planes_from_rect( + bContext *C, + float clip_planes[4][4], + const rcti *rect) { ViewContext vc; BoundBox bb; @@ -336,11 +346,12 @@ static void clip_planes_from_rect(bContext *C, * inside the clip_planes volume. If mode is outside, get all nodes * that lie at least partially outside the volume. If showing all, get * all nodes. */ -static void get_pbvh_nodes(PBVH *pbvh, - PBVHNode ***nodes, - int *totnode, - float clip_planes[4][4], - PartialVisArea mode) +static void get_pbvh_nodes( + PBVH *pbvh, + PBVHNode ***nodes, + int *totnode, + float clip_planes[4][4], + PartialVisArea mode) { BKE_pbvh_SearchCallback cb = NULL; diff --git a/source/blender/editors/sculpt_paint/paint_image.c b/source/blender/editors/sculpt_paint/paint_image.c index cee7801a9cbb..ab04a9275738 100644 --- a/source/blender/editors/sculpt_paint/paint_image.c +++ b/source/blender/editors/sculpt_paint/paint_image.c @@ -164,8 +164,9 @@ void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short te if (imapaintpartial.x1 != imapaintpartial.x2 && imapaintpartial.y1 != imapaintpartial.y2) { - IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1, - imapaintpartial.x2, imapaintpartial.y2); + IMB_partial_display_buffer_update_delayed( + ibuf, imapaintpartial.x1, imapaintpartial.y1, + imapaintpartial.x2, imapaintpartial.y2); } if (ibuf->mipmap[0]) @@ -264,7 +265,7 @@ static Brush *image_paint_brush(bContext *C) return BKE_paint_brush(&settings->imapaint.paint); } -static int image_paint_poll(bContext *C) +static bool image_paint_poll(bContext *C) { Object *obact; @@ -290,7 +291,7 @@ static int image_paint_poll(bContext *C) return 0; } -static int image_paint_2d_clone_poll(bContext *C) +static bool image_paint_2d_clone_poll(bContext *C) { Brush *brush = image_paint_brush(C); @@ -323,15 +324,16 @@ typedef struct PaintOperation { bool paint_use_opacity_masking(Brush *brush) { - return (brush->flag & BRUSH_AIRBRUSH) || - (brush->flag & BRUSH_DRAG_DOT) || - (brush->flag & BRUSH_ANCHORED) || - (brush->imagepaint_tool == PAINT_TOOL_SMEAR) || - (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) || - (brush->imagepaint_tool == PAINT_TOOL_FILL) || - (brush->flag & BRUSH_USE_GRADIENT) || - (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ? - false : true; + return ((brush->flag & BRUSH_AIRBRUSH) || + (brush->flag & BRUSH_DRAG_DOT) || + (brush->flag & BRUSH_ANCHORED) || + (brush->imagepaint_tool == PAINT_TOOL_SMEAR) || + (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) || + (brush->imagepaint_tool == PAINT_TOOL_FILL) || + (brush->flag & BRUSH_USE_GRADIENT) || + (brush->mtex.tex && + !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ? + false : true); } void paint_brush_color_get( @@ -539,8 +541,9 @@ static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke) paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint); } else { - paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke), - 1.0, 0.0, BKE_brush_size_get(scene, brush)); + paint_proj_stroke( + C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke), + 1.0, 0.0, BKE_brush_size_get(scene, brush)); /* two redraws, one for GPU update, one for notification */ paint_proj_redraw(C, pop->custom_paint, false); paint_proj_redraw(C, pop->custom_paint, true); @@ -554,8 +557,9 @@ static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke) paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint); } else { - paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke), - 1.0, 0.0, BKE_brush_size_get(scene, brush)); + paint_proj_stroke( + C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke), + 1.0, 0.0, BKE_brush_size_get(scene, brush)); /* two redraws, one for GPU update, one for notification */ paint_proj_redraw(C, pop->custom_paint, false); paint_proj_redraw(C, pop->custom_paint, true); @@ -606,10 +610,11 @@ static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event) { int retval; - op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start, - paint_stroke_update_step, - paint_stroke_redraw, - paint_stroke_done, event->type); + op->customdata = paint_stroke_new( + C, op, NULL, paint_stroke_test_start, + paint_stroke_update_step, + paint_stroke_redraw, + paint_stroke_done, event->type); if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) { paint_stroke_data_free(op); @@ -637,10 +642,11 @@ static int paint_exec(bContext *C, wmOperator *op) RNA_float_get_array(&firstpoint, "mouse", mouse); - op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start, - paint_stroke_update_step, - paint_stroke_redraw, - paint_stroke_done, 0); + op->customdata = paint_stroke_new( + C, op, NULL, paint_stroke_test_start, + paint_stroke_update_step, + paint_stroke_redraw, + paint_stroke_done, 0); /* frees op->customdata */ return paint_stroke_exec(C, op); } @@ -845,11 +851,12 @@ static void sample_color_update_header(SampleColorData *data, bContext *C) ScrArea *sa = CTX_wm_area(C); if (sa) { - BLI_snprintf(msg, sizeof(msg), - IFACE_("Sample color for %s"), - !data->sample_palette ? - IFACE_("Brush. Use Left Click to sample for palette instead") : - IFACE_("Palette. Use Left Click to sample more colors")); + BLI_snprintf( + msg, sizeof(msg), + IFACE_("Sample color for %s"), + !data->sample_palette ? + IFACE_("Brush. Use Left Click to sample for palette instead") : + IFACE_("Palette. Use Left Click to sample more colors")); ED_area_headerprint(sa, msg); } } @@ -976,7 +983,7 @@ static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event) return OPERATOR_RUNNING_MODAL; } -static int sample_color_poll(bContext *C) +static bool sample_color_poll(bContext *C) { return (image_paint_poll(C) || vertex_paint_poll(C)); } @@ -1009,7 +1016,7 @@ void PAINT_OT_sample_color(wmOperatorType *ot) /******************** texture paint toggle operator ********************/ -static int texture_paint_toggle_poll(bContext *C) +static bool texture_paint_toggle_poll(bContext *C) { Object *ob = CTX_data_active_object(C); if (ob == NULL || ob->type != OB_MESH) @@ -1024,6 +1031,7 @@ static int texture_paint_toggle_poll(bContext *C) static int texture_paint_toggle_exec(bContext *C, wmOperator *op) { + Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); Object *ob = CTX_data_active_object(C); const int mode_flag = OB_MODE_TEXTURE_PAINT; @@ -1039,14 +1047,13 @@ static int texture_paint_toggle_exec(bContext *C, wmOperator *op) ob->mode &= ~mode_flag; if (U.glreslimit != 0) - GPU_free_images(); - GPU_paint_set_mipmap(1); + GPU_free_images(bmain); + GPU_paint_set_mipmap(bmain, 1); toggle_paint_cursor(C, 0); } else { bScreen *sc; - Main *bmain = CTX_data_main(C); Image *ima = NULL; ImagePaintSettings *imapaint = &scene->toolsettings->imapaint; @@ -1089,8 +1096,8 @@ static int texture_paint_toggle_exec(bContext *C, wmOperator *op) BKE_paint_init(bmain, scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT); if (U.glreslimit != 0) - GPU_free_images(); - GPU_paint_set_mipmap(0); + GPU_free_images(bmain); + GPU_paint_set_mipmap(bmain, 0); toggle_paint_cursor(C, 1); } @@ -1145,7 +1152,7 @@ static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int brush_colors_flip_poll(bContext *C) +static bool brush_colors_flip_poll(bContext *C) { if (image_paint_poll(C)) { Brush *br = image_paint_brush(C); @@ -1195,7 +1202,7 @@ void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op) } -static int texture_paint_poll(bContext *C) +static bool texture_paint_poll(bContext *C) { if (texture_paint_toggle_poll(C)) if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT) @@ -1204,23 +1211,22 @@ static int texture_paint_poll(bContext *C) return 0; } -int image_texture_paint_poll(bContext *C) +bool image_texture_paint_poll(bContext *C) { return (texture_paint_poll(C) || image_paint_poll(C)); } -int facemask_paint_poll(bContext *C) +bool facemask_paint_poll(bContext *C) { return BKE_paint_select_face_test(CTX_data_active_object(C)); } -int vert_paint_poll(bContext *C) +bool vert_paint_poll(bContext *C) { return BKE_paint_select_vert_test(CTX_data_active_object(C)); } -int mask_paint_poll(bContext *C) +bool mask_paint_poll(bContext *C) { return BKE_paint_select_elem_test(CTX_data_active_object(C)); } - diff --git a/source/blender/editors/sculpt_paint/paint_image_2d.c b/source/blender/editors/sculpt_paint/paint_image_2d.c index ec1a6ebf7ed3..76190b13b61b 100644 --- a/source/blender/editors/sculpt_paint/paint_image_2d.c +++ b/source/blender/editors/sculpt_paint/paint_image_2d.c @@ -441,8 +441,9 @@ static ImBuf *brush_painter_imbuf_new(BrushPainter *painter, int size, float pre } /* update rectangular section of the brush image */ -static void brush_painter_imbuf_update(BrushPainter *painter, ImBuf *oldtexibuf, - int origx, int origy, int w, int h, int xt, int yt) +static void brush_painter_imbuf_update( + BrushPainter *painter, ImBuf *oldtexibuf, + int origx, int origy, int w, int h, int xt, int yt) { Scene *scene = painter->scene; Brush *brush = painter->brush; @@ -659,11 +660,12 @@ static void brush_painter_2d_refresh_cache(ImagePaintState *s, BrushPainter *pai bool do_random = false; bool do_partial_update = false; - bool update_color = (brush->flag & BRUSH_USE_GRADIENT) && - ((ELEM(brush->gradient_stroke_mode, - BRUSH_GRADIENT_SPACING_REPEAT, - BRUSH_GRADIENT_SPACING_CLAMP)) || - (cache->last_pressure != pressure)); + bool update_color = ( + (brush->flag & BRUSH_USE_GRADIENT) && + ((ELEM(brush->gradient_stroke_mode, + BRUSH_GRADIENT_SPACING_REPEAT, + BRUSH_GRADIENT_SPACING_CLAMP)) || + (cache->last_pressure != pressure))); float tex_rotation = -brush->mtex.rot; float mask_rotation = -brush->mask_mtex.rot; @@ -679,8 +681,9 @@ static void brush_painter_2d_refresh_cache(ImagePaintState *s, BrushPainter *pai else if (!((brush->flag & BRUSH_ANCHORED) || update_color)) do_partial_update = true; - brush_painter_2d_tex_mapping(s, diameter, painter->startpaintpos, pos, mouse, - brush->mtex.brush_map_mode, &painter->tex_mapping); + brush_painter_2d_tex_mapping( + s, diameter, painter->startpaintpos, pos, mouse, + brush->mtex.brush_map_mode, &painter->tex_mapping); } if (painter->cache.is_maskbrush) { @@ -712,8 +715,9 @@ static void brush_painter_2d_refresh_cache(ImagePaintState *s, BrushPainter *pai cache->tex_mask = NULL; } - brush_painter_2d_tex_mapping(s, diameter, painter->startpaintpos, pos, mouse, - brush->mask_mtex.brush_map_mode, &painter->mask_mapping); + brush_painter_2d_tex_mapping( + s, diameter, painter->startpaintpos, pos, mouse, + brush->mask_mtex.brush_map_mode, &painter->mask_mapping); if (do_partial_update_mask) brush_painter_mask_imbuf_partial_update(painter, pos, diameter); @@ -893,9 +897,10 @@ static void paint_2d_lift_soften(ImagePaintState *s, ImBuf *ibuf, ImBuf *ibufb, for (yk = 0; yk < kernel->side; yk++) { for (xk = 0; xk < kernel->side; xk++) { - count += paint_2d_ibuf_add_if(ibuf, xi + xk - kernel->pixel_len, - yi + yk - kernel->pixel_len, outrgb, tile, - kernel->wdata[xk + yk * kernel->side]); + count += paint_2d_ibuf_add_if( + ibuf, xi + xk - kernel->pixel_len, + yi + yk - kernel->pixel_len, outrgb, tile, + kernel->wdata[xk + yk * kernel->side]); } } @@ -994,10 +999,11 @@ static void paint_2d_lift_smear(ImBuf *ibuf, ImBuf *ibufb, int *pos, short tile) tot = paint_2d_torus_split_region(region, ibufb, ibuf, tile); for (a = 0; a < tot; a++) - IMB_rectblend(ibufb, ibufb, ibuf, NULL, NULL, NULL, 0, region[a].destx, region[a].desty, - region[a].destx, region[a].desty, - region[a].srcx, region[a].srcy, - region[a].width, region[a].height, IMB_BLEND_COPY, false); + IMB_rectblend( + ibufb, ibufb, ibuf, NULL, NULL, NULL, 0, region[a].destx, region[a].desty, + region[a].destx, region[a].desty, + region[a].srcx, region[a].srcy, + region[a].width, region[a].height, IMB_BLEND_COPY, false); } static ImBuf *paint_2d_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos) @@ -1008,10 +1014,12 @@ static ImBuf *paint_2d_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos) ImBuf *clonebuf = IMB_allocImBuf(w, h, ibufb->planes, ibufb->flags); IMB_rectclip(clonebuf, ibuf, &destx, &desty, &srcx, &srcy, &w, &h); - IMB_rectblend(clonebuf, clonebuf, ibufb, NULL, NULL, NULL, 0, destx, desty, destx, desty, destx, desty, w, h, - IMB_BLEND_COPY_ALPHA, false); - IMB_rectblend(clonebuf, clonebuf, ibuf, NULL, NULL, NULL, 0, destx, desty, destx, desty, srcx, srcy, w, h, - IMB_BLEND_COPY_RGB, false); + IMB_rectblend( + clonebuf, clonebuf, ibufb, NULL, NULL, NULL, 0, destx, desty, destx, desty, destx, desty, w, h, + IMB_BLEND_COPY_ALPHA, false); + IMB_rectblend( + clonebuf, clonebuf, ibuf, NULL, NULL, NULL, 0, destx, desty, destx, desty, srcx, srcy, w, h, + IMB_BLEND_COPY_RGB, false); return clonebuf; } @@ -1022,15 +1030,16 @@ static void paint_2d_convert_brushco(ImBuf *ibufb, const float pos[2], int ipos[ ipos[1] = (int)floorf((pos[1] - ibufb->y / 2)); } -static void paint_2d_do_making_brush(ImagePaintState *s, - ImagePaintRegion *region, - unsigned short *curveb, - unsigned short *texmaskb, - ImBuf *frombuf, - float mask_max, - short blend, - int tilex, int tiley, - int tilew, int tileh) +static void paint_2d_do_making_brush( + ImagePaintState *s, + ImagePaintRegion *region, + unsigned short *curveb, + unsigned short *texmaskb, + ImBuf *frombuf, + float mask_max, + short blend, + int tilex, int tiley, + int tilew, int tileh) { ImBuf tmpbuf; IMB_initImBuf(&tmpbuf, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, 0); @@ -1049,13 +1058,14 @@ static void paint_2d_do_making_brush(ImagePaintState *s, else tmpbuf.rect = image_undo_find_tile(undo_tiles, s->image, s->canvas, tx, ty, &mask, false); - IMB_rectblend(s->canvas, &tmpbuf, frombuf, mask, - curveb, texmaskb, mask_max, - region->destx, region->desty, - origx, origy, - region->srcx, region->srcy, - region->width, region->height, - blend, ((s->brush->flag & BRUSH_ACCUMULATE) != 0)); + IMB_rectblend( + s->canvas, &tmpbuf, frombuf, mask, + curveb, texmaskb, mask_max, + region->destx, region->desty, + origx, origy, + region->srcx, region->srcy, + region->width, region->height, + blend, ((s->brush->flag & BRUSH_ACCUMULATE) != 0)); } } } @@ -1078,11 +1088,12 @@ static void paint_2d_op_foreach_do( const ParallelRangeTLS *__restrict UNUSED(tls)) { Paint2DForeachData *data = (Paint2DForeachData *)data_v; - paint_2d_do_making_brush(data->s, data->region, data->curveb, - data->texmaskb, data->frombuf, data->mask_max, - data->blend, - data->tilex, iter, - data->tilew, iter); + paint_2d_do_making_brush( + data->s, data->region, data->curveb, + data->texmaskb, data->frombuf, data->mask_max, + data->blend, + data->tilex, iter, + data->tilew, iter); } static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsigned short *texmaskb, const float lastpos[2], const float pos[2]) @@ -1134,21 +1145,24 @@ static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsign /* blend into canvas */ for (a = 0; a < tot; a++) { - ED_imapaint_dirty_region(s->image, s->canvas, - region[a].destx, region[a].desty, - region[a].width, region[a].height, true); + ED_imapaint_dirty_region( + s->image, s->canvas, + region[a].destx, region[a].desty, + region[a].width, region[a].height, true); if (s->do_masking) { /* masking, find original pixels tiles from undo buffer to composite over */ int tilex, tiley, tilew, tileh; - imapaint_region_tiles(s->canvas, region[a].destx, region[a].desty, - region[a].width, region[a].height, - &tilex, &tiley, &tilew, &tileh); + imapaint_region_tiles( + s->canvas, region[a].destx, region[a].desty, + region[a].width, region[a].height, + &tilex, &tiley, &tilew, &tileh); if (tiley == tileh) { - paint_2d_do_making_brush(s, ®ion[a], curveb, texmaskb, frombuf, - mask_max, blend, tilex, tiley, tilew, tileh); + paint_2d_do_making_brush( + s, ®ion[a], curveb, texmaskb, frombuf, + mask_max, blend, tilex, tiley, tilew, tileh); } else { Paint2DForeachData data; @@ -1164,19 +1178,21 @@ static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsign ParallelRangeSettings settings; BLI_parallel_range_settings_defaults(&settings); - BLI_task_parallel_range(tiley, tileh + 1, &data, - paint_2d_op_foreach_do, - &settings); + BLI_task_parallel_range( + tiley, tileh + 1, &data, + paint_2d_op_foreach_do, + &settings); } } else { /* no masking, composite brush directly onto canvas */ - IMB_rectblend_threaded(s->canvas, s->canvas, frombuf, NULL, curveb, texmaskb, mask_max, - region[a].destx, region[a].desty, - region[a].destx, region[a].desty, - region[a].srcx, region[a].srcy, - region[a].width, region[a].height, blend, false); + IMB_rectblend_threaded( + s->canvas, s->canvas, frombuf, NULL, curveb, texmaskb, mask_max, + region[a].destx, region[a].desty, + region[a].destx, region[a].desty, + region[a].srcx, region[a].srcy, + region[a].width, region[a].height, blend, false); } } @@ -1477,16 +1493,18 @@ void paint_2d_bucket_fill( if (do_float) { for (x_px = 0; x_px < ibuf->x; x_px++) { for (y_px = 0; y_px < ibuf->y; y_px++) { - blend_color_mix_float(ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), - ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), color_f); + blend_color_mix_float( + ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), + ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), color_f); } } } else { for (x_px = 0; x_px < ibuf->x; x_px++) { for (y_px = 0; y_px < ibuf->y; y_px++) { - blend_color_mix_byte((unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), - (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), (unsigned char *)&color_b); + blend_color_mix_byte( + (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), + (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), (unsigned char *)&color_b); } } } @@ -1537,9 +1555,10 @@ void paint_2d_bucket_fill( while (!BLI_stack_is_empty(stack)) { BLI_stack_pop(stack, &coordinate); - IMB_blend_color_float(ibuf->rect_float + 4 * (coordinate), - ibuf->rect_float + 4 * (coordinate), - color_f, br->blend); + IMB_blend_color_float( + ibuf->rect_float + 4 * (coordinate), + ibuf->rect_float + 4 * (coordinate), + color_f, br->blend); /* reconstruct the coordinates here */ x_px = coordinate % width; @@ -1568,9 +1587,10 @@ void paint_2d_bucket_fill( while (!BLI_stack_is_empty(stack)) { BLI_stack_pop(stack, &coordinate); - IMB_blend_color_byte((unsigned char *)(ibuf->rect + coordinate), - (unsigned char *)(ibuf->rect + coordinate), - (unsigned char *)&color_b, br->blend); + IMB_blend_color_byte( + (unsigned char *)(ibuf->rect + coordinate), + (unsigned char *)(ibuf->rect + coordinate), + (unsigned char *)&color_b, br->blend); /* reconstruct the coordinates here */ x_px = coordinate % width; @@ -1678,9 +1698,10 @@ void paint_2d_gradient_fill( /* convert to premultiplied */ mul_v3_fl(color_f, color_f[3]); color_f[3] *= br->alpha; - IMB_blend_color_float(ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), - ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), - color_f, br->blend); + IMB_blend_color_float( + ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), + ibuf->rect_float + 4 * (((size_t)y_px) * ibuf->x + x_px), + color_f, br->blend); } } } @@ -1708,9 +1729,10 @@ void paint_2d_gradient_fill( linearrgb_to_srgb_v3_v3(color_f, color_f); rgba_float_to_uchar((unsigned char *)&color_b, color_f); ((unsigned char *)&color_b)[3] *= br->alpha; - IMB_blend_color_byte((unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), - (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), - (unsigned char *)&color_b, br->blend); + IMB_blend_color_byte( + (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), + (unsigned char *)(ibuf->rect + ((size_t)y_px) * ibuf->x + x_px), + (unsigned char *)&color_b, br->blend); } } } diff --git a/source/blender/editors/sculpt_paint/paint_image_proj.c b/source/blender/editors/sculpt_paint/paint_image_proj.c index 9843629b7067..6b13decd41ba 100644 --- a/source/blender/editors/sculpt_paint/paint_image_proj.c +++ b/source/blender/editors/sculpt_paint/paint_image_proj.c @@ -2611,8 +2611,9 @@ static void project_paint_face_init( } #if 0 - project_paint_undo_tiles_init(&bounds_px, ps->projImages + image_index, tmpibuf, - tile_width, threaded, ps->do_masking); + project_paint_undo_tiles_init( + &bounds_px, ps->projImages + image_index, tmpibuf, + tile_width, threaded, ps->do_masking); #endif /* clip face and */ @@ -2661,10 +2662,10 @@ static void project_paint_face_init( if (mask > 0.0f) { BLI_linklist_prepend_arena( bucketPixelNodes, - project_paint_uvpixel_init(ps, arena, &tinf, x, y, mask, tri_index, - pixelScreenCo, wco, w), - arena - ); + project_paint_uvpixel_init( + ps, arena, &tinf, x, y, mask, tri_index, + pixelScreenCo, wco, w), + arena); } } @@ -3428,21 +3429,14 @@ static bool proj_paint_state_dm_init(ProjPaintState *ps) /* Workaround for subsurf selection, try the display mesh first */ if (ps->source == PROJ_SRC_IMAGE_CAM) { /* using render mesh, assume only camera was rendered from */ - ps->dm = mesh_create_derived_render(ps->scene, ps->ob, ps->scene->customdata_mask | CD_MASK_MTFACE); + ps->dm = mesh_create_derived_render(ps->scene, ps->ob, ps->scene->customdata_mask | CD_MASK_MLOOPUV | CD_MASK_MTFACE); ps->dm_release = true; } - else if (ps->ob->derivedFinal && - CustomData_has_layer(&ps->ob->derivedFinal->loopData, CD_MLOOPUV) && - (ps->do_face_sel == false || CustomData_has_layer(&ps->ob->derivedFinal->polyData, CD_ORIGINDEX))) - { - ps->dm = ps->ob->derivedFinal; - ps->dm_release = false; - } else { ps->dm = mesh_get_derived_final( ps->scene, ps->ob, - ps->scene->customdata_mask | CD_MASK_MTFACE | (ps->do_face_sel ? CD_ORIGINDEX : 0)); - ps->dm_release = true; + ps->scene->customdata_mask | CD_MASK_MLOOPUV | CD_MASK_MTFACE | (ps->do_face_sel ? CD_MASK_ORIGINDEX : 0)); + ps->dm_release = false; } if (!CustomData_has_layer(&ps->dm->loopData, CD_MLOOPUV)) { @@ -4225,8 +4219,9 @@ static void do_projectpaint_clone_f(ProjPaintState *ps, ProjPixel *projPixel, fl * accumulation of color greater than 'projPixel->mask' however in the case of smear its not * really that important to be correct as it is with clone and painting */ -static void do_projectpaint_smear(ProjPaintState *ps, ProjPixel *projPixel, float mask, - MemArena *smearArena, LinkNode **smearPixels, const float co[2]) +static void do_projectpaint_smear( + ProjPaintState *ps, ProjPixel *projPixel, float mask, + MemArena *smearArena, LinkNode **smearPixels, const float co[2]) { unsigned char rgba_ub[4]; @@ -4237,8 +4232,9 @@ static void do_projectpaint_smear(ProjPaintState *ps, ProjPixel *projPixel, floa BLI_linklist_prepend_arena(smearPixels, (void *)projPixel, smearArena); } -static void do_projectpaint_smear_f(ProjPaintState *ps, ProjPixel *projPixel, float mask, - MemArena *smearArena, LinkNode **smearPixels_f, const float co[2]) +static void do_projectpaint_smear_f( + ProjPaintState *ps, ProjPixel *projPixel, float mask, + MemArena *smearArena, LinkNode **smearPixels_f, const float co[2]) { float rgba[4]; @@ -4249,8 +4245,9 @@ static void do_projectpaint_smear_f(ProjPaintState *ps, ProjPixel *projPixel, fl BLI_linklist_prepend_arena(smearPixels_f, (void *)projPixel, smearArena); } -static void do_projectpaint_soften_f(ProjPaintState *ps, ProjPixel *projPixel, float mask, - MemArena *softenArena, LinkNode **softenPixels) +static void do_projectpaint_soften_f( + ProjPaintState *ps, ProjPixel *projPixel, float mask, + MemArena *softenArena, LinkNode **softenPixels) { float accum_tot = 0.0f; int xk, yk; @@ -4305,8 +4302,9 @@ static void do_projectpaint_soften_f(ProjPaintState *ps, ProjPixel *projPixel, f } } -static void do_projectpaint_soften(ProjPaintState *ps, ProjPixel *projPixel, float mask, - MemArena *softenArena, LinkNode **softenPixels) +static void do_projectpaint_soften( + ProjPaintState *ps, ProjPixel *projPixel, float mask, + MemArena *softenArena, LinkNode **softenPixels) { float accum_tot = 0; int xk, yk; @@ -4587,8 +4585,9 @@ static void *do_projectpaint_thread(void *ph_v) if (is_floatbuf) { /* convert to premultipied */ mul_v3_fl(color_f, color_f[3]); - IMB_blend_color_float(projPixel->pixel.f_pt, projPixel->origColor.f_pt, - color_f, ps->blend); + IMB_blend_color_float( + projPixel->pixel.f_pt, projPixel->origColor.f_pt, + color_f, ps->blend); } else { linearrgb_to_srgb_v3_v3(color_f, color_f); @@ -4600,8 +4599,9 @@ static void *do_projectpaint_thread(void *ph_v) unit_float_to_uchar_clamp_v3(projPixel->newColor.ch, color_f); } projPixel->newColor.ch[3] = unit_float_to_uchar_clamp(color_f[3]); - IMB_blend_color_byte(projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, - projPixel->newColor.ch, ps->blend); + IMB_blend_color_byte( + projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, + projPixel->newColor.ch, ps->blend); } } else { @@ -4610,16 +4610,18 @@ static void *do_projectpaint_thread(void *ph_v) newColor_f[3] = ((float)projPixel->mask) * (1.0f / 65535.0f) * brush->alpha; copy_v3_v3(newColor_f, ps->paint_color_linear); - IMB_blend_color_float(projPixel->pixel.f_pt, projPixel->origColor.f_pt, - newColor_f, ps->blend); + IMB_blend_color_float( + projPixel->pixel.f_pt, projPixel->origColor.f_pt, + newColor_f, ps->blend); } else { float mask = ((float)projPixel->mask) * (1.0f / 65535.0f); projPixel->newColor.ch[3] = mask * 255 * brush->alpha; rgb_float_to_uchar(projPixel->newColor.ch, ps->paint_color); - IMB_blend_color_byte(projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, - projPixel->newColor.ch, ps->blend); + IMB_blend_color_byte( + projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, + projPixel->newColor.ch, ps->blend); } } @@ -4647,15 +4649,17 @@ static void *do_projectpaint_thread(void *ph_v) ps->reproject_ibuf_free_float = true; } - bicubic_interpolation_color(ps->reproject_ibuf, NULL, projPixel->newColor.f, - projPixel->projCoSS[0], projPixel->projCoSS[1]); + bicubic_interpolation_color( + ps->reproject_ibuf, NULL, projPixel->newColor.f, + projPixel->projCoSS[0], projPixel->projCoSS[1]); if (projPixel->newColor.f[3]) { float mask = ((float)projPixel->mask) * (1.0f / 65535.0f); mul_v4_v4fl(projPixel->newColor.f, projPixel->newColor.f, mask); - blend_color_mix_float(projPixel->pixel.f_pt, projPixel->origColor.f_pt, - projPixel->newColor.f); + blend_color_mix_float( + projPixel->pixel.f_pt, projPixel->origColor.f_pt, + projPixel->newColor.f); } } else { @@ -4664,14 +4668,16 @@ static void *do_projectpaint_thread(void *ph_v) ps->reproject_ibuf_free_uchar = true; } - bicubic_interpolation_color(ps->reproject_ibuf, projPixel->newColor.ch, NULL, - projPixel->projCoSS[0], projPixel->projCoSS[1]); + bicubic_interpolation_color( + ps->reproject_ibuf, projPixel->newColor.ch, NULL, + projPixel->projCoSS[0], projPixel->projCoSS[1]); if (projPixel->newColor.ch[3]) { float mask = ((float)projPixel->mask) * (1.0f / 65535.0f); projPixel->newColor.ch[3] *= mask; - blend_color_mix_byte(projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, - projPixel->newColor.ch); + blend_color_mix_byte( + projPixel->pixel.ch_pt, projPixel->origColor.ch_pt, + projPixel->newColor.ch); } } } @@ -5531,12 +5537,13 @@ void PAINT_OT_image_from_view(wmOperatorType *ot) void BKE_paint_data_warning(struct ReportList *reports, bool uvs, bool mat, bool tex, bool stencil) { - BKE_reportf(reports, RPT_WARNING, "Missing%s%s%s%s detected!", - !uvs ? " UVs," : "", - !mat ? " Materials," : "", - !tex ? " Textures," : "", - !stencil ? " Stencil," : "" - ); + BKE_reportf( + reports, RPT_WARNING, "Missing%s%s%s%s detected!", + !uvs ? " UVs," : "", + !mat ? " Materials," : "", + !tex ? " Textures," : "", + !stencil ? " Stencil," : "" + ); } /* Make sure that active object has a material, and assign UVs and image layers if they do not exist */ @@ -5673,8 +5680,9 @@ static Image *proj_paint_image_create(wmOperator *op, Main *bmain) alpha = RNA_boolean_get(op->ptr, "alpha"); RNA_string_get(op->ptr, "name", imagename); } - ima = BKE_image_add_generated(bmain, width, height, imagename, alpha ? 32 : 24, use_float, - gen_type, color, false); + ima = BKE_image_add_generated( + bmain, width, height, imagename, alpha ? 32 : 24, use_float, + gen_type, color, false); return ima; } @@ -5928,7 +5936,7 @@ static int add_simple_uvs_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int add_simple_uvs_poll(bContext *C) +static bool add_simple_uvs_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -5952,4 +5960,3 @@ void PAINT_OT_add_simple_uvs(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/sculpt_paint/paint_image_undo.c b/source/blender/editors/sculpt_paint/paint_image_undo.c index ef28dafa8c90..7ec7dd20dc58 100644 --- a/source/blender/editors/sculpt_paint/paint_image_undo.c +++ b/source/blender/editors/sculpt_paint/paint_image_undo.c @@ -103,8 +103,9 @@ static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, Cop { if (mode == COPY) { /* copy or swap contents of tile->rect and region in ibuf->rect */ - IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE, - tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); + IMB_rectcpy( + tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE, + tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); if (ibuf->rect_float) { SWAP(float *, tmpibuf->rect_float, tile->rect.fp); @@ -115,8 +116,9 @@ static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, Cop } else { if (mode == RESTORE_COPY) { - IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE, - tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); + IMB_rectcpy( + tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE, + tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); } /* swap to the tmpbuf for easy copying */ if (ibuf->rect_float) { @@ -126,8 +128,9 @@ static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, Cop SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint); } - IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE, - tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); + IMB_rectcpy( + ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE, + tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); if (mode == RESTORE) { if (ibuf->rect_float) { @@ -154,8 +157,9 @@ void *image_undo_find_tile( if (mask) { /* allocate mask if requested */ if (!tile->mask) { - tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE, - "UndoImageTile.mask"); + tile->mask = MEM_callocN( + sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE, + "UndoImageTile.mask"); } *mask = tile->mask; @@ -202,8 +206,9 @@ void *image_undo_push_tile( /* add mask explicitly here */ if (mask) { - *mask = tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE, - "UndoImageTile.mask"); + *mask = tile->mask = MEM_callocN( + sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE, + "UndoImageTile.mask"); } allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4; allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char); @@ -251,8 +256,9 @@ static void image_undo_restore_runtime(ListBase *lb) ImBuf *ibuf, *tmpibuf; UndoImageTile *tile; - tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, - IB_rectfloat | IB_rect); + tmpibuf = IMB_allocImBuf( + IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, + IB_rectfloat | IB_rect); for (tile = lb->first; tile; tile = tile->next) { Image *ima = tile->ima; diff --git a/source/blender/editors/sculpt_paint/paint_intern.h b/source/blender/editors/sculpt_paint/paint_intern.h index e1ac35c3675e..b782a47192a7 100644 --- a/source/blender/editors/sculpt_paint/paint_intern.h +++ b/source/blender/editors/sculpt_paint/paint_intern.h @@ -87,16 +87,16 @@ struct ViewContext *paint_stroke_view_context(struct PaintStroke *stroke); void *paint_stroke_mode_data(struct PaintStroke *stroke); float paint_stroke_distance_get(struct PaintStroke *stroke); void paint_stroke_set_mode_data(struct PaintStroke *stroke, void *mode_data); -int paint_poll(struct bContext *C); -void paint_cursor_start(struct bContext *C, int (*poll)(struct bContext *C)); -void paint_cursor_start_explicit(struct Paint *p, struct wmWindowManager *wm, int (*poll)(struct bContext *C)); +bool paint_poll(struct bContext *C); +void paint_cursor_start(struct bContext *C, bool (*poll)(struct bContext *C)); +void paint_cursor_start_explicit(struct Paint *p, struct wmWindowManager *wm, bool (*poll)(struct bContext *C)); void paint_cursor_delete_textures(void); /* paint_vertex.c */ -int weight_paint_poll(struct bContext *C); -int weight_paint_mode_poll(struct bContext *C); -int vertex_paint_poll(struct bContext *C); -int vertex_paint_mode_poll(struct bContext *C); +bool weight_paint_poll(struct bContext *C); +bool weight_paint_mode_poll(struct bContext *C); +bool vertex_paint_poll(struct bContext *C); +bool vertex_paint_mode_poll(struct bContext *C); typedef void (*VPaintTransform_Callback)(const float col[3], const void *user_data, float r_col[3]); @@ -177,7 +177,7 @@ typedef struct ImagePaintPartialRedraw { #define IMAPAINT_TILE_SIZE (1 << IMAPAINT_TILE_BITS) #define IMAPAINT_TILE_NUMBER(size) (((size) + IMAPAINT_TILE_SIZE - 1) >> IMAPAINT_TILE_BITS) -int image_texture_paint_poll(struct bContext *C); +bool image_texture_paint_poll(struct bContext *C); void imapaint_image_update(struct SpaceImage *sima, struct Image *image, struct ImBuf *ibuf, short texpaint); struct ImagePaintPartialRedraw *get_imapaintpartial(void); void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr); @@ -237,8 +237,8 @@ struct ListBase *ED_image_undosys_step_get_tiles(struct UndoStep *us_p); struct ListBase *ED_image_undo_get_tiles(void); /* sculpt_uv.c */ -int uv_sculpt_poll(struct bContext *C); -int uv_sculpt_keymap_poll(struct bContext *C); +bool uv_sculpt_poll(struct bContext *C); +bool uv_sculpt_keymap_poll(struct bContext *C); void SCULPT_OT_uv_sculpt_stroke(struct wmOperatorType *ot); @@ -265,7 +265,9 @@ void paint_calc_redraw_planes(float planes[4][4], float paint_calc_object_space_radius(struct ViewContext *vc, const float center[3], float pixel_radius); float paint_get_tex_pixel(const struct MTex *mtex, float u, float v, struct ImagePool *pool, int thread); -void paint_get_tex_pixel_col(const struct MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert, struct ColorSpace *colorspace); +void paint_get_tex_pixel_col( + const struct MTex *mtex, float u, float v, float rgba[4], + struct ImagePool *pool, int thread, bool convert, struct ColorSpace *colorspace); void paint_sample_color(struct bContext *C, struct ARegion *ar, int x, int y, bool texpaint_proj, bool palette); @@ -282,11 +284,11 @@ void PAINT_OT_face_select_reveal(struct wmOperatorType *ot); void PAINT_OT_vert_select_all(struct wmOperatorType *ot); void PAINT_OT_vert_select_ungrouped(struct wmOperatorType *ot); -int vert_paint_poll(struct bContext *C); -int mask_paint_poll(struct bContext *C); -int paint_curve_poll(struct bContext *C); +bool vert_paint_poll(struct bContext *C); +bool mask_paint_poll(struct bContext *C); +bool paint_curve_poll(struct bContext *C); -int facemask_paint_poll(struct bContext *C); +bool facemask_paint_poll(struct bContext *C); void flip_v3_v3(float out[3], const float in[3], const char symm); void flip_qt_qt(float out[3], const float in[3], const char symm); diff --git a/source/blender/editors/sculpt_paint/paint_mask.c b/source/blender/editors/sculpt_paint/paint_mask.c index 76b629395e25..e0fdcc0c7c8f 100644 --- a/source/blender/editors/sculpt_paint/paint_mask.c +++ b/source/blender/editors/sculpt_paint/paint_mask.c @@ -76,9 +76,10 @@ static const EnumPropertyItem mode_items[] = { {0}}; -static void mask_flood_fill_set_elem(float *elem, - PaintMaskFloodMode mode, - float value) +static void mask_flood_fill_set_elem( + float *elem, + PaintMaskFloodMode mode, + float value) { switch (mode) { case PAINT_MASK_FLOOD_VALUE: @@ -162,8 +163,9 @@ static int mask_flood_fill_exec(bContext *C, wmOperator *op) BLI_parallel_range_settings_defaults(&settings); settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT); BLI_task_parallel_range( - 0, totnode, &data, mask_flood_fill_task_cb, - &settings); + + 0, totnode, &data, mask_flood_fill_task_cb, + &settings); if (multires) multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED); diff --git a/source/blender/editors/sculpt_paint/paint_ops.c b/source/blender/editors/sculpt_paint/paint_ops.c index f03c119a09ea..74984d090f8d 100644 --- a/source/blender/editors/sculpt_paint/paint_ops.c +++ b/source/blender/editors/sculpt_paint/paint_ops.c @@ -183,7 +183,7 @@ static void PALETTE_OT_new(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } -static int palette_poll(bContext *C) +static bool palette_poll(bContext *C) { Paint *paint = BKE_paint_get_active_from_context(C); @@ -365,10 +365,11 @@ static Brush *brush_tool_toggle(Main *bmain, Brush *brush_orig, const int tool, return NULL; } -static int brush_generic_tool_set(Main *bmain, Paint *paint, const int tool, - const size_t tool_offset, const int ob_mode, - const char *tool_name, const bool create_missing, - const bool toggle) +static int brush_generic_tool_set( + Main *bmain, Paint *paint, const int tool, + const size_t tool_offset, const int ob_mode, + const char *tool_name, const bool create_missing, + const bool toggle) { Brush *brush, *brush_orig = BKE_paint_brush(paint); @@ -452,9 +453,10 @@ static int brush_select_exec(bContext *C, wmOperator *op) return OPERATOR_CANCELLED; } - return brush_generic_tool_set(bmain, paint, tool, tool_offset, - paint_mode, tool_name, create_missing, - toggle); + return brush_generic_tool_set( + bmain, paint, tool, tool_offset, + paint_mode, tool_name, create_missing, + toggle); } static void PAINT_OT_brush_select(wmOperatorType *ot) @@ -493,13 +495,15 @@ static void PAINT_OT_brush_select(wmOperatorType *ot) RNA_def_property_flag(prop, PROP_SKIP_SAVE); } -static wmKeyMapItem *keymap_brush_select(wmKeyMap *keymap, int paint_mode, - int tool, int keymap_type, - int keymap_modifier) +static wmKeyMapItem *keymap_brush_select( + wmKeyMap *keymap, int paint_mode, + int tool, int keymap_type, + int keymap_modifier) { wmKeyMapItem *kmi; - kmi = WM_keymap_add_item(keymap, "PAINT_OT_brush_select", - keymap_type, KM_PRESS, keymap_modifier, 0); + kmi = WM_keymap_add_item( + keymap, "PAINT_OT_brush_select", + keymap_type, KM_PRESS, keymap_modifier, 0); RNA_enum_set(kmi->ptr, "paint_mode", paint_mode); @@ -683,8 +687,7 @@ static void stencil_control_calculate(StencilControlData *scd, const int mval[2] switch (scd->mode) { case STENCIL_TRANSLATE: sub_v2_v2v2(mdiff, mvalf, scd->init_mouse); - add_v2_v2v2(scd->pos_target, scd->init_spos, - mdiff); + add_v2_v2v2(scd->pos_target, scd->init_spos, mdiff); CLAMP(scd->pos_target[0], -scd->dim_target[0] + PIXEL_MARGIN, scd->area_size[0] + scd->dim_target[0] - PIXEL_MARGIN); @@ -778,7 +781,7 @@ static int stencil_control_modal(bContext *C, wmOperator *op, const wmEvent *eve return OPERATOR_RUNNING_MODAL; } -static int stencil_control_poll(bContext *C) +static bool stencil_control_poll(bContext *C) { ePaintMode mode = BKE_paintmode_get_active_from_context(C); @@ -987,8 +990,9 @@ void ED_operatormacros_paint(void) wmOperatorType *ot; wmOperatorTypeMacro *otmacro; - ot = WM_operatortype_append_macro("PAINTCURVE_OT_add_point_slide", "Add Curve Point and Slide", - "Add new curve point and slide it", OPTYPE_UNDO); + ot = WM_operatortype_append_macro( + "PAINTCURVE_OT_add_point_slide", "Add Curve Point and Slide", + "Add new curve point and slide it", OPTYPE_UNDO); ot->description = "Add new curve point and slide it"; WM_operatortype_macro_define(ot, "PAINTCURVE_OT_add_point"); otmacro = WM_operatortype_macro_define(ot, "PAINTCURVE_OT_slide"); @@ -1088,8 +1092,9 @@ static void ed_keymap_paint_brush_switch(wmKeyMap *keymap, const char *mode) int i; /* index 0-9 (zero key is tenth), shift key for index 10-19 */ for (i = 0; i < 20; i++) { - kmi = WM_keymap_add_item(keymap, "BRUSH_OT_active_index_set", - ZEROKEY + ((i + 1) % 10), KM_PRESS, i < 10 ? 0 : KM_SHIFT, 0); + kmi = WM_keymap_add_item( + keymap, "BRUSH_OT_active_index_set", + ZEROKEY + ((i + 1) % 10), KM_PRESS, i < 10 ? 0 : KM_SHIFT, 0); RNA_string_set(kmi->ptr, "mode", mode); RNA_int_set(kmi->ptr, "index", i); } @@ -1106,8 +1111,9 @@ static void ed_keymap_paint_brush_size(wmKeyMap *keymap, const char *UNUSED(path RNA_float_set(kmi->ptr, "scalar", 10.0 / 9.0); // 1.1111.... } -static void set_brush_rc_path(PointerRNA *ptr, const char *brush_path, - const char *output_name, const char *input_name) +static void set_brush_rc_path( + PointerRNA *ptr, const char *brush_path, + const char *output_name, const char *input_name) { char *path; @@ -1116,9 +1122,10 @@ static void set_brush_rc_path(PointerRNA *ptr, const char *brush_path, MEM_freeN(path); } -void set_brush_rc_props(PointerRNA *ptr, const char *paint, - const char *prop, const char *secondary_prop, - RCFlags flags) +void set_brush_rc_props( + PointerRNA *ptr, const char *paint, + const char *prop, const char *secondary_prop, + RCFlags flags) { const char *ups_path = "tool_settings.unified_paint_settings"; char *brush_path; @@ -1167,8 +1174,9 @@ void set_brush_rc_props(PointerRNA *ptr, const char *paint, MEM_freeN(brush_path); } -static void ed_keymap_paint_brush_radial_control(wmKeyMap *keymap, const char *paint, - RCFlags flags) +static void ed_keymap_paint_brush_radial_control( + wmKeyMap *keymap, const char *paint, + RCFlags flags) { wmKeyMapItem *kmi; /* only size needs to follow zoom, strength shows fixed size circle */ @@ -1247,13 +1255,13 @@ void ED_keymap_paint(wmKeyConfig *keyconf) wmKeyMapItem *kmi; int i; - keymap = WM_keymap_find(keyconf, "Paint Curve", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Paint Curve", 0, 0); keymap->poll = paint_curve_poll; paint_keymap_curve(keymap); /* Sculpt mode */ - keymap = WM_keymap_find(keyconf, "Sculpt", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Sculpt", 0, 0); keymap->poll = sculpt_mode_poll; RNA_enum_set(WM_keymap_add_item(keymap, "SCULPT_OT_brush_stroke", LEFTMOUSE, KM_PRESS, 0, 0)->ptr, "mode", BRUSH_STROKE_NORMAL); @@ -1329,15 +1337,14 @@ void ED_keymap_paint(wmKeyConfig *keyconf) WM_keymap_add_menu(keymap, "VIEW3D_MT_angle_control", RKEY, KM_PRESS, 0, 0); /* Vertex Paint mode */ - keymap = WM_keymap_find(keyconf, "Vertex Paint", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Vertex Paint", 0, 0); keymap->poll = vertex_paint_mode_poll; WM_keymap_verify_item(keymap, "PAINT_OT_vertex_paint", LEFTMOUSE, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "PAINT_OT_brush_colors_flip", XKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "PAINT_OT_sample_color", SKEY, KM_PRESS, 0, 0); - WM_keymap_add_item(keymap, - "PAINT_OT_vertex_color_set", KKEY, KM_PRESS, KM_SHIFT, 0); + WM_keymap_add_item(keymap, "PAINT_OT_vertex_color_set", KKEY, KM_PRESS, KM_SHIFT, 0); ed_keymap_paint_brush_switch(keymap, "vertex_paint"); ed_keymap_paint_brush_size(keymap, "tool_settings.vertex_paint.brush.size"); @@ -1357,7 +1364,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) RNA_string_set(kmi->ptr, "data_path", "tool_settings.vertex_paint.brush.stroke_method"); /* Weight Paint mode */ - keymap = WM_keymap_find(keyconf, "Weight Paint", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Weight Paint", 0, 0); keymap->poll = weight_paint_mode_poll; WM_keymap_verify_item(keymap, "PAINT_OT_weight_paint", LEFTMOUSE, KM_PRESS, 0, 0); @@ -1369,8 +1376,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) RNA_enum_set(WM_keymap_add_item(keymap, "PAINT_OT_weight_gradient", LEFTMOUSE, KM_PRESS, KM_ALT, 0)->ptr, "type", WPAINT_GRADIENT_TYPE_LINEAR); RNA_enum_set(WM_keymap_add_item(keymap, "PAINT_OT_weight_gradient", LEFTMOUSE, KM_PRESS, KM_ALT | KM_CTRL, 0)->ptr, "type", WPAINT_GRADIENT_TYPE_RADIAL); - WM_keymap_add_item(keymap, - "PAINT_OT_weight_set", KKEY, KM_PRESS, KM_SHIFT, 0); + WM_keymap_add_item(keymap, "PAINT_OT_weight_set", KKEY, KM_PRESS, KM_SHIFT, 0); ed_keymap_paint_brush_switch(keymap, "weight_paint"); ed_keymap_paint_brush_size(keymap, "tool_settings.weight_paint.brush.size"); @@ -1390,7 +1396,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) RNA_string_set(kmi->ptr, "data_path", "tool_settings.weight_paint.brush.use_smooth_stroke"); /*Weight paint's Vertex Selection Mode */ - keymap = WM_keymap_find(keyconf, "Weight Paint Vertex Selection", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Weight Paint Vertex Selection", 0, 0); keymap->poll = vert_paint_poll; kmi = WM_keymap_add_item(keymap, "PAINT_OT_vert_select_all", AKEY, KM_PRESS, 0, 0); RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE); @@ -1404,7 +1410,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "VIEW3D_OT_select_circle", CKEY, KM_PRESS, 0, 0); /* Image/Texture Paint mode */ - keymap = WM_keymap_find(keyconf, "Image Paint", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Image Paint", 0, 0); keymap->poll = image_texture_paint_poll; RNA_enum_set(WM_keymap_add_item(keymap, "PAINT_OT_image_paint", LEFTMOUSE, KM_PRESS, 0, 0)->ptr, "mode", BRUSH_STROKE_NORMAL); @@ -1433,7 +1439,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) RNA_string_set(kmi->ptr, "data_path", "tool_settings.image_paint.brush.stroke_method"); /* face-mask mode */ - keymap = WM_keymap_find(keyconf, "Face Mask", 0, 0); + keymap = WM_keymap_ensure(keyconf, "Face Mask", 0, 0); keymap->poll = facemask_paint_poll; kmi = WM_keymap_add_item(keymap, "PAINT_OT_face_select_all", AKEY, KM_PRESS, 0, 0); @@ -1452,7 +1458,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) kmi = WM_keymap_add_item(keymap, "PAINT_OT_face_select_linked_pick", LKEY, KM_PRESS, KM_SHIFT, 0); RNA_boolean_set(kmi->ptr, "deselect", true); - keymap = WM_keymap_find(keyconf, "UV Sculpt", 0, 0); + keymap = WM_keymap_ensure(keyconf, "UV Sculpt", 0, 0); keymap->poll = uv_sculpt_keymap_poll; kmi = WM_keymap_add_item(keymap, "WM_OT_context_toggle", QKEY, KM_PRESS, 0, 0); diff --git a/source/blender/editors/sculpt_paint/paint_stroke.c b/source/blender/editors/sculpt_paint/paint_stroke.c index afd24f0fe901..de804677de94 100644 --- a/source/blender/editors/sculpt_paint/paint_stroke.c +++ b/source/blender/editors/sculpt_paint/paint_stroke.c @@ -198,8 +198,9 @@ static bool paint_tool_require_location(Brush *brush, ePaintMode mode) { switch (mode) { case ePaintSculpt: - if (ELEM(brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_ROTATE, - SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB)) + if (ELEM(brush->sculpt_tool, + SCULPT_TOOL_GRAB, SCULPT_TOOL_ROTATE, + SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB)) { return false; } @@ -214,13 +215,14 @@ static bool paint_tool_require_location(Brush *brush, ePaintMode mode) } /* Initialize the stroke cache variants from operator properties */ -static bool paint_brush_update(bContext *C, - Brush *brush, - ePaintMode mode, - struct PaintStroke *stroke, - const float mouse_init[2], - float mouse[2], float pressure, - float location[3]) +static bool paint_brush_update( + bContext *C, + Brush *brush, + ePaintMode mode, + struct PaintStroke *stroke, + const float mouse_init[2], + float mouse[2], float pressure, + float r_location[3], bool *r_location_is_set) { Scene *scene = CTX_data_scene(C); UnifiedPaintSettings *ups = stroke->ups; @@ -231,6 +233,7 @@ static bool paint_brush_update(bContext *C, bool is_dry_run = false; bool do_random = false; bool do_random_mask = false; + *r_location_is_set = false; /* XXX: Use pressure value from first brush step for brushes which don't * support strokes (grab, thumb). They depends on initial state and * brush coord/pressure/etc. @@ -329,10 +332,11 @@ static bool paint_brush_update(bContext *C, halfway[1] = dy * 0.5f + stroke->initial_mouse[1]; if (stroke->get_location) { - if (stroke->get_location(C, location, halfway)) { + if (stroke->get_location(C, r_location, halfway)) { hit = true; location_sampled = true; location_success = true; + *r_location_is_set = true; } else if (!paint_tool_require_location(brush, mode)) { hit = true; @@ -381,28 +385,33 @@ static bool paint_brush_update(bContext *C, if (do_random) { if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) { - ups->brush_rotation += -brush->mtex.random_angle / 2.0f + - brush->mtex.random_angle * BLI_frand(); + ups->brush_rotation += ( + -brush->mtex.random_angle / 2.0f + + brush->mtex.random_angle * BLI_frand()); } } if (do_random_mask) { if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) { - ups->brush_rotation_sec += -brush->mask_mtex.random_angle / 2.0f + - brush->mask_mtex.random_angle * BLI_frand(); + ups->brush_rotation_sec += ( + -brush->mask_mtex.random_angle / 2.0f + + brush->mask_mtex.random_angle * BLI_frand()); } } if (!location_sampled) { if (stroke->get_location) { - if (stroke->get_location(C, location, mouse)) + if (stroke->get_location(C, r_location, mouse)) { location_success = true; + *r_location_is_set = true; + } else if (!paint_tool_require_location(brush, mode)) location_success = true; } else { - zero_v3(location); + zero_v3(r_location); location_success = true; + /* don't set 'r_location_is_set', since we don't want to use the value. */ } } @@ -443,14 +452,24 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, const float #if 0 /* special exception here for too high pressure values on first touch in * windows for some tablets, then we just skip first touch .. */ - if (tablet && (pressure >= 0.99f) && ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || BKE_brush_use_alpha_pressure(scene, pop->s.brush) || BKE_brush_use_size_pressure(scene, pop->s.brush))) + if (tablet && (pressure >= 0.99f) && + ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || + BKE_brush_use_alpha_pressure(scene, pop->s.brush) || + BKE_brush_use_size_pressure(scene, pop->s.brush))) + { return; + } /* This can be removed once fixed properly in * BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, float *pos, double time, float pressure, void *user) * at zero pressure we should do nothing 1/2^12 is 0.0002 which is the sensitivity of the most sensitive pen tablet available */ - if (tablet && (pressure < 0.0002f) && ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || BKE_brush_use_alpha_pressure(scene, pop->s.brush) || BKE_brush_use_size_pressure(scene, pop->s.brush))) + if (tablet && (pressure < 0.0002f) && + ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) || + BKE_brush_use_alpha_pressure(scene, pop->s.brush) || + BKE_brush_use_size_pressure(scene, pop->s.brush))) + { return; + } #endif /* copy last position -before- jittering, or space fill code @@ -481,8 +500,13 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, const float } - ups->last_hit = paint_brush_update(C, brush, mode, stroke, mouse_in, mouse_out, pressure, location); - copy_v3_v3(ups->last_location, location); + bool is_location_is_set; + ups->last_hit = paint_brush_update( + C, brush, mode, stroke, mouse_in, mouse_out, pressure, + location, &is_location_is_set); + if (is_location_is_set) { + copy_v3_v3(ups->last_location, location); + } if (!ups->last_hit) { return; } @@ -529,7 +553,8 @@ static bool paint_smooth_stroke( return true; } -static float paint_space_stroke_spacing(const Scene *scene, PaintStroke *stroke, float size_pressure, float spacing_pressure) +static float paint_space_stroke_spacing( + const Scene *scene, PaintStroke *stroke, float size_pressure, float spacing_pressure) { /* brushes can have a minimum size of 1.0 but with pressure it can be smaller then a pixel * causing very high step sizes, hanging blender [#32381] */ @@ -599,7 +624,8 @@ static float paint_stroke_integrate_overlap(Brush *br, float factor) return 1.0f / max; } -static float paint_space_stroke_spacing_variable(const Scene *scene, PaintStroke *stroke, float pressure, float dpressure, float length) +static float paint_space_stroke_spacing_variable( + const Scene *scene, PaintStroke *stroke, float pressure, float dpressure, float length) { if (BKE_brush_use_size_pressure(scene, stroke->brush)) { /* use pressure to modify size. set spacing so that at 100%, the circles @@ -674,13 +700,14 @@ static int paint_space_stroke(bContext *C, wmOperator *op, const float final_mou /**** Public API ****/ -PaintStroke *paint_stroke_new(bContext *C, - wmOperator *op, - StrokeGetLocation get_location, - StrokeTestStart test_start, - StrokeUpdateStep update_step, - StrokeRedraw redraw, - StrokeDone done, int event_type) +PaintStroke *paint_stroke_new( + bContext *C, + wmOperator *op, + StrokeGetLocation get_location, + StrokeTestStart test_start, + StrokeUpdateStep update_step, + StrokeRedraw redraw, + StrokeDone done, int event_type) { PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke"); ToolSettings *toolsettings = CTX_data_tool_settings(C); @@ -777,11 +804,12 @@ bool paint_space_stroke_enabled(Brush *br, ePaintMode mode) static bool sculpt_is_grab_tool(Brush *br) { - return ELEM(br->sculpt_tool, - SCULPT_TOOL_GRAB, - SCULPT_TOOL_THUMB, - SCULPT_TOOL_ROTATE, - SCULPT_TOOL_SNAKE_HOOK); + return ELEM( + br->sculpt_tool, + SCULPT_TOOL_GRAB, + SCULPT_TOOL_THUMB, + SCULPT_TOOL_ROTATE, + SCULPT_TOOL_SNAKE_HOOK); } /* return true if the brush size can change during paint (normally used for pressure) */ @@ -882,9 +910,10 @@ struct wmKeyMap *paint_stroke_modal_keymap(struct wmKeyConfig *keyconf) return keymap; } -static void paint_stroke_add_sample(const Paint *paint, - PaintStroke *stroke, - float x, float y, float pressure) +static void paint_stroke_add_sample( + const Paint *paint, + PaintStroke *stroke, + float x, float y, float pressure) { PaintSample *sample = &stroke->samples[stroke->cur_sample]; int max_samples = CLAMPIS(paint->num_input_samples, 1, PAINT_MAX_INPUT_SAMPLES); @@ -900,8 +929,9 @@ static void paint_stroke_add_sample(const Paint *paint, stroke->num_samples++; } -static void paint_stroke_sample_average(const PaintStroke *stroke, - PaintSample *average) +static void paint_stroke_sample_average( + const PaintStroke *stroke, + PaintSample *average) { int i; @@ -1046,11 +1076,13 @@ static bool paint_stroke_curve_end(bContext *C, wmOperator *op, PaintStroke *str if (stroke->stroke_started) { paint_brush_stroke_add_step(C, op, data + 2 * j, 1.0); - paint_line_strokes_spacing(C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1)); + paint_line_strokes_spacing( + C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1)); } } else { - paint_line_strokes_spacing(C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1)); + paint_line_strokes_spacing( + C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1)); } } } @@ -1110,7 +1142,9 @@ int paint_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event) float pressure; /* see if tablet affects event. Line, anchored and drag dot strokes do not support pressure */ - pressure = (br->flag & (BRUSH_LINE | BRUSH_ANCHORED | BRUSH_DRAG_DOT)) ? 1.0f : WM_event_tablet_data(event, &stroke->pen_flip, NULL); + pressure = ( + (br->flag & (BRUSH_LINE | BRUSH_ANCHORED | BRUSH_DRAG_DOT)) ? + 1.0f : WM_event_tablet_data(event, &stroke->pen_flip, NULL)); paint_stroke_add_sample(p, stroke, event->mval[0], event->mval[1], pressure); paint_stroke_sample_average(stroke, &sample_average); @@ -1312,7 +1346,7 @@ void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data) stroke->mode_data = mode_data; } -int paint_poll(bContext *C) +bool paint_poll(bContext *C) { Paint *p = BKE_paint_get_active_from_context(C); Object *ob = CTX_data_active_object(C); diff --git a/source/blender/editors/sculpt_paint/paint_utils.c b/source/blender/editors/sculpt_paint/paint_utils.c index 77c9dcf8ac62..71b63ccbdffd 100644 --- a/source/blender/editors/sculpt_paint/paint_utils.c +++ b/source/blender/editors/sculpt_paint/paint_utils.c @@ -82,12 +82,13 @@ /* Convert the object-space axis-aligned bounding box (expressed as * its minimum and maximum corners) into a screen-space rectangle, * returns zero if the result is empty */ -bool paint_convert_bb_to_rect(rcti *rect, - const float bb_min[3], - const float bb_max[3], - const ARegion *ar, - RegionView3D *rv3d, - Object *ob) +bool paint_convert_bb_to_rect( + rcti *rect, + const float bb_min[3], + const float bb_max[3], + const ARegion *ar, + RegionView3D *rv3d, + Object *ob) { float projection_mat[4][4]; int i, j, k; @@ -128,11 +129,12 @@ bool paint_convert_bb_to_rect(rcti *rect, /* Get four planes in object-space that describe the projection of * screen_rect from screen into object-space (essentially converting a * 2D screens-space bounding box into four 3D planes) */ -void paint_calc_redraw_planes(float planes[4][4], - const ARegion *ar, - RegionView3D *rv3d, - Object *ob, - const rcti *screen_rect) +void paint_calc_redraw_planes( + float planes[4][4], + const ARegion *ar, + RegionView3D *rv3d, + Object *ob, + const rcti *screen_rect) { BoundBox bb; bglMats mats; @@ -152,8 +154,9 @@ void paint_calc_redraw_planes(float planes[4][4], negate_m4(planes); } -float paint_calc_object_space_radius(ViewContext *vc, const float center[3], - float pixel_radius) +float paint_calc_object_space_radius( + ViewContext *vc, const float center[3], + float pixel_radius) { Object *ob = vc->obact; float delta[3], scale, loc[3]; @@ -182,7 +185,9 @@ float paint_get_tex_pixel(const MTex *mtex, float u, float v, struct ImagePool * return intensity; } -void paint_get_tex_pixel_col(const MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert_to_linear, struct ColorSpace *colorspace) +void paint_get_tex_pixel_col( + const MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, + int thread, bool convert_to_linear, struct ColorSpace *colorspace) { float co[3] = {u, v, 0.0f}; int hasrgb; @@ -238,9 +243,10 @@ static void imapaint_project(float matrix[4][4], const float co[3], float pco[4] mul_m4_v4(matrix, pco); } -static void imapaint_tri_weights(float matrix[4][4], GLint view[4], - const float v1[3], const float v2[3], const float v3[3], - const float co[2], float w[3]) +static void imapaint_tri_weights( + float matrix[4][4], GLint view[4], + const float v1[3], const float v2[3], const float v3[3], + const float co[2], float w[3]) { float pv1[4], pv2[4], pv3[4], h[3], divw; float wmat[3][3], invwmat[3][3]; @@ -571,7 +577,7 @@ static int brush_curve_preset_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int brush_curve_preset_poll(bContext *C) +static bool brush_curve_preset_poll(bContext *C) { Brush *br = BKE_paint_brush(BKE_paint_get_active_from_context(C)); diff --git a/source/blender/editors/sculpt_paint/paint_vertex.c b/source/blender/editors/sculpt_paint/paint_vertex.c index 93c8b1c8fea7..e1d8cfc3221c 100644 --- a/source/blender/editors/sculpt_paint/paint_vertex.c +++ b/source/blender/editors/sculpt_paint/paint_vertex.c @@ -197,14 +197,14 @@ static void paint_last_stroke_update(Scene *scene, ARegion *ar, const float mval /* polling - retrieve whether cursor should be set or operator should be done */ /* Returns true if vertex paint mode is active */ -int vertex_paint_mode_poll(bContext *C) +bool vertex_paint_mode_poll(bContext *C) { Object *ob = CTX_data_active_object(C); return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly; } -int vertex_paint_poll(bContext *C) +bool vertex_paint_poll(bContext *C) { if (vertex_paint_mode_poll(C) && BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint)) @@ -219,14 +219,14 @@ int vertex_paint_poll(bContext *C) return 0; } -int weight_paint_mode_poll(bContext *C) +bool weight_paint_mode_poll(bContext *C) { Object *ob = CTX_data_active_object(C); return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly; } -int weight_paint_poll(bContext *C) +bool weight_paint_poll(bContext *C) { Object *ob = CTX_data_active_object(C); ScrArea *sa; @@ -938,15 +938,20 @@ static void do_weight_paint_vertex( /* Toggle operator for turning vertex paint mode on or off (copied from sculpt.c) */ -static void vertex_paint_init_session(Scene *scene, Object *ob) +static void vertex_paint_init_session(Scene *scene, Object *ob, eObjectMode object_mode) { /* Create persistent sculpt mode data */ BKE_sculpt_toolsettings_data_ensure(scene); - if (ob->sculpt == NULL) { - ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session"); - BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false); - } + BLI_assert(ob->sculpt == NULL); + ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session"); + ob->sculpt->mode_type = object_mode; + BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false); +} + +static void vertex_paint_init_stroke(Scene *scene, Object *ob) +{ + BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false); } static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob) @@ -957,12 +962,12 @@ static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob) if (ob->mode == OB_MODE_VERTEX_PAINT) { gmap = &ob->sculpt->mode.vpaint.gmap; brush = BKE_paint_brush(&ts->vpaint->paint); - ob->sculpt->mode_type = OB_MODE_VERTEX_PAINT; + BLI_assert(ob->sculpt->mode_type == OB_MODE_VERTEX_PAINT); } else if (ob->mode == OB_MODE_WEIGHT_PAINT) { gmap = &ob->sculpt->mode.wpaint.gmap; brush = BKE_paint_brush(&ts->wpaint->paint); - ob->sculpt->mode_type = OB_MODE_WEIGHT_PAINT; + BLI_assert(ob->sculpt->mode_type == OB_MODE_WEIGHT_PAINT); } else { ob->sculpt->mode_type = 0; @@ -1080,7 +1085,7 @@ static void ed_vwpaintmode_enter_generic( BKE_sculptsession_free(ob); } - vertex_paint_init_session(scene, ob); + vertex_paint_init_session(scene, ob, mode_flag); } void ED_object_vpaintmode_enter_ex( @@ -1227,7 +1232,7 @@ static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op) } /* for switching to/from mode */ -static int paint_poll_test(bContext *C) +static bool paint_poll_test(bContext *C) { Object *ob = CTX_data_active_object(C); if (ob == NULL || ob->type != OB_MESH) @@ -1454,8 +1459,9 @@ static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mo wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData"); paint_stroke_set_mode_data(stroke, wpd); ED_view3d_viewcontext_init(C, &wpd->vc); - view_angle_limits_init(&wpd->normal_angle_precalc, vp->paint.brush->falloff_angle, - (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0); + view_angle_limits_init( + &wpd->normal_angle_precalc, vp->paint.brush->falloff_angle, + (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0); wpd->active.index = vgroup_index.active; wpd->mirror.index = vgroup_index.mirror; @@ -1505,7 +1511,7 @@ static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mo } /* If not previously created, create vertex/weight paint mode session data */ - vertex_paint_init_session(scene, ob); + vertex_paint_init_stroke(scene, ob); vwpaint_update_cache_invariants(C, vp, ss, op, mouse); vertex_paint_init_session_data(ts, ob); @@ -1594,7 +1600,8 @@ static void do_wpaint_brush_blur_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap; const Brush *brush = data->brush; @@ -1621,8 +1628,8 @@ static void do_wpaint_brush_blur_task_cb_ex( if (sculpt_brush_test_sq_fn(&test, vd.co)) { /* For grid based pbvh, take the vert whose loop coopresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const char v_flag = data->me->mvert[v_index].flag; /* If the vertex is selected */ if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) { @@ -1685,7 +1692,8 @@ static void do_wpaint_brush_smear_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap; const Brush *brush = data->brush; @@ -1717,8 +1725,8 @@ static void do_wpaint_brush_smear_task_cb_ex( if (sculpt_brush_test_sq_fn(&test, vd.co)) { /* For grid based pbvh, take the vert whose loop cooresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const MVert *mv_curr = &data->me->mvert[v_index]; /* If the vertex is selected */ @@ -1794,7 +1802,8 @@ static void do_wpaint_brush_draw_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const Scene *scene = CTX_data_scene(data->C); const Brush *brush = data->brush; @@ -1823,8 +1832,8 @@ static void do_wpaint_brush_draw_task_cb_ex( /* Note: grids are 1:1 with corners (aka loops). * For multires, take the vert whose loop cooresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const char v_flag = data->me->mvert[v_index].flag; /* If the vertex is selected */ @@ -1867,7 +1876,8 @@ static void do_wpaint_brush_calc_average_weight_cb_ex( SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; StrokeCache *cache = ss->cache; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const bool use_normal = vwpaint_use_normal(data->vp); const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0; @@ -1892,8 +1902,8 @@ static void do_wpaint_brush_calc_average_weight_cb_ex( const float angle_cos = (use_normal && vd.no) ? dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f; if (angle_cos > 0.0 && BKE_brush_curve_strength(data->brush, sqrtf(test.dist), cache->radius) > 0.0) { - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - // const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + // const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const char v_flag = data->me->mvert[v_index].flag; /* If the vertex is selected. */ @@ -2444,13 +2454,13 @@ static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const f vpd = MEM_callocN(sizeof(*vpd), "VPaintData"); paint_stroke_set_mode_data(stroke, vpd); ED_view3d_viewcontext_init(C, &vpd->vc); - view_angle_limits_init(&vpd->normal_angle_precalc, vp->paint.brush->falloff_angle, - (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0); + view_angle_limits_init( + &vpd->normal_angle_precalc, vp->paint.brush->falloff_angle, + (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0); vpd->paintcol = vpaint_get_current_col(scene, vp); - vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) && - brush->mtex.tex; + vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) && brush->mtex.tex; /* are we painting onto a modified mesh?, * if not we can skip face map trickiness */ @@ -2482,7 +2492,7 @@ static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const f } /* If not previously created, create vertex/weight paint mode session data */ - vertex_paint_init_session(scene, ob); + vertex_paint_init_stroke(scene, ob); vwpaint_update_cache_invariants(C, vp, ss, op, mouse); vertex_paint_init_session_data(ts, ob); @@ -2500,7 +2510,8 @@ static void do_vpaint_brush_calc_average_color_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap; StrokeCache *cache = ss->cache; @@ -2522,7 +2533,7 @@ static void do_vpaint_brush_calc_average_color_cb_ex( { /* Test to see if the vertex coordinates are within the spherical brush region. */ if (sculpt_brush_test_sq_fn(&test, vd.co)) { - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; if (BKE_brush_curve_strength(data->brush, 0.0, cache->radius) > 0.0) { /* If the vertex is selected for painting. */ const MVert *mv = &data->me->mvert[v_index]; @@ -2564,7 +2575,8 @@ static void do_vpaint_brush_draw_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap; const Brush *brush = data->brush; @@ -2592,8 +2604,8 @@ static void do_vpaint_brush_draw_task_cb_ex( /* Note: Grids are 1:1 with corners (aka loops). * For grid based pbvh, take the vert whose loop cooresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const MVert *mv = &data->me->mvert[v_index]; /* If the vertex is selected for painting. */ @@ -2658,7 +2670,8 @@ static void do_vpaint_brush_blur_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); Scene *scene = CTX_data_scene(data->C); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap; @@ -2685,8 +2698,8 @@ static void do_vpaint_brush_blur_task_cb_ex( if (sculpt_brush_test_sq_fn(&test, vd.co)) { /* For grid based pbvh, take the vert whose loop cooresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const MVert *mv = &data->me->mvert[v_index]; /* If the vertex is selected for painting. */ @@ -2769,7 +2782,8 @@ static void do_vpaint_brush_smear_task_cb_ex( { SculptThreadedTaskData *data = userdata; SculptSession *ss = data->ob->sculpt; - CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh); + const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh); + const bool has_grids = (pbvh_type == PBVH_GRIDS); Scene *scene = CTX_data_scene(data->C); const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap; @@ -2802,8 +2816,8 @@ static void do_vpaint_brush_smear_task_cb_ex( if (sculpt_brush_test_sq_fn(&test, vd.co)) { /* For grid based pbvh, take the vert whose loop cooresponds to the current grid. * Otherwise, take the current vert. */ - const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; - const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f; + const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i]; + const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f; const MVert *mv_curr = &data->me->mvert[v_index]; /* if the vertex is selected for painting. */ @@ -3188,4 +3202,3 @@ void PAINT_OT_vertex_paint(wmOperatorType *ot) paint_stroke_operator_properties(ot); } - diff --git a/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c b/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c index b69ca32e5af9..4959c40c65e7 100644 --- a/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c +++ b/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c @@ -48,7 +48,7 @@ #include "paint_intern.h" /* own include */ -static int vertex_weight_paint_mode_poll(bContext *C) +static bool vertex_weight_paint_mode_poll(bContext *C) { Object *ob = CTX_data_active_object(C); Mesh *me = BKE_mesh_from_object(ob); diff --git a/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c b/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c index 957cb6a7389f..1a37973cd7d8 100644 --- a/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c +++ b/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c @@ -115,7 +115,7 @@ static void wpaint_prev_destroy(struct WPaintPrev *wpp) /** \name Weight from Bones Operator * \{ */ -static int weight_from_bones_poll(bContext *C) +static bool weight_from_bones_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -148,8 +148,9 @@ void PAINT_OT_weight_from_bones(wmOperatorType *ot) /* identifiers */ ot->name = "Weight from Bones"; ot->idname = "PAINT_OT_weight_from_bones"; - ot->description = "Set the weights of the groups matching the attached armature's selected bones, " - "using the distance between the vertices and the bones"; + ot->description = ( + "Set the weights of the groups matching the attached armature's selected bones, " + "using the distance between the vertices and the bones"); /* api callbacks */ ot->exec = weight_from_bones_exec; diff --git a/source/blender/editors/sculpt_paint/sculpt.c b/source/blender/editors/sculpt_paint/sculpt.c index bef705a29b1a..74baa267b692 100644 --- a/source/blender/editors/sculpt_paint/sculpt.c +++ b/source/blender/editors/sculpt_paint/sculpt.c @@ -4079,25 +4079,25 @@ static void sculpt_update_tex(const Scene *scene, Sculpt *sd, SculptSession *ss) -int sculpt_mode_poll(bContext *C) +bool sculpt_mode_poll(bContext *C) { Object *ob = CTX_data_active_object(C); return ob && ob->mode & OB_MODE_SCULPT; } -int sculpt_mode_poll_view3d(bContext *C) +bool sculpt_mode_poll_view3d(bContext *C) { return (sculpt_mode_poll(C) && CTX_wm_region_view3d(C)); } -int sculpt_poll_view3d(bContext *C) +bool sculpt_poll_view3d(bContext *C) { return (sculpt_poll(C) && CTX_wm_region_view3d(C)); } -int sculpt_poll(bContext *C) +bool sculpt_poll(bContext *C) { return sculpt_mode_poll(C) && paint_poll(C); } @@ -4804,7 +4804,7 @@ static void sculpt_brush_init_tex(const Scene *scene, Sculpt *sd, SculptSession sculpt_update_tex(scene, sd, ss); } -static bool sculpt_brush_stroke_init(bContext *C, wmOperator *op) +static void sculpt_brush_stroke_init(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Object *ob = CTX_data_active_object(C); @@ -4824,8 +4824,6 @@ static bool sculpt_brush_stroke_init(bContext *C, wmOperator *op) is_smooth = sculpt_any_smooth_mode(brush, NULL, mode); BKE_sculpt_update_mesh_elements(scene, sd, ob, is_smooth, need_mask); - - return 1; } static void sculpt_restore_mesh(Sculpt *sd, Object *ob) @@ -5069,8 +5067,7 @@ static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, const wmEvent int ignore_background_click; int retval; - if (!sculpt_brush_stroke_init(C, op)) - return OPERATOR_CANCELLED; + sculpt_brush_stroke_init(C, op); stroke = paint_stroke_new(C, op, sculpt_stroke_get_location, sculpt_stroke_test_start, @@ -5102,8 +5099,7 @@ static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, const wmEvent static int sculpt_brush_stroke_exec(bContext *C, wmOperator *op) { - if (!sculpt_brush_stroke_init(C, op)) - return OPERATOR_CANCELLED; + sculpt_brush_stroke_init(C, op); op->customdata = paint_stroke_new(C, op, sculpt_stroke_get_location, sculpt_stroke_test_start, sculpt_stroke_update_step, NULL, sculpt_stroke_done, 0); @@ -5531,7 +5527,7 @@ static int sculpt_optimize_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int sculpt_and_dynamic_topology_poll(bContext *C) +static bool sculpt_and_dynamic_topology_poll(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -5830,7 +5826,7 @@ static void SCULPT_OT_sculptmode_toggle(wmOperatorType *ot) } -static int sculpt_and_dynamic_topology_constant_detail_poll(bContext *C) +static bool sculpt_and_dynamic_topology_constant_detail_poll(bContext *C) { Object *ob = CTX_data_active_object(C); Sculpt *sd = CTX_data_tool_settings(C)->sculpt; diff --git a/source/blender/editors/sculpt_paint/sculpt_intern.h b/source/blender/editors/sculpt_paint/sculpt_intern.h index 1c94c1d91981..137e957dce6b 100644 --- a/source/blender/editors/sculpt_paint/sculpt_intern.h +++ b/source/blender/editors/sculpt_paint/sculpt_intern.h @@ -48,11 +48,11 @@ struct Object; struct SculptUndoNode; struct SculptOrigVertData; -int sculpt_mode_poll(struct bContext *C); -int sculpt_mode_poll_view3d(struct bContext *C); +bool sculpt_mode_poll(struct bContext *C); +bool sculpt_mode_poll_view3d(struct bContext *C); /* checks for a brush, not just sculpt mode */ -int sculpt_poll(struct bContext *C); -int sculpt_poll_view3d(struct bContext *C); +bool sculpt_poll(struct bContext *C); +bool sculpt_poll_view3d(struct bContext *C); /* Stroke */ bool sculpt_stroke_get_location(struct bContext *C, float out[3], const float mouse[2]); diff --git a/source/blender/editors/sculpt_paint/sculpt_uv.c b/source/blender/editors/sculpt_paint/sculpt_uv.c index 782743326607..7e30c8b5b23d 100644 --- a/source/blender/editors/sculpt_paint/sculpt_uv.c +++ b/source/blender/editors/sculpt_paint/sculpt_uv.c @@ -158,7 +158,7 @@ static Brush *uv_sculpt_brush(bContext *C) } -static int uv_sculpt_brush_poll_do(bContext *C, const bool check_region) +static bool uv_sculpt_brush_poll_do(bContext *C, const bool check_region) { BMEditMesh *em; int ret; @@ -186,7 +186,7 @@ static int uv_sculpt_brush_poll_do(bContext *C, const bool check_region) return ret; } -static int uv_sculpt_brush_poll(bContext *C) +static bool uv_sculpt_brush_poll(bContext *C) { return uv_sculpt_brush_poll_do(C, true); } @@ -246,8 +246,9 @@ void ED_space_image_uv_sculpt_update(Main *bmain, wmWindowManager *wm, Scene *sc BKE_paint_init(bmain, scene, ePaintSculptUV, PAINT_CURSOR_SCULPT); - settings->uvsculpt->paint.paint_cursor = WM_paint_cursor_activate(wm, uv_sculpt_brush_poll, - brush_drawcursor_uvsculpt, NULL); + settings->uvsculpt->paint.paint_cursor = WM_paint_cursor_activate( + wm, uv_sculpt_brush_poll, + brush_drawcursor_uvsculpt, NULL); } else { if (settings->uvsculpt) { @@ -257,12 +258,12 @@ void ED_space_image_uv_sculpt_update(Main *bmain, wmWindowManager *wm, Scene *sc } } -int uv_sculpt_poll(bContext *C) +bool uv_sculpt_poll(bContext *C) { return uv_sculpt_brush_poll_do(C, true); } -int uv_sculpt_keymap_poll(bContext *C) +bool uv_sculpt_keymap_poll(bContext *C) { return uv_sculpt_brush_poll_do(C, false); } diff --git a/source/blender/editors/sound/sound_intern.h b/source/blender/editors/sound/sound_intern.h index c1516c0f25e3..d95f473e4d9f 100644 --- a/source/blender/editors/sound/sound_intern.h +++ b/source/blender/editors/sound/sound_intern.h @@ -34,4 +34,3 @@ #endif /* __SOUND_INTERN_H__ */ - diff --git a/source/blender/editors/sound/sound_ops.c b/source/blender/editors/sound/sound_ops.c index ad8469a7c6aa..b605bd6e1a73 100644 --- a/source/blender/editors/sound/sound_ops.c +++ b/source/blender/editors/sound/sound_ops.c @@ -454,10 +454,10 @@ static bool sound_mixdown_check(bContext *UNUSED(C), wmOperator *op) prop = RNA_struct_find_property(op->ptr, "filepath"); RNA_property_string_get(op->ptr, prop, filepath); - if (BLI_testextensie_array(filepath, snd_ext_sound)) - check = BLI_replace_extension(filepath, FILE_MAX, extension); + if (BLI_path_extension_check_array(filepath, snd_ext_sound)) + check = BLI_path_extension_replace(filepath, FILE_MAX, extension); else - check = BLI_ensure_extension(filepath, FILE_MAX, extension); + check = BLI_path_extension_ensure(filepath, FILE_MAX, extension); if (!check) return check; @@ -481,7 +481,7 @@ static int sound_mixdown_invoke(bContext *C, wmOperator *op, const wmEvent *even #ifdef WITH_AUDASPACE -static bool sound_mixdown_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop) +static bool sound_mixdown_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop, void *UNUSED(user_data)) { const char *prop_id = RNA_property_identifier(prop); return !(STREQ(prop_id, "filepath") || @@ -634,7 +634,7 @@ static void sound_mixdown_draw(bContext *C, wmOperator *op) RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr); /* main draw call */ - uiDefAutoButsRNA(layout, &ptr, sound_mixdown_draw_check_prop, '\0'); + uiDefAutoButsRNA(layout, &ptr, sound_mixdown_draw_check_prop, NULL, '\0'); } #endif // WITH_AUDASPACE @@ -702,7 +702,7 @@ static void SOUND_OT_mixdown(wmOperatorType *ot) /* ******************************************************* */ -static int sound_poll(bContext *C) +static bool sound_poll(bContext *C) { Editing *ed = CTX_data_scene(C)->ed; diff --git a/source/blender/editors/space_action/action_data.c b/source/blender/editors/space_action/action_data.c index 74c9f2f8cfbf..8d4596a79a74 100644 --- a/source/blender/editors/space_action/action_data.c +++ b/source/blender/editors/space_action/action_data.c @@ -175,7 +175,7 @@ static void actedit_change_action(bContext *C, bAction *act) * The NLA Editor is active (i.e. Animation Data panel -> new action) * 2) The associated AnimData block must not be in tweakmode */ -static int action_new_poll(bContext *C) +static bool action_new_poll(bContext *C) { Scene *scene = CTX_data_scene(C); @@ -295,7 +295,7 @@ void ACTION_OT_new(wmOperatorType *ot) * 2) There must be an action active * 3) The associated AnimData block must not be in tweakmode */ -static int action_pushdown_poll(bContext *C) +static bool action_pushdown_poll(bContext *C) { if (ED_operator_action_active(C)) { SpaceAction *saction = (SpaceAction *)CTX_wm_space_data(C); @@ -426,7 +426,7 @@ void ACTION_OT_stash(wmOperatorType *ot) * 1) There must be an dopesheet/action editor, and it must be in a mode which uses actions * 2) The associated AnimData block must not be in tweakmode */ -static int action_stash_create_poll(bContext *C) +static bool action_stash_create_poll(bContext *C) { if (ED_operator_action_active(C)) { AnimData *adt = ED_actedit_animdata_from_context(C); @@ -618,7 +618,7 @@ void ED_animedit_unlink_action(bContext *C, ID *id, AnimData *adt, bAction *act, /* -------------------------- */ -static int action_unlink_poll(bContext *C) +static bool action_unlink_poll(bContext *C) { if (ED_operator_action_active(C)) { SpaceAction *saction = (SpaceAction *)CTX_wm_space_data(C); @@ -749,7 +749,7 @@ static void action_layer_switch_strip(AnimData *adt, /* ********************** One Layer Up Operator ************************** */ -static int action_layer_next_poll(bContext *C) +static bool action_layer_next_poll(bContext *C) { /* Action Editor's action editing modes only */ if (ED_operator_action_active(C)) { @@ -860,7 +860,7 @@ void ACTION_OT_layer_next(wmOperatorType *ot) /* ********************* One Layer Down Operator ************************* */ -static int action_layer_prev_poll(bContext *C) +static bool action_layer_prev_poll(bContext *C) { /* Action Editor's action editing modes only */ if (ED_operator_action_active(C)) { diff --git a/source/blender/editors/space_action/action_edit.c b/source/blender/editors/space_action/action_edit.c index bbad78c1416a..ae320aec6f48 100644 --- a/source/blender/editors/space_action/action_edit.c +++ b/source/blender/editors/space_action/action_edit.c @@ -93,7 +93,7 @@ * 3) that the set of markers being shown are the scene markers, not the list we're merging * 4) that there are some selected markers */ -static int act_markers_make_local_poll(bContext *C) +static bool act_markers_make_local_poll(bContext *C) { SpaceAction *sact = CTX_wm_space_action(C); @@ -1480,7 +1480,7 @@ void ACTION_OT_keyframe_type(wmOperatorType *ot) /* ***************** Jump to Selected Frames Operator *********************** */ -static int actkeys_framejump_poll(bContext *C) +static bool actkeys_framejump_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) diff --git a/source/blender/editors/space_action/action_intern.h b/source/blender/editors/space_action/action_intern.h index f2588b8139e6..37bef41e4d59 100644 --- a/source/blender/editors/space_action/action_intern.h +++ b/source/blender/editors/space_action/action_intern.h @@ -148,4 +148,3 @@ void action_operatortypes(void); void action_keymap(struct wmKeyConfig *keyconf); #endif /* __ACTION_INTERN_H__ */ - diff --git a/source/blender/editors/space_action/action_ops.c b/source/blender/editors/space_action/action_ops.c index 25218358ed4e..ea7591c36c0e 100644 --- a/source/blender/editors/space_action/action_ops.c +++ b/source/blender/editors/space_action/action_ops.c @@ -39,6 +39,7 @@ #include "ED_anim_api.h" #include "ED_markers.h" #include "ED_transform.h" +#include "ED_object.h" #include "action_intern.h" @@ -261,6 +262,7 @@ static void action_keymap_keyframes(wmKeyConfig *keyconf, wmKeyMap *keymap) kmi = WM_keymap_add_item(keymap, "WM_OT_context_toggle", OKEY, KM_PRESS, 0, 0); RNA_string_set(kmi->ptr, "data_path", "tool_settings.use_proportional_action"); + ED_keymap_proportional_cycle(keyconf, keymap); /* special markers hotkeys for anim editors: see note in definition of this function */ ED_marker_keymap_animedit_conflictfree(keymap); @@ -273,7 +275,7 @@ void action_keymap(wmKeyConfig *keyconf) wmKeyMap *keymap; /* keymap for all regions */ - keymap = WM_keymap_find(keyconf, "Dopesheet Generic", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(keyconf, "Dopesheet Generic", SPACE_ACTION, 0); /* region management... */ WM_keymap_add_item(keymap, "ACTION_OT_properties", NKEY, KM_PRESS, 0, 0); @@ -286,7 +288,6 @@ void action_keymap(wmKeyConfig *keyconf) */ /* keyframes */ - keymap = WM_keymap_find(keyconf, "Dopesheet", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(keyconf, "Dopesheet", SPACE_ACTION, 0); action_keymap_keyframes(keyconf, keymap); } - diff --git a/source/blender/editors/space_action/space_action.c b/source/blender/editors/space_action/space_action.c index 0b7201c28577..a2fe129c819a 100644 --- a/source/blender/editors/space_action/space_action.c +++ b/source/blender/editors/space_action/space_action.c @@ -192,9 +192,9 @@ static void action_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Dopesheet", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Dopesheet", SPACE_ACTION, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -266,10 +266,10 @@ static void action_channel_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_LIST, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Animation Channels", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Animation Channels", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -550,7 +550,7 @@ static void action_buttons_area_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Dopesheet Generic", SPACE_ACTION, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -705,4 +705,3 @@ void ED_spacetype_action(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_buttons/buttons_intern.h b/source/blender/editors/space_buttons/buttons_intern.h index 53b541ad3824..77623974d0a4 100644 --- a/source/blender/editors/space_buttons/buttons_intern.h +++ b/source/blender/editors/space_buttons/buttons_intern.h @@ -114,4 +114,3 @@ void BUTTONS_OT_directory_browse(struct wmOperatorType *ot); void BUTTONS_OT_toolbox(struct wmOperatorType *ot); #endif /* __BUTTONS_INTERN_H__ */ - diff --git a/source/blender/editors/space_buttons/buttons_texture.c b/source/blender/editors/space_buttons/buttons_texture.c index 50791cf6befc..1d9d5130f98e 100644 --- a/source/blender/editors/space_buttons/buttons_texture.c +++ b/source/blender/editors/space_buttons/buttons_texture.c @@ -687,4 +687,3 @@ void uiTemplateTextureShow(uiLayout *layout, bContext *C, PointerRNA *ptr, Prope UI_but_func_set(but, template_texture_show, user->ptr.data, user->prop); } } - diff --git a/source/blender/editors/space_buttons/space_buttons.c b/source/blender/editors/space_buttons/space_buttons.c index 3df913c5f7e0..1ff0cb53f6ad 100644 --- a/source/blender/editors/space_buttons/space_buttons.c +++ b/source/blender/editors/space_buttons/space_buttons.c @@ -131,7 +131,7 @@ static void buttons_main_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Property Editor", SPACE_BUTS, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Property Editor", SPACE_BUTS, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -185,7 +185,7 @@ static void buttons_operatortypes(void) static void buttons_keymap(struct wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Property Editor", SPACE_BUTS, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Property Editor", SPACE_BUTS, 0); WM_keymap_add_item(keymap, "BUTTONS_OT_toolbox", RIGHTMOUSE, KM_PRESS, 0, 0); } @@ -485,4 +485,3 @@ void ED_spacetype_buttons(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_clip/clip_buttons.c b/source/blender/editors/space_clip/clip_buttons.c index ec8e4a881e1a..ce97d87d0c45 100644 --- a/source/blender/editors/space_clip/clip_buttons.c +++ b/source/blender/editors/space_clip/clip_buttons.c @@ -76,7 +76,7 @@ void ED_clip_buttons_register(ARegionType *UNUSED(art)) /********************* MovieClip Template ************************/ -void uiTemplateMovieClip(uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, int compact) +void uiTemplateMovieClip(uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, bool compact) { PropertyRNA *prop; PointerRNA clipptr; @@ -332,7 +332,7 @@ static void marker_block_handler(bContext *C, void *arg_cb, int event) } void uiTemplateMarker(uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *userptr, - PointerRNA *trackptr, int compact) + PointerRNA *trackptr, bool compact) { PropertyRNA *prop; uiBlock *block; diff --git a/source/blender/editors/space_clip/clip_dopesheet_ops.c b/source/blender/editors/space_clip/clip_dopesheet_ops.c index c8675fc390b8..a12e8db6daff 100644 --- a/source/blender/editors/space_clip/clip_dopesheet_ops.c +++ b/source/blender/editors/space_clip/clip_dopesheet_ops.c @@ -53,7 +53,7 @@ #include "clip_intern.h" // own include -static int space_clip_dopesheet_poll(bContext *C) +static bool space_clip_dopesheet_poll(bContext *C) { if (ED_space_clip_tracking_poll(C)) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -70,7 +70,7 @@ static int space_clip_dopesheet_poll(bContext *C) /********************** select channel operator *********************/ -static int dopesheet_select_channel_poll(bContext *C) +static bool dopesheet_select_channel_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); diff --git a/source/blender/editors/space_clip/clip_editor.c b/source/blender/editors/space_clip/clip_editor.c index 2a218df2a44b..30628b417d44 100644 --- a/source/blender/editors/space_clip/clip_editor.c +++ b/source/blender/editors/space_clip/clip_editor.c @@ -76,7 +76,7 @@ /* ******** operactor poll functions ******** */ -int ED_space_clip_poll(bContext *C) +bool ED_space_clip_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -86,7 +86,7 @@ int ED_space_clip_poll(bContext *C) return false; } -int ED_space_clip_view_clip_poll(bContext *C) +bool ED_space_clip_view_clip_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -97,7 +97,7 @@ int ED_space_clip_view_clip_poll(bContext *C) return false; } -int ED_space_clip_tracking_poll(bContext *C) +bool ED_space_clip_tracking_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -107,7 +107,7 @@ int ED_space_clip_tracking_poll(bContext *C) return false; } -int ED_space_clip_maskedit_poll(bContext *C) +bool ED_space_clip_maskedit_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -118,7 +118,7 @@ int ED_space_clip_maskedit_poll(bContext *C) return false; } -int ED_space_clip_maskedit_mask_poll(bContext *C) +bool ED_space_clip_maskedit_mask_poll(bContext *C) { if (ED_space_clip_maskedit_poll(C)) { MovieClip *clip = CTX_data_edit_movieclip(C); diff --git a/source/blender/editors/space_clip/clip_graph_ops.c b/source/blender/editors/space_clip/clip_graph_ops.c index b572e1893ae8..2c6aad36b2a7 100644 --- a/source/blender/editors/space_clip/clip_graph_ops.c +++ b/source/blender/editors/space_clip/clip_graph_ops.c @@ -54,7 +54,7 @@ /******************** common graph-editing utilities ********************/ -static int ED_space_clip_graph_poll(bContext *C) +static bool ED_space_clip_graph_poll(bContext *C) { if (ED_space_clip_tracking_poll(C)) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -65,7 +65,7 @@ static int ED_space_clip_graph_poll(bContext *C) return false; } -static int clip_graph_knots_poll(bContext *C) +static bool clip_graph_knots_poll(bContext *C) { if (ED_space_clip_graph_poll(C)) { SpaceClip *sc = CTX_wm_space_clip(C); diff --git a/source/blender/editors/space_clip/clip_ops.c b/source/blender/editors/space_clip/clip_ops.c index 172ea0f8554a..4754d45a0d15 100644 --- a/source/blender/editors/space_clip/clip_ops.c +++ b/source/blender/editors/space_clip/clip_ops.c @@ -898,7 +898,7 @@ void CLIP_OT_view_selected(wmOperatorType *ot) /********************** change frame operator *********************/ -static int change_frame_poll(bContext *C) +static bool change_frame_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) diff --git a/source/blender/editors/space_clip/clip_toolbar.c b/source/blender/editors/space_clip/clip_toolbar.c index d2a7244ededf..7d4aa0083f1b 100644 --- a/source/blender/editors/space_clip/clip_toolbar.c +++ b/source/blender/editors/space_clip/clip_toolbar.c @@ -86,7 +86,7 @@ ARegion *ED_clip_has_properties_region(ScrArea *sa) return arnew; } -static int properties_poll(bContext *C) +static bool properties_poll(bContext *C) { return (CTX_wm_space_clip(C) != NULL); } @@ -161,7 +161,7 @@ static ARegion *clip_has_tools_region(ScrArea *sa) return artool; } -static int tools_poll(bContext *C) +static bool tools_poll(bContext *C) { return (CTX_wm_space_clip(C) != NULL); } @@ -193,7 +193,7 @@ void CLIP_OT_tools(wmOperatorType *ot) static void clip_panel_operator_redo_buts(const bContext *C, Panel *pa, wmOperator *op) { - uiTemplateOperatorPropertyButs(C, pa->layout, op, NULL, 'V', 0); + uiTemplateOperatorPropertyButs(C, pa->layout, op, 'V', 0); } static void clip_panel_operator_redo_header(const bContext *C, Panel *pa) diff --git a/source/blender/editors/space_clip/space_clip.c b/source/blender/editors/space_clip/space_clip.c index 58930fa2cf20..35aa9896d12e 100644 --- a/source/blender/editors/space_clip/space_clip.c +++ b/source/blender/editors/space_clip/space_clip.c @@ -548,7 +548,7 @@ static void clip_keymap(struct wmKeyConfig *keyconf) /* ******** Global hotkeys avalaible for all regions ******** */ - keymap = WM_keymap_find(keyconf, "Clip", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(keyconf, "Clip", SPACE_CLIP, 0); WM_keymap_add_item(keymap, "CLIP_OT_open", OKEY, KM_PRESS, KM_ALT, 0); @@ -588,7 +588,7 @@ static void clip_keymap(struct wmKeyConfig *keyconf) /* ******** Hotkeys avalaible for main region only ******** */ - keymap = WM_keymap_find(keyconf, "Clip Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(keyconf, "Clip Editor", SPACE_CLIP, 0); // keymap->poll = ED_space_clip_tracking_poll; /* ** View/navigation ** */ @@ -756,7 +756,7 @@ static void clip_keymap(struct wmKeyConfig *keyconf) /* ******** Hotkeys avalaible for preview region only ******** */ - keymap = WM_keymap_find(keyconf, "Clip Graph Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(keyconf, "Clip Graph Editor", SPACE_CLIP, 0); /* "timeline" */ WM_keymap_add_item(keymap, "CLIP_OT_change_frame", ACTIONMOUSE, KM_PRESS, 0, 0); @@ -810,7 +810,7 @@ static void clip_keymap(struct wmKeyConfig *keyconf) /* ******** Hotkeys avalaible for channels region only ******** */ - keymap = WM_keymap_find(keyconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(keyconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); kmi = WM_keymap_add_item(keymap, "CLIP_OT_dopesheet_select_channel", LEFTMOUSE, KM_PRESS, 0, 0); RNA_boolean_set(kmi->ptr, "extend", true); /* toggle */ @@ -848,7 +848,7 @@ static int clip_context(const bContext *C, const char *member, bContextDataResul } /* dropboxes */ -static int clip_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool clip_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_PATH) if (ELEM(drag->icon, 0, ICON_FILE_IMAGE, ICON_FILE_MOVIE, ICON_FILE_BLANK)) /* rule might not work? */ @@ -1137,14 +1137,14 @@ static void clip_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_STANDARD, ar->winx, ar->winy); /* mask polls mode */ - keymap = WM_keymap_find(wm->defaultconf, "Mask Editing", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Clip", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Clip Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip Editor", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -1261,13 +1261,13 @@ static void clip_preview_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Clip", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Clip Graph Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip Graph Editor", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -1365,7 +1365,7 @@ static void clip_channels_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_LIST, ar->winx, ar->winy); - keymap = WM_keymap_find(wm->defaultconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip Dopesheet Editor", SPACE_CLIP, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -1437,7 +1437,7 @@ static void clip_tools_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Clip", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip", SPACE_CLIP, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -1480,7 +1480,7 @@ static void clip_properties_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Clip", SPACE_CLIP, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Clip", SPACE_CLIP, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } diff --git a/source/blender/editors/space_clip/tracking_ops.c b/source/blender/editors/space_clip/tracking_ops.c index 50f21c8891c0..2a64b476ea49 100644 --- a/source/blender/editors/space_clip/tracking_ops.c +++ b/source/blender/editors/space_clip/tracking_ops.c @@ -2106,7 +2106,7 @@ void CLIP_OT_copy_tracks(wmOperatorType *ot) /********************* paste tracks from clipboard operator ********************/ -static int paste_tracks_poll(bContext *C) +static bool paste_tracks_poll(bContext *C) { if (ED_space_clip_tracking_poll(C)) { return BKE_tracking_clipboard_has_tracks(); diff --git a/source/blender/editors/space_clip/tracking_ops_orient.c b/source/blender/editors/space_clip/tracking_ops_orient.c index 8c5be7c9d04f..8ad31fc3b9bb 100644 --- a/source/blender/editors/space_clip/tracking_ops_orient.c +++ b/source/blender/editors/space_clip/tracking_ops_orient.c @@ -106,7 +106,7 @@ static Object *get_orientation_object(bContext *C) return object; } -static int set_orientation_poll(bContext *C) +static bool set_orientation_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); if (sc != NULL) { @@ -746,7 +746,7 @@ void CLIP_OT_set_scale(wmOperatorType *ot) /********************** set solution scale operator *********************/ -static int set_solution_scale_poll(bContext *C) +static bool set_solution_scale_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); if (sc != NULL) { @@ -806,7 +806,7 @@ void CLIP_OT_set_solution_scale(wmOperatorType *ot) /********************** apply solution scale operator *********************/ -static int apply_solution_scale_poll(bContext *C) +static bool apply_solution_scale_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); if (sc != NULL) { diff --git a/source/blender/editors/space_clip/tracking_ops_stabilize.c b/source/blender/editors/space_clip/tracking_ops_stabilize.c index 35b1aead3439..e865ee26b20c 100644 --- a/source/blender/editors/space_clip/tracking_ops_stabilize.c +++ b/source/blender/editors/space_clip/tracking_ops_stabilize.c @@ -49,7 +49,7 @@ /********************* add 2d stabilization tracks operator ********************/ -static int stabilize_2d_poll(bContext *C) +static bool stabilize_2d_poll(bContext *C) { if (ED_space_clip_tracking_poll(C)) { SpaceClip *sc = CTX_wm_space_clip(C); @@ -344,4 +344,3 @@ void CLIP_OT_stabilize_2d_rotation_select(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - diff --git a/source/blender/editors/space_clip/tracking_select.c b/source/blender/editors/space_clip/tracking_select.c index ecbc1f5ae1ee..cf4687dca318 100644 --- a/source/blender/editors/space_clip/tracking_select.c +++ b/source/blender/editors/space_clip/tracking_select.c @@ -350,7 +350,7 @@ static int mouse_select(bContext *C, float co[2], int extend) return OPERATOR_FINISHED; } -static int select_poll(bContext *C) +static bool select_poll(bContext *C) { SpaceClip *sc = CTX_wm_space_clip(C); diff --git a/source/blender/editors/space_console/space_console.c b/source/blender/editors/space_console/space_console.c index 2dfe02cc333f..919602f7bb56 100644 --- a/source/blender/editors/space_console/space_console.c +++ b/source/blender/editors/space_console/space_console.c @@ -145,7 +145,7 @@ static void console_main_region_init(wmWindowManager *wm, ARegion *ar) } /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Console", SPACE_CONSOLE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Console", SPACE_CONSOLE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* add drop boxes */ @@ -169,7 +169,7 @@ static void console_cursor(wmWindow *win, ScrArea *sa, ARegion *ar) /* ************* dropboxes ************* */ -static int id_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool id_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { // SpaceConsole *sc = CTX_wm_space_console(C); if (drag->type == WM_DRAG_ID) @@ -188,7 +188,7 @@ static void id_drop_copy(wmDrag *drag, wmDropBox *drop) MEM_freeN(text); } -static int path_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool path_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { // SpaceConsole *sc = CTX_wm_space_console(C); if (drag->type == WM_DRAG_PATH) @@ -271,7 +271,7 @@ static void console_operatortypes(void) static void console_keymap(struct wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Console", SPACE_CONSOLE, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Console", SPACE_CONSOLE, 0); wmKeyMapItem *kmi; #ifdef __APPLE__ diff --git a/source/blender/editors/space_file/file_intern.h b/source/blender/editors/space_file/file_intern.h index 742715039cf8..6eaf2dda084f 100644 --- a/source/blender/editors/space_file/file_intern.h +++ b/source/blender/editors/space_file/file_intern.h @@ -130,4 +130,3 @@ void file_panels_register(struct ARegionType *art); void file_tile_boundbox(const ARegion *ar, FileLayout *layout, const int file, rcti *r_bounds); #endif /* __FILE_INTERN_H__ */ - diff --git a/source/blender/editors/space_file/file_ops.c b/source/blender/editors/space_file/file_ops.c index 0cd31ce7ca5a..81bc585db82b 100644 --- a/source/blender/editors/space_file/file_ops.c +++ b/source/blender/editors/space_file/file_ops.c @@ -1179,9 +1179,9 @@ int file_cancel_exec(bContext *C, wmOperator *UNUSED(unused)) return OPERATOR_FINISHED; } -static int file_operator_poll(bContext *C) +static bool file_operator_poll(bContext *C) { - int poll = ED_operator_file_active(C); + bool poll = ED_operator_file_active(C); SpaceFile *sfile = CTX_wm_space_file(C); if (!sfile || !sfile->op) poll = 0; @@ -2202,7 +2202,7 @@ static int file_rename_exec(bContext *C, wmOperator *UNUSED(op)) } -static int file_rename_poll(bContext *C) +static bool file_rename_poll(bContext *C) { bool poll = ED_operator_file_active(C); SpaceFile *sfile = CTX_wm_space_file(C); @@ -2248,9 +2248,9 @@ void FILE_OT_rename(struct wmOperatorType *ot) } -static int file_delete_poll(bContext *C) +static bool file_delete_poll(bContext *C) { - int poll = ED_operator_file_active(C); + bool poll = ED_operator_file_active(C); SpaceFile *sfile = CTX_wm_space_file(C); if (sfile && sfile->params) { diff --git a/source/blender/editors/space_file/file_panels.c b/source/blender/editors/space_file/file_panels.c index 70321ca45402..a40334098d7c 100644 --- a/source/blender/editors/space_file/file_panels.c +++ b/source/blender/editors/space_file/file_panels.c @@ -43,6 +43,7 @@ #include "MEM_guardedalloc.h" #include "RNA_access.h" +#include "RNA_define.h" #include "ED_fileselect.h" @@ -57,7 +58,7 @@ #include -static int file_panel_operator_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool file_panel_operator_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceFile *sfile = CTX_wm_space_file(C); return (sfile && sfile->op); @@ -71,24 +72,30 @@ static void file_panel_operator_header(const bContext *C, Panel *pa) BLI_strncpy(pa->drawname, RNA_struct_ui_name(op->type->srna), sizeof(pa->drawname)); } -static bool file_panel_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop) -{ - const char *prop_id = RNA_property_identifier(prop); - return !(STREQ(prop_id, "filepath") || - STREQ(prop_id, "directory") || - STREQ(prop_id, "filename") - ); -} - static void file_panel_operator(const bContext *C, Panel *pa) { SpaceFile *sfile = CTX_wm_space_file(C); wmOperator *op = sfile->op; - // int empty = 1, flag; UI_block_func_set(uiLayoutGetBlock(pa->layout), file_draw_check_cb, NULL, NULL); - uiTemplateOperatorPropertyButs(C, pa->layout, op, file_panel_check_prop, '\0', UI_TEMPLATE_OP_PROPS_SHOW_EMPTY); + /* Hack: temporary hide.*/ + const char *hide[] = {"filepath", "directory", "filename", "files"}; + for (int i = 0; i < ARRAY_SIZE(hide); i++) { + PropertyRNA *prop = RNA_struct_find_property(op->ptr, hide[i]); + if (prop) { + RNA_def_property_flag(prop, PROP_HIDDEN); + } + } + + uiTemplateOperatorPropertyButs(C, pa->layout, op, '\0', UI_TEMPLATE_OP_PROPS_SHOW_EMPTY); + + for (int i = 0; i < ARRAY_SIZE(hide); i++) { + PropertyRNA *prop = RNA_struct_find_property(op->ptr, hide[i]); + if (prop) { + RNA_def_property_clear_flag(prop, PROP_HIDDEN); + } + } UI_block_func_set(uiLayoutGetBlock(pa->layout), NULL, NULL, NULL); } @@ -106,4 +113,3 @@ void file_panels_register(ARegionType *art) pt->draw = file_panel_operator; BLI_addtail(&art->paneltypes, pt); } - diff --git a/source/blender/editors/space_file/filelist.c b/source/blender/editors/space_file/filelist.c index 8123bed541c2..09e2660a762f 100644 --- a/source/blender/editors/space_file/filelist.c +++ b/source/blender/editors/space_file/filelist.c @@ -267,10 +267,11 @@ typedef struct FileListEntryPreview { ImBuf *img; } FileListEntryPreview; + typedef struct FileListFilter { unsigned int filter; unsigned int filter_id; - char filter_glob[256]; + char filter_glob[FILE_MAXFILE]; char filter_search[66]; /* + 2 for heading/trailing implicit '*' wildcards. */ short flags; } FileListFilter; @@ -1973,31 +1974,31 @@ int ED_path_extension_type(const char *path) else if (file_is_blend_backup(path)) { return FILE_TYPE_BLENDER_BACKUP; } - else if (BLI_testextensie(path, ".app")) { + else if (BLI_path_extension_check(path, ".app")) { return FILE_TYPE_APPLICATIONBUNDLE; } - else if (BLI_testextensie(path, ".py")) { + else if (BLI_path_extension_check(path, ".py")) { return FILE_TYPE_PYSCRIPT; } - else if (BLI_testextensie_n(path, ".txt", ".glsl", ".osl", ".data", ".pov", ".ini", ".mcr", ".inc", NULL)) { + else if (BLI_path_extension_check_n(path, ".txt", ".glsl", ".osl", ".data", ".pov", ".ini", ".mcr", ".inc", NULL)) { return FILE_TYPE_TEXT; } - else if (BLI_testextensie_n(path, ".ttf", ".ttc", ".pfb", ".otf", ".otc", NULL)) { + else if (BLI_path_extension_check_n(path, ".ttf", ".ttc", ".pfb", ".otf", ".otc", NULL)) { return FILE_TYPE_FTFONT; } - else if (BLI_testextensie(path, ".btx")) { + else if (BLI_path_extension_check(path, ".btx")) { return FILE_TYPE_BTX; } - else if (BLI_testextensie(path, ".dae")) { + else if (BLI_path_extension_check(path, ".dae")) { return FILE_TYPE_COLLADA; } - else if (BLI_testextensie(path, ".abc")) { + else if (BLI_path_extension_check(path, ".abc")) { return FILE_TYPE_ALEMBIC; } - else if (BLI_testextensie_array(path, imb_ext_image)) { + else if (BLI_path_extension_check_array(path, imb_ext_image)) { return FILE_TYPE_IMAGE; } - else if (BLI_testextensie(path, ".ogg")) { + else if (BLI_path_extension_check(path, ".ogg")) { if (IMB_isanim(path)) { return FILE_TYPE_MOVIE; } @@ -2005,10 +2006,10 @@ int ED_path_extension_type(const char *path) return FILE_TYPE_SOUND; } } - else if (BLI_testextensie_array(path, imb_ext_movie)) { + else if (BLI_path_extension_check_array(path, imb_ext_movie)) { return FILE_TYPE_MOVIE; } - else if (BLI_testextensie_array(path, imb_ext_audio)) { + else if (BLI_path_extension_check_array(path, imb_ext_audio)) { return FILE_TYPE_SOUND; } return 0; @@ -2233,7 +2234,7 @@ static int filelist_readjob_list_dir( /* Otherwise, do not check extensions for directories! */ else if (!(entry->typeflag & FILE_TYPE_DIR)) { entry->typeflag = file_extension_type(root, entry->relpath); - if (filter_glob[0] && BLI_testextensie_glob(entry->relpath, filter_glob)) { + if (filter_glob[0] && BLI_path_extension_check_glob(entry->relpath, filter_glob)) { entry->typeflag |= FILE_TYPE_OPERATOR; } } @@ -2464,7 +2465,7 @@ static void filelist_readjob_do( BLI_Stack *todo_dirs; TodoDir *td_dir; char dir[FILE_MAX_LIBEXTRA]; - char filter_glob[64]; /* TODO should be define! */ + char filter_glob[FILE_MAXFILE]; const char *root = filelist->filelist.root; const int max_recursion = filelist->max_recursion; int nbr_done_dirs = 0, nbr_todo_dirs = 1; diff --git a/source/blender/editors/space_file/filelist.h b/source/blender/editors/space_file/filelist.h index 4e9c1e0dd1dd..76845c442265 100644 --- a/source/blender/editors/space_file/filelist.h +++ b/source/blender/editors/space_file/filelist.h @@ -127,4 +127,3 @@ bool filelist_cache_previews_running(struct FileList *filelist); #endif #endif - diff --git a/source/blender/editors/space_file/filesel.c b/source/blender/editors/space_file/filesel.c index 4723ee07a7d1..1c86ecc327bc 100644 --- a/source/blender/editors/space_file/filesel.c +++ b/source/blender/editors/space_file/filesel.c @@ -196,6 +196,10 @@ short ED_fileselect_set_params(SpaceFile *sfile) if (tmp != params->filter_glob) { BLI_strncpy(params->filter_glob, tmp, sizeof(params->filter_glob)); MEM_freeN(tmp); + + /* Fix stupid things that truncating might have generated, + * like last group being a 'match everything' wildcard-only one... */ + BLI_path_extension_glob_validate(params->filter_glob); } params->filter |= (FILE_TYPE_OPERATOR | FILE_TYPE_FOLDER); } diff --git a/source/blender/editors/space_file/fsmenu.h b/source/blender/editors/space_file/fsmenu.h index 85804538e19b..bb201a7a80c7 100644 --- a/source/blender/editors/space_file/fsmenu.h +++ b/source/blender/editors/space_file/fsmenu.h @@ -80,4 +80,3 @@ void fsmenu_refresh_bookmarks_status(struct FSMenu *fsmenu); int fsmenu_get_active_indices(struct FSMenu *fsmenu, enum FSMenuCategory category, const char *dir); #endif - diff --git a/source/blender/editors/space_file/space_file.c b/source/blender/editors/space_file/space_file.c index 8b681bd93c33..7bab5e34d40e 100644 --- a/source/blender/editors/space_file/space_file.c +++ b/source/blender/editors/space_file/space_file.c @@ -330,10 +330,10 @@ static void file_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_LIST, ar->winx, ar->winy); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "File Browser Main", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser Main", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -453,7 +453,7 @@ static void file_keymap(struct wmKeyConfig *keyconf) { wmKeyMapItem *kmi; /* keys for all regions */ - wmKeyMap *keymap = WM_keymap_find(keyconf, "File Browser", SPACE_FILE, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "File Browser", SPACE_FILE, 0); /* More common 'fliebrowser-like navigation' shortcuts. */ WM_keymap_add_item(keymap, "FILE_OT_parent", UPARROWKEY, KM_PRESS, KM_ALT, 0); @@ -476,7 +476,7 @@ static void file_keymap(struct wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "FILE_OT_bookmark_add", BKEY, KM_PRESS, KM_CTRL, 0); /* keys for main region */ - keymap = WM_keymap_find(keyconf, "File Browser Main", SPACE_FILE, 0); + keymap = WM_keymap_ensure(keyconf, "File Browser Main", SPACE_FILE, 0); kmi = WM_keymap_add_item(keymap, "FILE_OT_execute", LEFTMOUSE, KM_DBL_CLICK, 0, 0); RNA_boolean_set(kmi->ptr, "need_active", true); @@ -568,7 +568,7 @@ static void file_keymap(struct wmKeyConfig *keyconf) /* keys for button region (top) */ - keymap = WM_keymap_find(keyconf, "File Browser Buttons", SPACE_FILE, 0); + keymap = WM_keymap_ensure(keyconf, "File Browser Buttons", SPACE_FILE, 0); kmi = WM_keymap_add_item(keymap, "FILE_OT_filenum", PADPLUSKEY, KM_PRESS, 0, 0); RNA_int_set(kmi->ptr, "increment", 1); kmi = WM_keymap_add_item(keymap, "FILE_OT_filenum", PADPLUSKEY, KM_PRESS, KM_SHIFT, 0); @@ -592,7 +592,7 @@ static void file_tools_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -618,7 +618,7 @@ static void file_header_region_init(wmWindowManager *wm, ARegion *ar) ED_region_header_init(ar); - keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -635,10 +635,10 @@ static void file_ui_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_HEADER, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "File Browser", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "File Browser Buttons", SPACE_FILE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "File Browser Buttons", SPACE_FILE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -677,7 +677,7 @@ static void file_ui_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), AR } } -static int filepath_drop_poll(bContext *C, wmDrag *drag, const wmEvent *UNUSED(event)) +static bool filepath_drop_poll(bContext *C, wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_PATH) { SpaceFile *sfile = CTX_wm_space_file(C); @@ -811,4 +811,3 @@ void ED_file_read_bookmarks(void) fsmenu_read_bookmarks(ED_fsmenu_get(), name); } } - diff --git a/source/blender/editors/space_graph/graph_buttons.c b/source/blender/editors/space_graph/graph_buttons.c index d5586a51a40a..22ca3275ff96 100644 --- a/source/blender/editors/space_graph/graph_buttons.c +++ b/source/blender/editors/space_graph/graph_buttons.c @@ -103,7 +103,7 @@ static int graph_panel_context(const bContext *C, bAnimListElem **ale, FCurve ** return 1; } -static int graph_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool graph_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { return graph_panel_context(C, NULL, NULL); } @@ -576,7 +576,7 @@ static void driver_update_flags_cb(bContext *UNUSED(C), void *fcu_v, void *UNUSE } /* drivers panel poll */ -static int graph_panel_drivers_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool graph_panel_drivers_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceIpo *sipo = CTX_wm_space_graph(C); @@ -782,7 +782,7 @@ static void graph_panel_drivers(const bContext *C, Panel *pa) /* errors? */ if ((G.f & G_SCRIPT_AUTOEXEC) == 0) { - uiItemL(col, IFACE_("ERROR: Python auto-execution disabled"), ICON_CANCEL); + uiItemL(col, IFACE_("WARNING: Python expressions limited for security"), ICON_ERROR); } else if (driver->flag & DRIVER_FLAG_INVALID) { uiItemL(col, IFACE_("ERROR: Invalid Python expression"), ICON_CANCEL); diff --git a/source/blender/editors/space_graph/graph_edit.c b/source/blender/editors/space_graph/graph_edit.c index 0b8e89160b75..7717b8c82005 100644 --- a/source/blender/editors/space_graph/graph_edit.c +++ b/source/blender/editors/space_graph/graph_edit.c @@ -1971,7 +1971,7 @@ void GRAPH_OT_euler_filter(wmOperatorType *ot) /* ***************** Jump to Selected Frames Operator *********************** */ -static int graphkeys_framejump_poll(bContext *C) +static bool graphkeys_framejump_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) @@ -2806,7 +2806,7 @@ static int graph_driver_delete_invalid_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int graph_driver_delete_invalid_poll(bContext *C) +static bool graph_driver_delete_invalid_poll(bContext *C) { bAnimContext ac; ScrArea *sa = CTX_wm_area(C); diff --git a/source/blender/editors/space_graph/graph_intern.h b/source/blender/editors/space_graph/graph_intern.h index da352d4ea066..c50e0497519d 100644 --- a/source/blender/editors/space_graph/graph_intern.h +++ b/source/blender/editors/space_graph/graph_intern.h @@ -170,10 +170,10 @@ void graph_buttons_register(struct ARegionType *art); struct bAnimListElem *get_active_fcurve_channel(struct bAnimContext *ac); -int graphop_visible_keyframes_poll(struct bContext *C); -int graphop_editable_keyframes_poll(struct bContext *C); -int graphop_active_fcurve_poll(struct bContext *C); -int graphop_selected_fcurve_poll(struct bContext *C); +bool graphop_visible_keyframes_poll(struct bContext *C); +bool graphop_editable_keyframes_poll(struct bContext *C); +bool graphop_active_fcurve_poll(struct bContext *C); +bool graphop_selected_fcurve_poll(struct bContext *C); /* ***************************************** */ /* graph_ops.c */ diff --git a/source/blender/editors/space_graph/graph_ops.c b/source/blender/editors/space_graph/graph_ops.c index b90fdd9ac677..0bb46ca6fb85 100644 --- a/source/blender/editors/space_graph/graph_ops.c +++ b/source/blender/editors/space_graph/graph_ops.c @@ -67,7 +67,7 @@ * 2) Value Indicator (stored per Graph Editor instance) */ -static int graphview_cursor_poll(bContext *C) +static bool graphview_cursor_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) @@ -686,7 +686,7 @@ void graphedit_keymap(wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* keymap for all regions */ - keymap = WM_keymap_find(keyconf, "Graph Editor Generic", SPACE_IPO, 0); + keymap = WM_keymap_ensure(keyconf, "Graph Editor Generic", SPACE_IPO, 0); WM_keymap_add_item(keymap, "GRAPH_OT_properties", NKEY, KM_PRESS, 0, 0); /* extrapolation works on channels, not keys */ @@ -712,7 +712,6 @@ void graphedit_keymap(wmKeyConfig *keyconf) */ /* keyframes */ - keymap = WM_keymap_find(keyconf, "Graph Editor", SPACE_IPO, 0); + keymap = WM_keymap_ensure(keyconf, "Graph Editor", SPACE_IPO, 0); graphedit_keymap_keyframes(keyconf, keymap); } - diff --git a/source/blender/editors/space_graph/graph_utils.c b/source/blender/editors/space_graph/graph_utils.c index f55a5511e2d6..ad59e8c7edab 100644 --- a/source/blender/editors/space_graph/graph_utils.c +++ b/source/blender/editors/space_graph/graph_utils.c @@ -90,7 +90,7 @@ bAnimListElem *get_active_fcurve_channel(bAnimContext *ac) /* Operator Polling Callbacks */ /* Check if there are any visible keyframes (for selection tools) */ -int graphop_visible_keyframes_poll(bContext *C) +bool graphop_visible_keyframes_poll(bContext *C) { bAnimContext ac; bAnimListElem *ale; @@ -139,7 +139,7 @@ int graphop_visible_keyframes_poll(bContext *C) } /* Check if there are any visible + editable keyframes (for editing tools) */ -int graphop_editable_keyframes_poll(bContext *C) +bool graphop_editable_keyframes_poll(bContext *C) { bAnimContext ac; bAnimListElem *ale; @@ -189,7 +189,7 @@ int graphop_editable_keyframes_poll(bContext *C) } /* has active F-Curve that's editable */ -int graphop_active_fcurve_poll(bContext *C) +bool graphop_active_fcurve_poll(bContext *C) { bAnimContext ac; bAnimListElem *ale; @@ -229,7 +229,7 @@ int graphop_active_fcurve_poll(bContext *C) } /* has selected F-Curve that's editable */ -int graphop_selected_fcurve_poll(bContext *C) +bool graphop_selected_fcurve_poll(bContext *C) { bAnimContext ac; ListBase anim_data = {NULL, NULL}; diff --git a/source/blender/editors/space_graph/space_graph.c b/source/blender/editors/space_graph/space_graph.c index 383c2b5b2204..4e39c741b9ba 100644 --- a/source/blender/editors/space_graph/space_graph.c +++ b/source/blender/editors/space_graph/space_graph.c @@ -216,9 +216,9 @@ static void graph_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Graph Editor", SPACE_IPO, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Graph Editor", SPACE_IPO, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -343,9 +343,9 @@ static void graph_channel_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_LIST, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Animation Channels", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Animation Channels", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -395,7 +395,7 @@ static void graph_buttons_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Graph Editor Generic", SPACE_IPO, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -759,4 +759,3 @@ void ED_spacetype_ipo(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_image/image_buttons.c b/source/blender/editors/space_image/image_buttons.c index dee7439a2781..44af24cbab51 100644 --- a/source/blender/editors/space_image/image_buttons.c +++ b/source/blender/editors/space_image/image_buttons.c @@ -826,7 +826,7 @@ static void rna_update_cb(bContext *C, void *arg_cb, void *UNUSED(arg)) RNA_property_update(C, &cb->ptr, cb->prop); } -void uiTemplateImage(uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, PointerRNA *userptr, int compact, int multiview, int cubemap) +void uiTemplateImage(uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, PointerRNA *userptr, bool compact, bool multiview, bool cubemap) { PropertyRNA *prop; PointerRNA imaptr; @@ -1072,7 +1072,7 @@ void uiTemplateImage(uiLayout *layout, bContext *C, PointerRNA *ptr, const char MEM_freeN(cb); } -void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, int color_management) +void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, bool color_management) { ImageFormatData *imf = imfptr->data; ID *id = imfptr->id.data; @@ -1358,4 +1358,3 @@ void IMAGE_OT_toolshelf(wmOperatorType *ot) /* flags */ ot->flag = 0; } - diff --git a/source/blender/editors/space_image/image_edit.c b/source/blender/editors/space_image/image_edit.c index 087f3cdc7fe2..5eaefcc9bb2f 100644 --- a/source/blender/editors/space_image/image_edit.c +++ b/source/blender/editors/space_image/image_edit.c @@ -386,7 +386,7 @@ bool ED_space_image_check_show_maskedit(Scene *scene, SpaceImage *sima) return (sima->mode == SI_MODE_MASK); } -int ED_space_image_maskedit_poll(bContext *C) +bool ED_space_image_maskedit_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); @@ -413,7 +413,7 @@ bool ED_space_image_paint_curve(const bContext *C) } -int ED_space_image_maskedit_mask_poll(bContext *C) +bool ED_space_image_maskedit_mask_poll(bContext *C) { if (ED_space_image_maskedit_poll(C)) { SpaceImage *sima = CTX_wm_space_image(C); @@ -422,4 +422,3 @@ int ED_space_image_maskedit_mask_poll(bContext *C) return false; } - diff --git a/source/blender/editors/space_image/image_intern.h b/source/blender/editors/space_image/image_intern.h index a5173037fcce..d90fa5365a67 100644 --- a/source/blender/editors/space_image/image_intern.h +++ b/source/blender/editors/space_image/image_intern.h @@ -54,7 +54,7 @@ void draw_image_grease_pencil(struct bContext *C, bool onlyv2d); void draw_image_sample_line(struct SpaceImage *sima); /* image_ops.c */ -int space_image_main_region_poll(struct bContext *C); +bool space_image_main_region_poll(struct bContext *C); void IMAGE_OT_view_all(struct wmOperatorType *ot); void IMAGE_OT_view_pan(struct wmOperatorType *ot); @@ -102,4 +102,3 @@ void IMAGE_OT_properties(struct wmOperatorType *ot); void IMAGE_OT_toolshelf(struct wmOperatorType *ot); #endif /* __IMAGE_INTERN_H__ */ - diff --git a/source/blender/editors/space_image/image_ops.c b/source/blender/editors/space_image/image_ops.c index ccf4040d452e..3c55ae64f6eb 100644 --- a/source/blender/editors/space_image/image_ops.c +++ b/source/blender/editors/space_image/image_ops.c @@ -179,13 +179,13 @@ static void sima_zoom_set_from_bounds(SpaceImage *sima, ARegion *ar, const rctf } #if 0 // currently unused -static int image_poll(bContext *C) +static bool image_poll(bContext *C) { return (CTX_data_edit_image(C) != NULL); } #endif -static int space_image_buffer_exists_poll(bContext *C) +static bool space_image_buffer_exists_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); if (sima && ED_space_image_has_buffer(sima)) { @@ -194,7 +194,7 @@ static int space_image_buffer_exists_poll(bContext *C) return false; } -static int image_not_packed_poll(bContext *C) +static bool image_not_packed_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); @@ -213,7 +213,7 @@ static bool imbuf_format_writeable(const ImBuf *ibuf) return (BKE_image_imtype_to_ftype(im_format.imtype, &options_dummy) == ibuf->ftype); } -static int space_image_file_exists_poll(bContext *C) +static bool space_image_file_exists_poll(bContext *C) { if (space_image_buffer_exists_poll(C)) { Main *bmain = CTX_data_main(C); @@ -249,7 +249,7 @@ static int space_image_file_exists_poll(bContext *C) } #if 0 /* UNUSED */ -static int space_image_poll(bContext *C) +static bool space_image_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); if (sima && sima->image) { @@ -259,7 +259,7 @@ static int space_image_poll(bContext *C) } #endif -int space_image_main_region_poll(bContext *C) +bool space_image_main_region_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); /* XXX ARegion *ar = CTX_wm_region(C); */ @@ -271,7 +271,7 @@ int space_image_main_region_poll(bContext *C) } /* For IMAGE_OT_curves_point_set to avoid sampling when in uv smooth mode or editmode */ -static int space_image_main_area_not_uv_brush_poll(bContext *C) +static bool space_image_main_area_not_uv_brush_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); Scene *scene = CTX_data_scene(C); @@ -283,7 +283,7 @@ static int space_image_main_area_not_uv_brush_poll(bContext *C) return 0; } -static int image_sample_poll(bContext *C) +static bool image_sample_poll(bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); if (sima) { @@ -830,7 +830,7 @@ static int image_view_selected_exec(bContext *C, wmOperator *UNUSED(op)) return OPERATOR_FINISHED; } -static int image_view_selected_poll(bContext *C) +static bool image_view_selected_poll(bContext *C) { return (space_image_main_region_poll(C) && (ED_operator_uvedit(C) || ED_operator_mask(C))); } @@ -1406,7 +1406,7 @@ static int image_open_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED( return OPERATOR_RUNNING_MODAL; } -static bool image_open_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop) +static bool image_open_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop, void *UNUSED(user_data)) { const char *prop_id = RNA_property_identifier(prop); @@ -1425,7 +1425,7 @@ static void image_open_draw(bContext *UNUSED(C), wmOperator *op) /* main draw call */ RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); - uiDefAutoButsRNA(layout, &ptr, image_open_draw_check_prop, '\0'); + uiDefAutoButsRNA(layout, &ptr, image_open_draw_check_prop, NULL, '\0'); /* image template */ RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &imf_ptr); @@ -1532,7 +1532,7 @@ static int image_replace_exec(bContext *C, wmOperator *op) BKE_image_signal(bmain, sima->image, &sima->iuser, IMA_SIGNAL_SRC_CHANGE); } - if (BLI_testextensie_array(str, imb_ext_movie)) + if (BLI_path_extension_check_array(str, imb_ext_movie)) sima->image->source = IMA_SRC_MOVIE; else sima->image->source = IMA_SRC_FILE; @@ -2120,7 +2120,7 @@ static void image_save_as_cancel(bContext *UNUSED(C), wmOperator *op) image_save_as_free(op); } -static bool image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop) +static bool image_save_as_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop, void *UNUSED(user_data)) { const char *prop_id = RNA_property_identifier(prop); @@ -2145,14 +2145,14 @@ static void image_save_as_draw(bContext *UNUSED(C), wmOperator *op) /* main draw call */ RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); - uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, '\0'); + uiDefAutoButsRNA(layout, &ptr, image_save_as_draw_check_prop, NULL, '\0'); /* multiview template */ if (is_multiview) uiTemplateImageFormatViews(layout, &imf_ptr, op->ptr); } -static int image_save_as_poll(bContext *C) +static bool image_save_as_poll(bContext *C) { if (space_image_buffer_exists_poll(C)) { if (G.is_rendering) { @@ -2656,7 +2656,7 @@ void IMAGE_OT_new(wmOperatorType *ot) /********************* invert operators *********************/ -static int image_invert_poll(bContext *C) +static bool image_invert_poll(bContext *C) { Image *ima = CTX_data_edit_image(C); @@ -3500,7 +3500,7 @@ void IMAGE_OT_record_composite(wmOperatorType *ot) /********************* cycle render slot operator *********************/ -static int image_cycle_render_slot_poll(bContext *C) +static bool image_cycle_render_slot_poll(bContext *C) { Image *ima = CTX_data_edit_image(C); @@ -3544,7 +3544,7 @@ void IMAGE_OT_cycle_render_slot(wmOperatorType *ot) /********************** change frame operator *********************/ -static int change_frame_poll(bContext *C) +static bool change_frame_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) diff --git a/source/blender/editors/space_image/space_image.c b/source/blender/editors/space_image/space_image.c index 497a068cce2c..de628a4b8344 100644 --- a/source/blender/editors/space_image/space_image.c +++ b/source/blender/editors/space_image/space_image.c @@ -283,7 +283,7 @@ static void image_operatortypes(void) static void image_keymap(struct wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Image Generic", SPACE_IMAGE, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Image Generic", SPACE_IMAGE, 0); wmKeyMapItem *kmi; int i; @@ -299,7 +299,7 @@ static void image_keymap(struct wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "IMAGE_OT_cycle_render_slot", JKEY, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "IMAGE_OT_cycle_render_slot", JKEY, KM_PRESS, KM_ALT, 0)->ptr, "reverse", true); - keymap = WM_keymap_find(keyconf, "Image", SPACE_IMAGE, 0); + keymap = WM_keymap_ensure(keyconf, "Image", SPACE_IMAGE, 0); WM_keymap_add_item(keymap, "IMAGE_OT_view_all", HOMEKEY, KM_PRESS, 0, 0); @@ -375,7 +375,7 @@ static void image_keymap(struct wmKeyConfig *keyconf) } /* dropboxes */ -static int image_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool image_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_PATH) if (ELEM(drag->icon, 0, ICON_FILE_IMAGE, ICON_FILE_MOVIE, ICON_FILE_BLANK)) /* rule might not work? */ @@ -661,29 +661,29 @@ static void image_main_region_init(wmWindowManager *wm, ARegion *ar) // UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_STANDARD, ar->winx, ar->winy); /* mask polls mode */ - keymap = WM_keymap_find(wm->defaultconf, "Mask Editing", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* image paint polls for mode */ - keymap = WM_keymap_find(wm->defaultconf, "Curve", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Curve", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Paint Curve", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Paint Curve", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Image Paint", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image Paint", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "UV Editor", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "UV Editor", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "UV Sculpt", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "UV Sculpt", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Image", SPACE_IMAGE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image", SPACE_IMAGE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -836,7 +836,7 @@ static void image_buttons_region_init(wmWindowManager *wm, ARegion *ar) ar->v2d.scroll = V2D_SCROLL_RIGHT | V2D_SCROLL_VERTICAL_HIDE; ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -888,7 +888,7 @@ static void image_tools_region_init(wmWindowManager *wm, ARegion *ar) ar->v2d.scroll = V2D_SCROLL_RIGHT | V2D_SCROLL_VERTICAL_HIDE; ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image Generic", SPACE_IMAGE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -1086,4 +1086,3 @@ void ED_spacetype_image(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_info/space_info.c b/source/blender/editors/space_info/space_info.c index 92b1be066b04..7e3d57f95ed6 100644 --- a/source/blender/editors/space_info/space_info.c +++ b/source/blender/editors/space_info/space_info.c @@ -133,7 +133,7 @@ static void info_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Info", SPACE_INFO, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Info", SPACE_INFO, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -203,12 +203,12 @@ static void info_operatortypes(void) static void info_keymap(struct wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Window", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Window", 0, 0); WM_keymap_verify_item(keymap, "INFO_OT_reports_display_update", TIMERREPORT, KM_ANY, KM_ANY, 0); /* info space */ - keymap = WM_keymap_find(keyconf, "Info", SPACE_INFO, 0); + keymap = WM_keymap_ensure(keyconf, "Info", SPACE_INFO, 0); /* report selection */ @@ -256,7 +256,7 @@ static void info_header_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegi /* context changes */ switch (wmn->category) { case NC_SCREEN: - if (ELEM(wmn->data, ND_SCREENCAST, ND_ANIMPLAY)) + if (ELEM(wmn->data, ND_ANIMPLAY)) ED_region_tag_redraw(ar); break; case NC_WM: diff --git a/source/blender/editors/space_logic/logic_buttons.c b/source/blender/editors/space_logic/logic_buttons.c index 9de3daa41cac..40edb9ca095c 100644 --- a/source/blender/editors/space_logic/logic_buttons.c +++ b/source/blender/editors/space_logic/logic_buttons.c @@ -163,4 +163,3 @@ void LOGIC_OT_links_cut(wmOperatorType *ot) /* internal */ RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX); } - diff --git a/source/blender/editors/space_logic/logic_intern.h b/source/blender/editors/space_logic/logic_intern.h index b976538b7294..ddbb145440d3 100644 --- a/source/blender/editors/space_logic/logic_intern.h +++ b/source/blender/editors/space_logic/logic_intern.h @@ -52,4 +52,3 @@ void logic_buttons(struct bContext *C, struct ARegion *ar); void make_unique_prop_names(struct bContext *C, char *str); #endif /* __LOGIC_INTERN_H__ */ - diff --git a/source/blender/editors/space_logic/logic_ops.c b/source/blender/editors/space_logic/logic_ops.c index 065f27a12fb5..39a5733e5128 100644 --- a/source/blender/editors/space_logic/logic_ops.c +++ b/source/blender/editors/space_logic/logic_ops.c @@ -67,7 +67,7 @@ #include "logic_intern.h" /* ************* Generic Operator Helpers ************* */ -static int edit_sensor_poll(bContext *C) +static bool edit_sensor_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "sensor", &RNA_Sensor); @@ -75,7 +75,7 @@ static int edit_sensor_poll(bContext *C) return 1; } -static int edit_controller_poll(bContext *C) +static bool edit_controller_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "controller", &RNA_Controller); @@ -83,7 +83,7 @@ static int edit_controller_poll(bContext *C) return 1; } -static int edit_actuator_poll(bContext *C) +static bool edit_actuator_poll(bContext *C) { PointerRNA ptr = CTX_data_pointer_get_type(C, "actuator", &RNA_Actuator); diff --git a/source/blender/editors/space_logic/logic_window.c b/source/blender/editors/space_logic/logic_window.c index b0072af207d6..1db2cbfad487 100644 --- a/source/blender/editors/space_logic/logic_window.c +++ b/source/blender/editors/space_logic/logic_window.c @@ -2604,4 +2604,3 @@ void logic_buttons(bContext *C, ARegion *ar) if (idar) MEM_freeN(idar); } - diff --git a/source/blender/editors/space_logic/space_logic.c b/source/blender/editors/space_logic/space_logic.c index 5bc5be28e41d..6d484b4cb4c6 100644 --- a/source/blender/editors/space_logic/space_logic.c +++ b/source/blender/editors/space_logic/space_logic.c @@ -179,7 +179,7 @@ static void logic_operatortypes(void) static void logic_keymap(struct wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Logic Editor", SPACE_LOGIC, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Logic Editor", SPACE_LOGIC, 0); WM_keymap_add_item(keymap, "LOGIC_OT_properties", NKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "LOGIC_OT_links_cut", LEFTMOUSE, KM_PRESS, KM_CTRL, 0); @@ -242,7 +242,7 @@ static void logic_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -281,7 +281,7 @@ static void logic_buttons_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -371,5 +371,3 @@ void ED_spacetype_logic(void) BKE_spacetype_register(st); } - - diff --git a/source/blender/editors/space_nla/nla_buttons.c b/source/blender/editors/space_nla/nla_buttons.c index a26e6b0280eb..659a36c4a23e 100644 --- a/source/blender/editors/space_nla/nla_buttons.c +++ b/source/blender/editors/space_nla/nla_buttons.c @@ -184,31 +184,31 @@ bool nla_panel_context(const bContext *C, PointerRNA *adt_ptr, PointerRNA *nlt_p } #if 0 -static int nla_panel_poll(const bContext *C, PanelType *pt) +static bool nla_panel_poll(const bContext *C, PanelType *pt) { return nla_panel_context(C, NULL, NULL); } #endif -static int nla_animdata_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool nla_animdata_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { PointerRNA ptr; return (nla_panel_context(C, &ptr, NULL, NULL) && (ptr.data != NULL)); } -static int nla_track_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool nla_track_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { PointerRNA ptr; return (nla_panel_context(C, NULL, &ptr, NULL) && (ptr.data != NULL)); } -static int nla_strip_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool nla_strip_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { PointerRNA ptr; return (nla_panel_context(C, NULL, NULL, &ptr) && (ptr.data != NULL)); } -static int nla_strip_actclip_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool nla_strip_actclip_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { PointerRNA ptr; NlaStrip *strip; @@ -222,7 +222,7 @@ static int nla_strip_actclip_panel_poll(const bContext *C, PanelType *UNUSED(pt) return (strip->type == NLASTRIP_TYPE_CLIP); } -static int nla_strip_eval_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool nla_strip_eval_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { PointerRNA ptr; NlaStrip *strip; diff --git a/source/blender/editors/space_nla/nla_channels.c b/source/blender/editors/space_nla/nla_channels.c index 8fdba4ce60d7..9bb25724daf3 100644 --- a/source/blender/editors/space_nla/nla_channels.c +++ b/source/blender/editors/space_nla/nla_channels.c @@ -509,7 +509,7 @@ void NLA_OT_action_pushdown(wmOperatorType *ot) /* ******************** Action Unlink ******************************** */ -static int nla_action_unlink_poll(bContext *C) +static bool nla_action_unlink_poll(bContext *C) { if (ED_operator_nla_active(C)) { return nla_panel_context(C, NULL, NULL, NULL); diff --git a/source/blender/editors/space_nla/nla_intern.h b/source/blender/editors/space_nla/nla_intern.h index 2e73c82ebb6f..a00e71a192d1 100644 --- a/source/blender/editors/space_nla/nla_intern.h +++ b/source/blender/editors/space_nla/nla_intern.h @@ -148,8 +148,8 @@ void NLA_OT_selected_objects_add(wmOperatorType *ot); /* **************************************** */ /* nla_ops.c */ -int nlaop_poll_tweakmode_off(bContext *C); -int nlaop_poll_tweakmode_on(bContext *C); +bool nlaop_poll_tweakmode_off(bContext *C); +bool nlaop_poll_tweakmode_on(bContext *C); bool nlaedit_is_tweakmode_on(bAnimContext *ac); @@ -159,4 +159,3 @@ void nla_operatortypes(void); void nla_keymap(wmKeyConfig *keyconf); #endif /* __NLA_INTERN_H__ */ - diff --git a/source/blender/editors/space_nla/nla_ops.c b/source/blender/editors/space_nla/nla_ops.c index 0c087fa67b95..78e70b765641 100644 --- a/source/blender/editors/space_nla/nla_ops.c +++ b/source/blender/editors/space_nla/nla_ops.c @@ -52,7 +52,7 @@ /* ************************** poll callbacks for operators **********************************/ /* tweakmode is NOT enabled */ -int nlaop_poll_tweakmode_off(bContext *C) +bool nlaop_poll_tweakmode_off(bContext *C) { Scene *scene; @@ -74,7 +74,7 @@ int nlaop_poll_tweakmode_off(bContext *C) } /* tweakmode IS enabled */ -int nlaop_poll_tweakmode_on(bContext *C) +bool nlaop_poll_tweakmode_on(bContext *C) { Scene *scene; @@ -313,7 +313,7 @@ void nla_keymap(wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* keymap for all regions ------------------------------------------- */ - keymap = WM_keymap_find(keyconf, "NLA Generic", SPACE_NLA, 0); + keymap = WM_keymap_ensure(keyconf, "NLA Generic", SPACE_NLA, 0); /* region management */ WM_keymap_add_item(keymap, "NLA_OT_properties", NKEY, KM_PRESS, 0, 0); @@ -345,10 +345,10 @@ void nla_keymap(wmKeyConfig *keyconf) * * However, those operations which involve clicking on channels and/or the placement of them in the view are implemented here instead */ - keymap = WM_keymap_find(keyconf, "NLA Channels", SPACE_NLA, 0); + keymap = WM_keymap_ensure(keyconf, "NLA Channels", SPACE_NLA, 0); nla_keymap_channels(keymap); /* data ------------------------------------------------------------- */ - keymap = WM_keymap_find(keyconf, "NLA Editor", SPACE_NLA, 0); + keymap = WM_keymap_ensure(keyconf, "NLA Editor", SPACE_NLA, 0); nla_keymap_main(keyconf, keymap); } diff --git a/source/blender/editors/space_nla/space_nla.c b/source/blender/editors/space_nla/space_nla.c index 88ef4a181420..1f9ff9aaabd8 100644 --- a/source/blender/editors/space_nla/space_nla.c +++ b/source/blender/editors/space_nla/space_nla.c @@ -212,13 +212,13 @@ static void nla_channel_region_init(wmWindowManager *wm, ARegion *ar) /* own keymap */ /* own channels map first to override some channel keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "NLA Channels", SPACE_NLA, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "NLA Channels", SPACE_NLA, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* now generic channels map for everything else that can apply */ - keymap = WM_keymap_find(wm->defaultconf, "Animation Channels", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Animation Channels", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -258,9 +258,9 @@ static void nla_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "NLA Editor", SPACE_NLA, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "NLA Editor", SPACE_NLA, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -344,7 +344,7 @@ static void nla_buttons_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "NLA Generic", SPACE_NLA, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } diff --git a/source/blender/editors/space_node/drawnode.c b/source/blender/editors/space_node/drawnode.c index 327be46a041d..bcc5b41dbe23 100644 --- a/source/blender/editors/space_node/drawnode.c +++ b/source/blender/editors/space_node/drawnode.c @@ -968,6 +968,8 @@ static void node_shader_buts_tex_musgrave(uiLayout *layout, bContext *UNUSED(C), static void node_shader_buts_tex_voronoi(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) { uiItemR(layout, ptr, "coloring", 0, "", ICON_NONE); + uiItemR(layout, ptr, "distance", 0, "", ICON_NONE); + uiItemR(layout, ptr, "feature", 0, "", ICON_NONE); } static void node_shader_buts_tex_pointdensity(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) @@ -1116,6 +1118,11 @@ static void node_shader_buts_hair(uiLayout *layout, bContext *UNUSED(C), Pointer uiItemR(layout, ptr, "component", 0, "", ICON_NONE); } +static void node_shader_buts_principled_hair(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) +{ + uiItemR(layout, ptr, "parametrization", 0, "", ICON_NONE); +} + static void node_shader_buts_ies(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) { uiLayout *row; @@ -1309,6 +1316,9 @@ static void node_shader_set_butfunc(bNodeType *ntype) case SH_NODE_BSDF_HAIR: ntype->draw_buttons = node_shader_buts_hair; break; + case SH_NODE_BSDF_HAIR_PRINCIPLED: + ntype->draw_buttons = node_shader_buts_principled_hair; + break; case SH_NODE_SCRIPT: ntype->draw_buttons = node_shader_buts_script; ntype->draw_buttons_ex = node_shader_buts_script_ex; @@ -2552,6 +2562,25 @@ static void node_composit_buts_sunbeams(uiLayout *layout, bContext *UNUSED(C), P uiItemR(layout, ptr, "ray_length", UI_ITEM_R_SLIDER, NULL, ICON_NONE); } +static void node_composit_buts_cryptomatte(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) +{ + uiLayout *col = uiLayoutColumn(layout, true); + + uiItemL(col, IFACE_("Matte Objects:"), ICON_NONE); + + uiLayout *row = uiLayoutRow(col, true); + uiTemplateCryptoPicker(row, ptr, "add"); + uiTemplateCryptoPicker(row, ptr, "remove"); + + uiItemR(col, ptr, "matte_id", 0, "", ICON_NONE); +} + +static void node_composit_buts_cryptomatte_ex(uiLayout *layout, bContext *UNUSED(C), PointerRNA *UNUSED(ptr)) +{ + uiItemO(layout, IFACE_("Add Crypto Layer"), ICON_ZOOMIN, "NODE_OT_cryptomatte_layer_add"); + uiItemO(layout, IFACE_("Remove Crypto Layer"), ICON_ZOOMOUT, "NODE_OT_cryptomatte_layer_remove"); +} + static void node_composit_buts_brightcontrast(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) { uiItemR(layout, ptr, "use_premultiply", 0, NULL, ICON_NONE); @@ -2784,6 +2813,10 @@ static void node_composit_set_butfunc(bNodeType *ntype) case CMP_NODE_SUNBEAMS: ntype->draw_buttons = node_composit_buts_sunbeams; break; + case CMP_NODE_CRYPTOMATTE: + ntype->draw_buttons = node_composit_buts_cryptomatte; + ntype->draw_buttons_ex = node_composit_buts_cryptomatte_ex; + break; case CMP_NODE_BRIGHTCONTRAST: ntype->draw_buttons = node_composit_buts_brightcontrast; } diff --git a/source/blender/editors/space_node/node_add.c b/source/blender/editors/space_node/node_add.c index 10dbda082804..3ae909041c2a 100644 --- a/source/blender/editors/space_node/node_add.c +++ b/source/blender/editors/space_node/node_add.c @@ -402,7 +402,7 @@ void NODE_OT_add_file(wmOperatorType *ot) /* ****************** Add Mask Node Operator ******************* */ -static int node_add_mask_poll(bContext *C) +static bool node_add_mask_poll(bContext *C) { SpaceNode *snode = CTX_wm_space_node(C); @@ -543,4 +543,3 @@ void NODE_OT_new_node_tree(wmOperatorType *ot) RNA_def_enum_funcs(prop, new_node_tree_type_itemf); RNA_def_string(ot->srna, "name", "NodeTree", MAX_ID_NAME - 2, "Name", ""); } - diff --git a/source/blender/editors/space_node/node_buttons.c b/source/blender/editors/space_node/node_buttons.c index 0a656ee1deb0..6104761eb499 100644 --- a/source/blender/editors/space_node/node_buttons.c +++ b/source/blender/editors/space_node/node_buttons.c @@ -59,7 +59,7 @@ #if 0 /* poll for active nodetree */ -static int active_nodetree_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool active_nodetree_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -67,7 +67,7 @@ static int active_nodetree_poll(const bContext *C, PanelType *UNUSED(pt)) } #endif -static int node_sockets_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool node_sockets_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -95,7 +95,7 @@ static void node_sockets_panel(const bContext *C, Panel *pa) } } -static int node_tree_interface_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool node_tree_interface_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -216,7 +216,7 @@ static int node_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) } /* non-standard poll operator which doesn't care if there are any nodes */ -static int node_properties_poll(bContext *C) +static bool node_properties_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); return (sa && (sa->spacetype == SPACE_NODE)); diff --git a/source/blender/editors/space_node/node_edit.c b/source/blender/editors/space_node/node_edit.c index 8d8593099a49..97c5157486dd 100644 --- a/source/blender/editors/space_node/node_edit.c +++ b/source/blender/editors/space_node/node_edit.c @@ -302,7 +302,7 @@ void ED_node_composite_job(const bContext *C, struct bNodeTree *nodetree, Scene /* ***************************************** */ /* operator poll callback */ -int composite_node_active(bContext *C) +bool composite_node_active(bContext *C) { if (ED_operator_node_active(C)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -313,7 +313,7 @@ int composite_node_active(bContext *C) } /* operator poll callback */ -int composite_node_editable(bContext *C) +bool composite_node_editable(bContext *C) { if (ED_operator_node_editable(C)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -748,7 +748,7 @@ void ED_node_post_apply_transform(bContext *UNUSED(C), bNodeTree *UNUSED(ntree)) #if 0 /* UNUSED */ -static int edit_node_poll(bContext *C) +static bool edit_node_poll(bContext *C) { return ED_operator_node_active(C); } @@ -1680,7 +1680,7 @@ void NODE_OT_delete(wmOperatorType *ot) /* ****************** Switch View ******************* */ -static int node_switch_view_poll(bContext *C) +static bool node_switch_view_poll(bContext *C) { SpaceNode *snode = CTX_wm_space_node(C); @@ -2353,7 +2353,7 @@ void NODE_OT_tree_socket_move(wmOperatorType *ot) /* ********************** Shader Script Update ******************/ -static int node_shader_script_update_poll(bContext *C) +static bool node_shader_script_update_poll(bContext *C) { Scene *scene = CTX_data_scene(C); RenderEngineType *type = RE_engines_find(scene->r.engine); @@ -2611,3 +2611,93 @@ void NODE_OT_clear_viewer_border(wmOperatorType *ot) /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } + +/* ****************** Cryptomatte Add Socket ******************* */ + +static int node_cryptomatte_add_socket_exec(bContext *C, wmOperator *UNUSED(op)) +{ + SpaceNode *snode = CTX_wm_space_node(C); + PointerRNA ptr = CTX_data_pointer_get(C, "node"); + bNodeTree *ntree = NULL; + bNode *node = NULL; + + if (ptr.data) { + node = ptr.data; + ntree = ptr.id.data; + } + else if (snode && snode->edittree) { + ntree = snode->edittree; + node = nodeGetActive(snode->edittree); + } + + if (!node || node->type != CMP_NODE_CRYPTOMATTE) { + return OPERATOR_CANCELLED; + } + + ntreeCompositCryptomatteAddSocket(ntree, node); + + snode_notify(C, snode); + + return OPERATOR_FINISHED; +} + +void NODE_OT_cryptomatte_layer_add(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Add Cryptomatte Socket"; + ot->description = "Add a new input layer to a Cryptomatte node"; + ot->idname = "NODE_OT_cryptomatte_layer_add"; + + /* callbacks */ + ot->exec = node_cryptomatte_add_socket_exec; + ot->poll = composite_node_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; +} + +/* ****************** Cryptomatte Remove Socket ******************* */ + +static int node_cryptomatte_remove_socket_exec(bContext *C, wmOperator *UNUSED(op)) +{ + SpaceNode *snode = CTX_wm_space_node(C); + PointerRNA ptr = CTX_data_pointer_get(C, "node"); + bNodeTree *ntree = NULL; + bNode *node = NULL; + + if (ptr.data) { + node = ptr.data; + ntree = ptr.id.data; + } + else if (snode && snode->edittree) { + ntree = snode->edittree; + node = nodeGetActive(snode->edittree); + } + + if (!node || node->type != CMP_NODE_CRYPTOMATTE) { + return OPERATOR_CANCELLED; + } + + if (!ntreeCompositCryptomatteRemoveSocket(ntree, node)) { + return OPERATOR_CANCELLED; + } + + snode_notify(C, snode); + + return OPERATOR_FINISHED; +} + +void NODE_OT_cryptomatte_layer_remove(wmOperatorType *ot) +{ + /* identifiers */ + ot->name = "Remove Cryptomatte Socket"; + ot->description = "Remove layer from a Crytpomatte node"; + ot->idname = "NODE_OT_cryptomatte_layer_remove"; + + /* callbacks */ + ot->exec = node_cryptomatte_remove_socket_exec; + ot->poll = composite_node_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; +} diff --git a/source/blender/editors/space_node/node_group.c b/source/blender/editors/space_node/node_group.c index 926fff7a3b6f..a3294211ff9d 100644 --- a/source/blender/editors/space_node/node_group.c +++ b/source/blender/editors/space_node/node_group.c @@ -65,7 +65,7 @@ #include "node_intern.h" /* own include */ #include "NOD_common.h" -static int node_group_operator_active(bContext *C) +static bool node_group_operator_active(bContext *C) { if (ED_operator_node_active(C)) { SpaceNode *snode = CTX_wm_space_node(C); @@ -84,7 +84,7 @@ static int node_group_operator_active(bContext *C) return false; } -static int node_group_operator_editable(bContext *C) +static bool node_group_operator_editable(bContext *C) { if (ED_operator_node_editable(C)) { SpaceNode *snode = CTX_wm_space_node(C); diff --git a/source/blender/editors/space_node/node_intern.h b/source/blender/editors/space_node/node_intern.h index 9bcbe94d2870..9b396aa9642b 100644 --- a/source/blender/editors/space_node/node_intern.h +++ b/source/blender/editors/space_node/node_intern.h @@ -179,8 +179,8 @@ void snode_dag_update(struct bContext *C, struct SpaceNode *snode); void snode_set_context(const struct bContext *C); void snode_update(struct SpaceNode *snode, struct bNode *node); -int composite_node_active(struct bContext *C); -int composite_node_editable(struct bContext *C); +bool composite_node_active(struct bContext *C); +bool composite_node_editable(struct bContext *C); int node_has_hidden_sockets(bNode *node); void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set); @@ -222,6 +222,9 @@ void NODE_OT_shader_script_update(struct wmOperatorType *ot); void NODE_OT_viewer_border(struct wmOperatorType *ot); void NODE_OT_clear_viewer_border(struct wmOperatorType *ot); +void NODE_OT_cryptomatte_layer_add(struct wmOperatorType *ot); +void NODE_OT_cryptomatte_layer_remove(struct wmOperatorType *ot); + extern const char *node_context_dir[]; // XXXXXX diff --git a/source/blender/editors/space_node/node_ops.c b/source/blender/editors/space_node/node_ops.c index d7ded62a988d..d4585c0835da 100644 --- a/source/blender/editors/space_node/node_ops.c +++ b/source/blender/editors/space_node/node_ops.c @@ -130,6 +130,9 @@ void node_operatortypes(void) WM_operatortype_append(NODE_OT_tree_socket_add); WM_operatortype_append(NODE_OT_tree_socket_remove); WM_operatortype_append(NODE_OT_tree_socket_move); + + WM_operatortype_append(NODE_OT_cryptomatte_layer_add); + WM_operatortype_append(NODE_OT_cryptomatte_layer_remove); } void ED_operatormacros_node(void) @@ -228,13 +231,13 @@ void node_keymap(struct wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* Entire Editor only ----------------- */ - keymap = WM_keymap_find(keyconf, "Node Generic", SPACE_NODE, 0); + keymap = WM_keymap_ensure(keyconf, "Node Generic", SPACE_NODE, 0); WM_keymap_add_item(keymap, "NODE_OT_properties", NKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "NODE_OT_toolbar", TKEY, KM_PRESS, 0, 0); /* Main Region only ----------------- */ - keymap = WM_keymap_find(keyconf, "Node Editor", SPACE_NODE, 0); + keymap = WM_keymap_ensure(keyconf, "Node Editor", SPACE_NODE, 0); /* mouse select in nodes used to be both keys, but perhaps this should be reduced? * NOTE: mouse-clicks on left-mouse will fall through to allow transform-tweak, but also link/resize diff --git a/source/blender/editors/space_node/node_select.c b/source/blender/editors/space_node/node_select.c index 3ae542c48db4..636ed755cb1d 100644 --- a/source/blender/editors/space_node/node_select.c +++ b/source/blender/editors/space_node/node_select.c @@ -1064,5 +1064,3 @@ void NODE_OT_find_node(wmOperatorType *ot) RNA_def_boolean(ot->srna, "prev", 0, "Previous", ""); } - - diff --git a/source/blender/editors/space_node/node_templates.c b/source/blender/editors/space_node/node_templates.c index bba21f7f5ebf..ef9ead3407c2 100644 --- a/source/blender/editors/space_node/node_templates.c +++ b/source/blender/editors/space_node/node_templates.c @@ -772,4 +772,3 @@ void uiTemplateNodeView(uiLayout *layout, bContext *C, bNodeTree *ntree, bNode * else ui_node_draw_node(layout, C, ntree, node, 0); } - diff --git a/source/blender/editors/space_node/node_toolbar.c b/source/blender/editors/space_node/node_toolbar.c index 21278dd9fa59..b4e7e853330d 100644 --- a/source/blender/editors/space_node/node_toolbar.c +++ b/source/blender/editors/space_node/node_toolbar.c @@ -63,7 +63,7 @@ static int node_toolbar_toggle_exec(bContext *C, wmOperator *UNUSED(op)) } /* non-standard poll operator which doesn't care if there are any nodes */ -static int node_toolbar_poll(bContext *C) +static bool node_toolbar_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); return (sa && (sa->spacetype == SPACE_NODE)); diff --git a/source/blender/editors/space_node/space_node.c b/source/blender/editors/space_node/space_node.c index c954ebad4c9e..ed228cdaf74a 100644 --- a/source/blender/editors/space_node/space_node.c +++ b/source/blender/editors/space_node/space_node.c @@ -593,7 +593,7 @@ static void node_buttons_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Node Generic", SPACE_NODE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Node Generic", SPACE_NODE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -609,7 +609,7 @@ static void node_toolbar_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "Node Generic", SPACE_NODE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Node Generic", SPACE_NODE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -644,10 +644,10 @@ static void node_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "Node Generic", SPACE_NODE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Node Generic", SPACE_NODE, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Node Editor", SPACE_NODE, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Node Editor", SPACE_NODE, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* add drop boxes */ @@ -664,7 +664,7 @@ static void node_main_region_draw(const bContext *C, ARegion *ar) /* ************* dropboxes ************* */ -static int node_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool node_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -678,7 +678,7 @@ static int node_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent * return 0; } -static int node_mask_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool node_mask_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -747,7 +747,6 @@ static void node_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegi break; case NC_SCREEN: switch (wmn->data) { - case ND_SCREENCAST: case ND_ANIMPLAY: ED_region_tag_redraw(ar); break; @@ -968,4 +967,3 @@ void ED_spacetype_node(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_outliner/outliner_edit.c b/source/blender/editors/space_outliner/outliner_edit.c index 7d5ff560b28b..3708b653ec42 100644 --- a/source/blender/editors/space_outliner/outliner_edit.c +++ b/source/blender/editors/space_outliner/outliner_edit.c @@ -161,7 +161,7 @@ static int do_outliner_item_openclose(bContext *C, SpaceOops *soops, TreeElement /* all below close/open? */ if (all) { tselem->flag &= ~TSE_CLOSED; - outliner_set_flag(&te->subtree, TSE_CLOSED, !outliner_has_one_flag(&te->subtree, TSE_CLOSED, 1)); + outliner_flag_set(&te->subtree, TSE_CLOSED, !outliner_flag_is_any_test(&te->subtree, TSE_CLOSED, 1)); } else { if (tselem->flag & TSE_CLOSED) tselem->flag &= ~TSE_CLOSED; @@ -435,7 +435,7 @@ static int outliner_id_remap_exec(bContext *C, wmOperator *op) DAG_scene_relations_rebuild(bmain, scene); /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */ - GPU_materials_free(); + GPU_materials_free(bmain); WM_event_add_notifier(C, NC_WINDOW, NULL); @@ -727,7 +727,7 @@ static int outliner_count_levels(ListBase *lb, const int curlevel) return level; } -int outliner_has_one_flag(ListBase *lb, short flag, const int curlevel) +int outliner_flag_is_any_test(ListBase *lb, short flag, const int curlevel) { TreeElement *te; TreeStoreElem *tselem; @@ -737,13 +737,13 @@ int outliner_has_one_flag(ListBase *lb, short flag, const int curlevel) tselem = TREESTORE(te); if (tselem->flag & flag) return curlevel; - level = outliner_has_one_flag(&te->subtree, flag, curlevel + 1); + level = outliner_flag_is_any_test(&te->subtree, flag, curlevel + 1); if (level) return level; } return 0; } -void outliner_set_flag(ListBase *lb, short flag, short set) +void outliner_flag_set(ListBase *lb, short flag, short set) { TreeElement *te; TreeStoreElem *tselem; @@ -752,7 +752,7 @@ void outliner_set_flag(ListBase *lb, short flag, short set) tselem = TREESTORE(te); if (set == 0) tselem->flag &= ~flag; else tselem->flag |= flag; - outliner_set_flag(&te->subtree, flag, set); + outliner_flag_set(&te->subtree, flag, set); } } @@ -965,10 +965,10 @@ static int outliner_toggle_expanded_exec(bContext *C, wmOperator *UNUSED(op)) SpaceOops *soops = CTX_wm_space_outliner(C); ARegion *ar = CTX_wm_region(C); - if (outliner_has_one_flag(&soops->tree, TSE_CLOSED, 1)) - outliner_set_flag(&soops->tree, TSE_CLOSED, 0); + if (outliner_flag_is_any_test(&soops->tree, TSE_CLOSED, 1)) + outliner_flag_set(&soops->tree, TSE_CLOSED, 0); else - outliner_set_flag(&soops->tree, TSE_CLOSED, 1); + outliner_flag_set(&soops->tree, TSE_CLOSED, 1); ED_region_tag_redraw(ar); @@ -997,10 +997,10 @@ static int outliner_toggle_selected_exec(bContext *C, wmOperator *UNUSED(op)) ARegion *ar = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); - if (outliner_has_one_flag(&soops->tree, TSE_SELECTED, 1)) - outliner_set_flag(&soops->tree, TSE_SELECTED, 0); + if (outliner_flag_is_any_test(&soops->tree, TSE_SELECTED, 1)) + outliner_flag_set(&soops->tree, TSE_SELECTED, 0); else - outliner_set_flag(&soops->tree, TSE_SELECTED, 1); + outliner_flag_set(&soops->tree, TSE_SELECTED, 1); soops->storeflag |= SO_TREESTORE_REDRAW; @@ -1265,7 +1265,7 @@ static void outliner_find_panel(Scene *UNUSED(scene), ARegion *ar, SpaceOops *so outliner_set_coordinates(ar, soops); /* deselect all visible, and select found element */ - outliner_set_flag(soops, &soops->tree, TSE_SELECTED, 0); + outliner_flag_set(soops, &soops->tree, TSE_SELECTED, 0); tselem->flag |= TSE_SELECTED; /* make te->ys center of view */ @@ -1325,7 +1325,7 @@ static int outliner_one_level_exec(bContext *C, wmOperator *op) const bool add = RNA_boolean_get(op->ptr, "open"); int level; - level = outliner_has_one_flag(&soops->tree, TSE_CLOSED, 1); + level = outliner_flag_is_any_test(&soops->tree, TSE_CLOSED, 1); if (add == 1) { if (level) outliner_openclose_level(&soops->tree, 1, level, 1); } @@ -1439,7 +1439,7 @@ void OUTLINER_OT_show_hierarchy(wmOperatorType *ot) /* KeyingSet and Driver Creation - Helper functions */ /* specialized poll callback for these operators to work in Datablocks view only */ -static int ed_operator_outliner_datablocks_active(bContext *C) +static bool ed_operator_outliner_datablocks_active(bContext *C) { ScrArea *sa = CTX_wm_area(C); if ((sa) && (sa->spacetype == SPACE_OUTLINER)) { @@ -1927,7 +1927,7 @@ void OUTLINER_OT_keyingset_remove_selected(wmOperatorType *ot) /* ************************************************************** */ /* ORPHANED DATABLOCKS */ -static int ed_operator_outliner_id_orphans_active(bContext *C) +static bool ed_operator_outliner_id_orphans_active(bContext *C) { ScrArea *sa = CTX_wm_area(C); if ((sa) && (sa->spacetype == SPACE_OUTLINER)) { @@ -2164,7 +2164,7 @@ void OUTLINER_OT_parent_drop(wmOperatorType *ot) RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", ""); } -static int outliner_parenting_poll(bContext *C) +static bool outliner_parenting_poll(bContext *C) { SpaceOops *soops = CTX_wm_space_outliner(C); diff --git a/source/blender/editors/space_outliner/outliner_intern.h b/source/blender/editors/space_outliner/outliner_intern.h index 9bf2231b3130..49647a0d838c 100644 --- a/source/blender/editors/space_outliner/outliner_intern.h +++ b/source/blender/editors/space_outliner/outliner_intern.h @@ -172,8 +172,8 @@ void outliner_do_object_operation( int common_restrict_check(struct bContext *C, struct Object *ob); -int outliner_has_one_flag(ListBase *lb, short flag, const int curlevel); -void outliner_set_flag(ListBase *lb, short flag, short set); +int outliner_flag_is_any_test(ListBase *lb, short flag, const int curlevel); +void outliner_flag_set(ListBase *lb, short flag, short set); void object_toggle_visibility_cb( struct bContext *C, struct ReportList *reports, struct Scene *scene, diff --git a/source/blender/editors/space_outliner/outliner_ops.c b/source/blender/editors/space_outliner/outliner_ops.c index ad2b8008db60..16cd383b5c2a 100644 --- a/source/blender/editors/space_outliner/outliner_ops.c +++ b/source/blender/editors/space_outliner/outliner_ops.c @@ -91,7 +91,7 @@ void outliner_operatortypes(void) void outliner_keymap(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Outliner", SPACE_OUTLINER, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Outliner", SPACE_OUTLINER, 0); wmKeyMapItem *kmi; WM_keymap_add_item(keymap, "OUTLINER_OT_item_rename", LEFTMOUSE, KM_DBL_CLICK, 0, 0); @@ -155,4 +155,3 @@ void outliner_keymap(wmKeyConfig *keyconf) WM_keymap_verify_item(keymap, "OUTLINER_OT_drivers_add_selected", DKEY, KM_PRESS, 0, 0); WM_keymap_verify_item(keymap, "OUTLINER_OT_drivers_delete_selected", DKEY, KM_PRESS, KM_ALT, 0); } - diff --git a/source/blender/editors/space_outliner/outliner_select.c b/source/blender/editors/space_outliner/outliner_select.c index 5149715740f2..e40ba8670496 100644 --- a/source/blender/editors/space_outliner/outliner_select.c +++ b/source/blender/editors/space_outliner/outliner_select.c @@ -988,7 +988,7 @@ static bool do_outliner_item_activate_from_cursor( /* all below close/open? */ if (extend) { tselem->flag &= ~TSE_CLOSED; - outliner_set_flag(&te->subtree, TSE_CLOSED, !outliner_has_one_flag(&te->subtree, TSE_CLOSED, 1)); + outliner_flag_set(&te->subtree, TSE_CLOSED, !outliner_flag_is_any_test(&te->subtree, TSE_CLOSED, 1)); } else { if (tselem->flag & TSE_CLOSED) tselem->flag &= ~TSE_CLOSED; diff --git a/source/blender/editors/space_outliner/outliner_tools.c b/source/blender/editors/space_outliner/outliner_tools.c index 75151325bdf0..2707e1305981 100644 --- a/source/blender/editors/space_outliner/outliner_tools.c +++ b/source/blender/editors/space_outliner/outliner_tools.c @@ -1860,8 +1860,8 @@ static int do_outliner_operation_event(bContext *C, ARegion *ar, SpaceOops *soop /* select object that's clicked on and popup context menu */ if (!(tselem->flag & TSE_SELECTED)) { - if (outliner_has_one_flag(&soops->tree, TSE_SELECTED, 1)) - outliner_set_flag(&soops->tree, TSE_SELECTED, 0); + if (outliner_flag_is_any_test(&soops->tree, TSE_SELECTED, 1)) + outliner_flag_set(&soops->tree, TSE_SELECTED, 0); tselem->flag |= TSE_SELECTED; /* redraw, same as outliner_select function */ diff --git a/source/blender/editors/space_outliner/outliner_tree.c b/source/blender/editors/space_outliner/outliner_tree.c index b54a77056867..173b48cc731c 100644 --- a/source/blender/editors/space_outliner/outliner_tree.c +++ b/source/blender/editors/space_outliner/outliner_tree.c @@ -1844,5 +1844,3 @@ void outliner_build_tree(Main *mainvar, Scene *scene, SpaceOops *soops) BKE_main_id_clear_newpoins(mainvar); } - - diff --git a/source/blender/editors/space_outliner/space_outliner.c b/source/blender/editors/space_outliner/space_outliner.c index 0cf4fd09555b..c10399278105 100644 --- a/source/blender/editors/space_outliner/space_outliner.c +++ b/source/blender/editors/space_outliner/space_outliner.c @@ -81,7 +81,7 @@ static void outliner_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_LIST, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Outliner", SPACE_OUTLINER, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Outliner", SPACE_OUTLINER, 0); /* don't pass on view2d mask, it's always set with scrollbar space, hide fails */ WM_event_add_keymap_handler_bb(&ar->handlers, keymap, NULL, &ar->winrct); @@ -90,7 +90,7 @@ static void outliner_main_region_init(wmWindowManager *wm, ARegion *ar) WM_event_add_dropbox_handler(&ar->handlers, lb); } -static int outliner_parent_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool outliner_parent_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); SpaceOops *soops = CTX_wm_space_outliner(C); @@ -134,7 +134,7 @@ static void outliner_parent_drop_copy(wmDrag *drag, wmDropBox *drop) RNA_string_set(drop->ptr, "child", id->name + 2); } -static int outliner_parent_clear_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool outliner_parent_clear_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); SpaceOops *soops = CTX_wm_space_outliner(C); @@ -180,7 +180,7 @@ static void outliner_parent_clear_copy(wmDrag *drag, wmDropBox *drop) RNA_enum_set(drop->ptr, "type", 0); } -static int outliner_scene_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool outliner_scene_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); SpaceOops *soops = CTX_wm_space_outliner(C); @@ -205,7 +205,7 @@ static void outliner_scene_drop_copy(wmDrag *drag, wmDropBox *drop) RNA_string_set(drop->ptr, "object", id->name + 2); } -static int outliner_material_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool outliner_material_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); SpaceOops *soops = CTX_wm_space_outliner(C); @@ -230,7 +230,7 @@ static void outliner_material_drop_copy(wmDrag *drag, wmDropBox *drop) RNA_string_set(drop->ptr, "material", id->name + 2); } -static int outliner_group_link_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool outliner_group_link_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); SpaceOops *soops = CTX_wm_space_outliner(C); @@ -563,4 +563,3 @@ void ED_spacetype_outliner(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_script/script_intern.h b/source/blender/editors/space_script/script_intern.h index a3fcbb34e7ed..0e0936cf082f 100644 --- a/source/blender/editors/space_script/script_intern.h +++ b/source/blender/editors/space_script/script_intern.h @@ -43,4 +43,3 @@ void SCRIPT_OT_python_file_run(struct wmOperatorType *ot); void SCRIPT_OT_autoexec_warn_clear(struct wmOperatorType *ot); #endif /* __SCRIPT_INTERN_H__ */ - diff --git a/source/blender/editors/space_script/space_script.c b/source/blender/editors/space_script/space_script.c index cd77e3032f15..2adfcc521f59 100644 --- a/source/blender/editors/space_script/space_script.c +++ b/source/blender/editors/space_script/space_script.c @@ -132,7 +132,7 @@ static void script_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_STANDARD, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Script", SPACE_SCRIPT, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Script", SPACE_SCRIPT, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -223,4 +223,3 @@ void ED_spacetype_script(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_sequencer/sequencer_add.c b/source/blender/editors/space_sequencer/sequencer_add.c index 5c3329250113..b3e1d3be42a2 100644 --- a/source/blender/editors/space_sequencer/sequencer_add.c +++ b/source/blender/editors/space_sequencer/sequencer_add.c @@ -627,7 +627,7 @@ static void sequencer_add_cancel(bContext *UNUSED(C), wmOperator *op) op->customdata = NULL; } -static bool sequencer_add_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop) +static bool sequencer_add_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *prop, void *UNUSED(user_data)) { const char *prop_id = RNA_property_identifier(prop); @@ -693,7 +693,7 @@ static void sequencer_add_draw(bContext *UNUSED(C), wmOperator *op) /* main draw call */ RNA_pointer_create(NULL, op->type->srna, op->properties, &ptr); - uiDefAutoButsRNA(layout, &ptr, sequencer_add_draw_check_prop, '\0'); + uiDefAutoButsRNA(layout, &ptr, sequencer_add_draw_check_prop, NULL, '\0'); /* image template */ RNA_pointer_create(NULL, &RNA_ImageFormatSettings, imf, &imf_ptr); diff --git a/source/blender/editors/space_sequencer/sequencer_buttons.c b/source/blender/editors/space_sequencer/sequencer_buttons.c index 72f78d4f466a..a4bca5554901 100644 --- a/source/blender/editors/space_sequencer/sequencer_buttons.c +++ b/source/blender/editors/space_sequencer/sequencer_buttons.c @@ -52,7 +52,7 @@ /* **************************** buttons ********************************* */ #if 0 -static int sequencer_grease_pencil_panel_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool sequencer_grease_pencil_panel_poll(const bContext *C, PanelType *UNUSED(pt)) { SpaceSeq *sseq = CTX_wm_space_seq(C); @@ -102,4 +102,3 @@ void SEQUENCER_OT_properties(wmOperatorType *ot) /* flags */ ot->flag = 0; } - diff --git a/source/blender/editors/space_sequencer/sequencer_draw.c b/source/blender/editors/space_sequencer/sequencer_draw.c index 7c32895afb4c..915e2466d545 100644 --- a/source/blender/editors/space_sequencer/sequencer_draw.c +++ b/source/blender/editors/space_sequencer/sequencer_draw.c @@ -220,9 +220,9 @@ static void drawseqwave(const bContext *C, SpaceSeq *sseq, Scene *scene, Sequenc BLI_spin_lock(sound->spinlock); if (!sound->waveform) { - if (!(sound->flags & SOUND_FLAGS_WAVEFORM_LOADING)) { + if (!(sound->tags & SOUND_TAGS_WAVEFORM_LOADING)) { /* prevent sounds from reloading */ - sound->flags |= SOUND_FLAGS_WAVEFORM_LOADING; + sound->tags |= SOUND_TAGS_WAVEFORM_LOADING; BLI_spin_unlock(sound->spinlock); sequencer_preview_add_sound(C, seq); } @@ -1700,5 +1700,3 @@ void draw_timeline_seq(const bContext *C, ARegion *ar) UI_view2d_scrollers_draw(C, v2d, scrollers); UI_view2d_scrollers_free(scrollers); } - - diff --git a/source/blender/editors/space_sequencer/sequencer_edit.c b/source/blender/editors/space_sequencer/sequencer_edit.c index e93a18449b0a..5b8f2ae70678 100644 --- a/source/blender/editors/space_sequencer/sequencer_edit.c +++ b/source/blender/editors/space_sequencer/sequencer_edit.c @@ -474,7 +474,7 @@ void recurs_sel_seq(Sequence *seqm) } } -int ED_space_sequencer_maskedit_mask_poll(bContext *C) +bool ED_space_sequencer_maskedit_mask_poll(bContext *C) { /* in this case both funcs are the same, for clip editor not */ return ED_space_sequencer_maskedit_poll(C); @@ -489,7 +489,7 @@ bool ED_space_sequencer_check_show_maskedit(SpaceSeq *sseq, Scene *scene) return false; } -int ED_space_sequencer_maskedit_poll(bContext *C) +bool ED_space_sequencer_maskedit_poll(bContext *C) { SpaceSeq *sseq = CTX_wm_space_seq(C); @@ -737,7 +737,7 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe) if (!skip_dup) { /* Duplicate AFTER the first change */ - seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM); + seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_ANIM); } if (seqn) { @@ -846,7 +846,7 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe) if (!skip_dup) { /* Duplicate AFTER the first change */ - seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM); + seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_ANIM); } if (seqn) { @@ -1147,27 +1147,27 @@ static int seq_get_snaplimit(View2D *v2d) #endif /* Operator functions */ -int sequencer_edit_poll(bContext *C) +bool sequencer_edit_poll(bContext *C) { return (BKE_sequencer_editing_get(CTX_data_scene(C), false) != NULL); } #if 0 /* UNUSED */ -int sequencer_strip_poll(bContext *C) +bool sequencer_strip_poll(bContext *C) { Editing *ed; return (((ed = BKE_sequencer_editing_get(CTX_data_scene(C), false)) != NULL) && (ed->act_seq != NULL)); } #endif -int sequencer_strip_has_path_poll(bContext *C) +bool sequencer_strip_has_path_poll(bContext *C) { Editing *ed; Sequence *seq; return (((ed = BKE_sequencer_editing_get(CTX_data_scene(C), false)) != NULL) && ((seq = ed->act_seq) != NULL) && (SEQ_HAS_PATH(seq))); } -int sequencer_view_preview_poll(bContext *C) +bool sequencer_view_preview_poll(bContext *C) { SpaceSeq *sseq = CTX_wm_space_seq(C); Editing *ed = BKE_sequencer_editing_get(CTX_data_scene(C), false); @@ -1177,7 +1177,7 @@ int sequencer_view_preview_poll(bContext *C) return 0; } -int sequencer_view_strips_poll(bContext *C) +bool sequencer_view_strips_poll(bContext *C) { SpaceSeq *sseq = CTX_wm_space_seq(C); if (sseq && ED_space_sequencer_check_show_strip(sseq)) @@ -1935,7 +1935,7 @@ void SEQUENCER_OT_reload(struct wmOperatorType *ot) } /* reload operator */ -static int sequencer_refresh_all_poll(bContext *C) +static bool sequencer_refresh_all_poll(bContext *C) { if (G.is_rendering) { return 0; @@ -1997,7 +1997,7 @@ static int sequencer_reassign_inputs_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int sequencer_effect_poll(bContext *C) +static bool sequencer_effect_poll(bContext *C) { Scene *scene = CTX_data_scene(C); Editing *ed = BKE_sequencer_editing_get(scene, false); @@ -2112,6 +2112,7 @@ static int sequencer_cut_exec(bContext *C, wmOperator *op) SEQP_BEGIN (ed, seq) { + BKE_sequence_base_unique_name_recursive(&ed->seqbase, seq); if (seq->seq1 || seq->seq2 || seq->seq3) { BKE_sequence_calc(scene, seq); } @@ -2991,7 +2992,7 @@ static bool strip_jump_internal(Scene *scene, return changed; } -static int sequencer_strip_jump_poll(bContext *C) +static bool sequencer_strip_jump_poll(bContext *C) { /* prevent changes during render */ if (G.is_rendering) @@ -3894,7 +3895,7 @@ static int sequencer_export_subtitles_invoke(bContext *C, wmOperator *op, const else BLI_strncpy(filepath, BKE_main_blendfile_path(bmain), sizeof(filepath)); - BLI_replace_extension(filepath, sizeof(filepath), ".srt"); + BLI_path_extension_replace(filepath, sizeof(filepath), ".srt"); RNA_string_set(op->ptr, "filepath", filepath); } @@ -3919,7 +3920,7 @@ static int sequencer_export_subtitles_exec(bContext *C, wmOperator *op) } RNA_string_get(op->ptr, "filepath", filepath); - BLI_ensure_extension(filepath, sizeof(filepath), ".srt"); + BLI_path_extension_ensure(filepath, sizeof(filepath), ".srt"); /* Avoid File write exceptions */ if (!BLI_exists(filepath)) { @@ -3973,7 +3974,7 @@ static int sequencer_export_subtitles_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int sequencer_strip_is_text_poll(bContext *C) +static bool sequencer_strip_is_text_poll(bContext *C) { Editing *ed; Sequence *seq; diff --git a/source/blender/editors/space_sequencer/sequencer_intern.h b/source/blender/editors/space_sequencer/sequencer_intern.h index 713aa8994b3f..e06f4558f00a 100644 --- a/source/blender/editors/space_sequencer/sequencer_intern.h +++ b/source/blender/editors/space_sequencer/sequencer_intern.h @@ -76,12 +76,12 @@ void recurs_sel_seq(struct Sequence *seqm); int seq_effect_find_selected(struct Scene *scene, struct Sequence *activeseq, int type, struct Sequence **selseq1, struct Sequence **selseq2, struct Sequence **selseq3, const char **error_str); /* operator helpers */ -int sequencer_edit_poll(struct bContext *C); +bool sequencer_edit_poll(struct bContext *C); /* UNUSED */ -//int sequencer_strip_poll(struct bContext *C); -int sequencer_strip_has_path_poll(struct bContext *C); -int sequencer_view_preview_poll(struct bContext *C); -int sequencer_view_strips_poll(struct bContext *C); +//bool sequencer_strip_poll(struct bContext *C); +bool sequencer_strip_has_path_poll(struct bContext *C); +bool sequencer_view_preview_poll(struct bContext *C); +bool sequencer_view_strips_poll(struct bContext *C); /* externs */ extern EnumPropertyItem sequencer_prop_effect_types[]; @@ -213,4 +213,3 @@ int sequencer_image_seq_get_minmax_frame(struct wmOperator *op, int sfra, int *r void sequencer_image_seq_reserve_frames(struct wmOperator *op, struct StripElem *se, int len, int minframe, int numdigits); #endif /* __SEQUENCER_INTERN_H__ */ - diff --git a/source/blender/editors/space_sequencer/sequencer_modifier.c b/source/blender/editors/space_sequencer/sequencer_modifier.c index 7ab9308f9a67..3c4481b32cbf 100644 --- a/source/blender/editors/space_sequencer/sequencer_modifier.c +++ b/source/blender/editors/space_sequencer/sequencer_modifier.c @@ -50,7 +50,7 @@ /*********************** Add modifier operator *************************/ -static int strip_modifier_active_poll(bContext *C) +static bool strip_modifier_active_poll(bContext *C) { Scene *scene = CTX_data_scene(C); Editing *ed = BKE_sequencer_editing_get(scene, false); @@ -281,4 +281,3 @@ void SEQUENCER_OT_strip_modifier_copy(wmOperatorType *ot) /* properties */ ot->prop = RNA_def_enum(ot->srna, "type", type_items, SEQ_MODIFIER_COPY_REPLACE, "Type", ""); } - diff --git a/source/blender/editors/space_sequencer/sequencer_ops.c b/source/blender/editors/space_sequencer/sequencer_ops.c index 234989ef2448..408dc551382f 100644 --- a/source/blender/editors/space_sequencer/sequencer_ops.c +++ b/source/blender/editors/space_sequencer/sequencer_ops.c @@ -137,7 +137,7 @@ void sequencer_keymap(wmKeyConfig *keyconf) wmKeyMapItem *kmi; /* Common items ------------------------------------------------------------------ */ - keymap = WM_keymap_find(keyconf, "SequencerCommon", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(keyconf, "SequencerCommon", SPACE_SEQ, 0); WM_keymap_add_item(keymap, "SEQUENCER_OT_properties", NKEY, KM_PRESS, 0, 0); @@ -148,7 +148,7 @@ void sequencer_keymap(wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "SEQUENCER_OT_view_toggle", TABKEY, KM_PRESS, KM_CTRL, 0); /* Strips Region --------------------------------------------------------------- */ - keymap = WM_keymap_find(keyconf, "Sequencer", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(keyconf, "Sequencer", SPACE_SEQ, 0); kmi = WM_keymap_add_item(keymap, "SEQUENCER_OT_select_all", AKEY, KM_PRESS, 0, 0); RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE); @@ -340,7 +340,7 @@ void sequencer_keymap(wmKeyConfig *keyconf) /* Preview Region ----------------------------------------------------------- */ - keymap = WM_keymap_find(keyconf, "SequencerPreview", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(keyconf, "SequencerPreview", SPACE_SEQ, 0); WM_keymap_add_item(keymap, "SEQUENCER_OT_view_all_preview", HOMEKEY, KM_PRESS, 0, 0); #ifdef WITH_INPUT_NDOF WM_keymap_add_item(keymap, "SEQUENCER_OT_view_all_preview", NDOF_BUTTON_FIT, KM_PRESS, 0, 0); diff --git a/source/blender/editors/space_sequencer/sequencer_preview.c b/source/blender/editors/space_sequencer/sequencer_preview.c index c58c05b67c09..ae011e48538d 100644 --- a/source/blender/editors/space_sequencer/sequencer_preview.c +++ b/source/blender/editors/space_sequencer/sequencer_preview.c @@ -96,7 +96,7 @@ static void preview_startjob(void *data, short *stop, short *do_update, float *p /* make sure we cleanup the loading flag! */ BLI_spin_lock(sound->spinlock); - sound->flags &= ~SOUND_FLAGS_WAVEFORM_LOADING; + sound->tags &= ~SOUND_TAGS_WAVEFORM_LOADING; BLI_spin_unlock(sound->spinlock); BLI_mutex_lock(pj->mutex); diff --git a/source/blender/editors/space_sequencer/sequencer_select.c b/source/blender/editors/space_sequencer/sequencer_select.c index d7206a6da4ea..88ad2cad3e90 100644 --- a/source/blender/editors/space_sequencer/sequencer_select.c +++ b/source/blender/editors/space_sequencer/sequencer_select.c @@ -1282,4 +1282,3 @@ void SEQUENCER_OT_select_grouped(wmOperatorType *ot) RNA_def_boolean(ot->srna, "use_active_channel", false, "Same Channel", "Only consider strips on the same channel as the active one"); } - diff --git a/source/blender/editors/space_sequencer/sequencer_view.c b/source/blender/editors/space_sequencer/sequencer_view.c index 4acda8799cb0..daf9af7db4b2 100644 --- a/source/blender/editors/space_sequencer/sequencer_view.c +++ b/source/blender/editors/space_sequencer/sequencer_view.c @@ -219,7 +219,7 @@ static void sample_cancel(bContext *C, wmOperator *op) sample_exit(C, op); } -static int sample_poll(bContext *C) +static bool sample_poll(bContext *C) { SpaceSeq *sseq = CTX_wm_space_seq(C); return sseq && BKE_sequencer_editing_get(CTX_data_scene(C), false) != NULL; diff --git a/source/blender/editors/space_sequencer/space_sequencer.c b/source/blender/editors/space_sequencer/space_sequencer.c index 47c134d02e13..ebeeef191918 100644 --- a/source/blender/editors/space_sequencer/space_sequencer.c +++ b/source/blender/editors/space_sequencer/space_sequencer.c @@ -370,7 +370,7 @@ static void sequencer_listener(bScreen *UNUSED(sc), ScrArea *sa, wmNotifier *wmn /* ************* dropboxes ************* */ -static int image_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool image_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); @@ -384,7 +384,7 @@ static int image_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) return 0; } -static int movie_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool movie_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); @@ -397,7 +397,7 @@ static int movie_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) return 0; } -static int sound_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool sound_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { ARegion *ar = CTX_wm_region(C); Scene *scene = CTX_data_scene(C); @@ -475,15 +475,15 @@ static void sequencer_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); #if 0 - keymap = WM_keymap_find(wm->defaultconf, "Mask Editing", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); #endif - keymap = WM_keymap_find(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Sequencer", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Sequencer", SPACE_SEQ, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* add drop boxes */ @@ -530,7 +530,7 @@ static void sequencer_main_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED( ED_region_tag_redraw(ar); break; case NC_SCREEN: - if (ELEM(wmn->data, ND_SCREENCAST, ND_ANIMPLAY)) + if (ELEM(wmn->data, ND_ANIMPLAY)) ED_region_tag_redraw(ar); break; } @@ -556,15 +556,15 @@ static void sequencer_preview_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); #if 0 - keymap = WM_keymap_find(wm->defaultconf, "Mask Editing", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Mask Editing", 0, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); #endif - keymap = WM_keymap_find(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "SequencerPreview", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "SequencerPreview", SPACE_SEQ, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -659,7 +659,7 @@ static void sequencer_buttons_region_init(wmWindowManager *wm, ARegion *ar) { wmKeyMap *keymap; - keymap = WM_keymap_find(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "SequencerCommon", SPACE_SEQ, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); ED_region_panels_init(wm, ar); diff --git a/source/blender/editors/space_text/space_text.c b/source/blender/editors/space_text/space_text.c index 84ab4a36d305..20402a82ff44 100644 --- a/source/blender/editors/space_text/space_text.c +++ b/source/blender/editors/space_text/space_text.c @@ -243,7 +243,7 @@ static void text_keymap(struct wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "Text Generic", SPACE_TEXT, 0); + keymap = WM_keymap_ensure(keyconf, "Text Generic", SPACE_TEXT, 0); WM_keymap_add_item(keymap, "TEXT_OT_start_find", FKEY, KM_PRESS, KM_CTRL, 0); #ifdef __APPLE__ WM_keymap_add_item(keymap, "TEXT_OT_start_find", FKEY, KM_PRESS, KM_OSKEY, 0); @@ -253,7 +253,7 @@ static void text_keymap(struct wmKeyConfig *keyconf) WM_keymap_add_item(keymap, "TEXT_OT_replace", HKEY, KM_PRESS, KM_CTRL, 0); WM_keymap_add_item(keymap, "TEXT_OT_properties", TKEY, KM_PRESS, KM_CTRL, 0); - keymap = WM_keymap_find(keyconf, "Text", SPACE_TEXT, 0); + keymap = WM_keymap_ensure(keyconf, "Text", SPACE_TEXT, 0); #ifdef __APPLE__ RNA_enum_set(WM_keymap_add_item(keymap, "TEXT_OT_move", LEFTARROWKEY, KM_PRESS, KM_OSKEY, 0)->ptr, "type", LINE_BEGIN); @@ -422,9 +422,9 @@ static void text_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_STANDARD, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Text Generic", SPACE_TEXT, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Text Generic", SPACE_TEXT, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); - keymap = WM_keymap_find(wm->defaultconf, "Text", SPACE_TEXT, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Text", SPACE_TEXT, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); /* add drop boxes */ @@ -470,7 +470,7 @@ static void text_cursor(wmWindow *win, ScrArea *sa, ARegion *ar) /* ************* dropboxes ************* */ -static int text_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool text_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_PATH) { /* rule might not work? */ @@ -487,7 +487,7 @@ static void text_drop_copy(wmDrag *drag, wmDropBox *drop) RNA_string_set(drop->ptr, "filepath", drag->path); } -static int text_drop_paste_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool text_drop_paste_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) return true; @@ -542,7 +542,7 @@ static void text_properties_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "Text Generic", SPACE_TEXT, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Text Generic", SPACE_TEXT, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } @@ -641,4 +641,3 @@ void ED_spacetype_text(void) ED_text_format_register_pov_ini(); ED_text_format_register_glsl(); } - diff --git a/source/blender/editors/space_text/text_autocomplete.c b/source/blender/editors/space_text/text_autocomplete.c index 9163831c333b..4f6a3bc82bac 100644 --- a/source/blender/editors/space_text/text_autocomplete.c +++ b/source/blender/editors/space_text/text_autocomplete.c @@ -40,7 +40,10 @@ #include "WM_api.h" #include "WM_types.h" +#include "ED_text.h" +#include "ED_undo.h" #include "ED_screen.h" + #include "UI_interface.h" #include "text_format.h" @@ -284,10 +287,11 @@ static int text_autocomplete_invoke(bContext *C, wmOperator *op, const wmEvent * ED_area_tag_redraw(CTX_wm_area(C)); if (texttool_suggest_first() == texttool_suggest_last()) { - TextUndoBuf *utxt = NULL; // FIXME + TextUndoBuf *utxt = ED_text_undo_push_init(C); confirm_suggestion(st->text, utxt); text_update_line_edited(st->text->curl); text_autocomplete_free(C, op); + ED_undo_push(C, op->type->name); return OPERATOR_FINISHED; } else { @@ -315,8 +319,6 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e (void)text; - TextUndoBuf *utxt = NULL; // FIXME - if (st->doplugins && texttool_text_is_active(st->text)) { if (texttool_suggest_first()) tools |= TOOL_SUGG_LIST; if (texttool_docs_get()) tools |= TOOL_DOCUMENT; @@ -343,8 +345,10 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e case MIDDLEMOUSE: if (event->val == KM_PRESS) { if (text_do_suggest_select(st, ar)) { + TextUndoBuf *utxt = ED_text_undo_push_init(C); confirm_suggestion(st->text, utxt); text_update_line_edited(st->text->curl); + ED_undo_push(C, op->type->name); swallow = 1; } else { @@ -378,8 +382,10 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e case PADENTER: if (event->val == KM_PRESS) { if (tools & TOOL_SUGG_LIST) { + TextUndoBuf *utxt = ED_text_undo_push_init(C); confirm_suggestion(st->text, utxt); text_update_line_edited(st->text->curl); + ED_undo_push(C, op->type->name); swallow = 1; draw = 1; } @@ -591,5 +597,6 @@ void TEXT_OT_autocomplete(wmOperatorType *ot) ot->poll = text_space_edit_poll; /* flags */ + /* Undo is handled conditionally by this operator. */ ot->flag = OPTYPE_BLOCKING; } diff --git a/source/blender/editors/space_text/text_header.c b/source/blender/editors/space_text/text_header.c index 50a8739c5b4b..f9bfa45c23a6 100644 --- a/source/blender/editors/space_text/text_header.c +++ b/source/blender/editors/space_text/text_header.c @@ -72,7 +72,7 @@ static ARegion *text_has_properties_region(ScrArea *sa) return arnew; } -static int text_properties_poll(bContext *C) +static bool text_properties_poll(bContext *C) { return (CTX_wm_space_text(C) != NULL); } @@ -212,4 +212,3 @@ void TEXT_OT_start_find(wmOperatorType *ot) UI_popup_menu_end(C, pup); } #endif - diff --git a/source/blender/editors/space_text/text_intern.h b/source/blender/editors/space_text/text_intern.h index bc902135b50d..02948d356234 100644 --- a/source/blender/editors/space_text/text_intern.h +++ b/source/blender/editors/space_text/text_intern.h @@ -142,7 +142,7 @@ void TEXT_OT_to_3d_object(struct wmOperatorType *ot); void TEXT_OT_resolve_conflict(struct wmOperatorType *ot); -int text_space_edit_poll(struct bContext *C); +bool text_space_edit_poll(struct bContext *C); /* text_autocomplete.c */ void TEXT_OT_autocomplete(struct wmOperatorType *ot); @@ -151,4 +151,3 @@ void TEXT_OT_autocomplete(struct wmOperatorType *ot); extern const char *text_context_dir[]; /* doc access */ #endif /* __TEXT_INTERN_H__ */ - diff --git a/source/blender/editors/space_text/text_ops.c b/source/blender/editors/space_text/text_ops.c index d896c6a1d9ad..91da2d8b6edc 100644 --- a/source/blender/editors/space_text/text_ops.c +++ b/source/blender/editors/space_text/text_ops.c @@ -80,12 +80,12 @@ BLI_INLINE int text_pixel_x_to_column(SpaceText *st, const int x) return (x + (st->cwidth / 2)) / st->cwidth; } -static int text_new_poll(bContext *UNUSED(C)) +static bool text_new_poll(bContext *UNUSED(C)) { return 1; } -static int text_edit_poll(bContext *C) +static bool text_edit_poll(bContext *C) { Text *text = CTX_data_edit_text(C); @@ -100,7 +100,7 @@ static int text_edit_poll(bContext *C) return 1; } -int text_space_edit_poll(bContext *C) +bool text_space_edit_poll(bContext *C) { SpaceText *st = CTX_wm_space_text(C); Text *text = CTX_data_edit_text(C); @@ -116,7 +116,7 @@ int text_space_edit_poll(bContext *C) return 1; } -static int text_region_edit_poll(bContext *C) +static bool text_region_edit_poll(bContext *C) { SpaceText *st = CTX_wm_space_text(C); Text *text = CTX_data_edit_text(C); @@ -361,7 +361,7 @@ void TEXT_OT_reload(wmOperatorType *ot) /******************* delete operator *********************/ -static int text_unlink_poll(bContext *C) +static bool text_unlink_poll(bContext *C) { /* it should be possible to unlink texts if they're lib-linked in... */ return CTX_data_edit_text(C) != NULL; @@ -447,7 +447,7 @@ void TEXT_OT_make_internal(wmOperatorType *ot) /******************* save operator *********************/ -static int text_save_poll(bContext *C) +static bool text_save_poll(bContext *C) { Text *text = CTX_data_edit_text(C); @@ -590,7 +590,7 @@ void TEXT_OT_save_as(wmOperatorType *ot) /******************* run script operator *********************/ -static int text_run_script_poll(bContext *C) +static bool text_run_script_poll(bContext *C) { return (CTX_data_edit_text(C) != NULL); } @@ -2146,7 +2146,7 @@ typedef struct TextScroll { int zone; } TextScroll; -static int text_scroll_poll(bContext *C) +static bool text_scroll_poll(bContext *C) { /* it should be possible to still scroll linked texts to read them, even if they can't be edited... */ return CTX_data_edit_text(C) != NULL; @@ -2329,7 +2329,7 @@ void TEXT_OT_scroll(wmOperatorType *ot) /******************** scroll bar operator *******************/ -static int text_region_scroll_poll(bContext *C) +static bool text_region_scroll_poll(bContext *C) { /* same as text_region_edit_poll except it works on libdata too */ SpaceText *st = CTX_wm_space_text(C); diff --git a/source/blender/editors/space_time/space_time.c b/source/blender/editors/space_time/space_time.c index 97daed53e242..e3fe124a5c42 100644 --- a/source/blender/editors/space_time/space_time.c +++ b/source/blender/editors/space_time/space_time.c @@ -562,7 +562,7 @@ static void time_main_region_init(wmWindowManager *wm, ARegion *ar) UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); /* own keymap */ - keymap = WM_keymap_find(wm->defaultconf, "Timeline", SPACE_TIME, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Timeline", SPACE_TIME, 0); WM_event_add_keymap_handler_bb(&ar->handlers, keymap, &ar->v2d.mask, &ar->winrct); } diff --git a/source/blender/editors/space_time/time_intern.h b/source/blender/editors/space_time/time_intern.h index 3d2bc18c334f..67e33afabb61 100644 --- a/source/blender/editors/space_time/time_intern.h +++ b/source/blender/editors/space_time/time_intern.h @@ -40,4 +40,3 @@ void time_operatortypes(void); void time_keymap(struct wmKeyConfig *keyconf); #endif /* __TIME_INTERN_H__ */ - diff --git a/source/blender/editors/space_time/time_ops.c b/source/blender/editors/space_time/time_ops.c index 85e8ca110ef7..a68bd2a9fbb8 100644 --- a/source/blender/editors/space_time/time_ops.c +++ b/source/blender/editors/space_time/time_ops.c @@ -214,7 +214,7 @@ void time_operatortypes(void) void time_keymap(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Timeline", SPACE_TIME, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Timeline", SPACE_TIME, 0); WM_keymap_add_item(keymap, "TIME_OT_start_frame_set", SKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "TIME_OT_end_frame_set", EKEY, KM_PRESS, 0, 0); @@ -224,4 +224,3 @@ void time_keymap(wmKeyConfig *keyconf) #endif WM_keymap_add_item(keymap, "TIME_OT_view_frame", PAD0, KM_PRESS, 0, 0); } - diff --git a/source/blender/editors/space_userpref/space_userpref.c b/source/blender/editors/space_userpref/space_userpref.c index 209b32f45f31..bf3f1d0dfb3e 100644 --- a/source/blender/editors/space_userpref/space_userpref.c +++ b/source/blender/editors/space_userpref/space_userpref.c @@ -192,4 +192,3 @@ void ED_spacetype_userpref(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_userpref/userpref_intern.h b/source/blender/editors/space_userpref/userpref_intern.h index d67ba32f68b6..720b4da0f710 100644 --- a/source/blender/editors/space_userpref/userpref_intern.h +++ b/source/blender/editors/space_userpref/userpref_intern.h @@ -34,4 +34,3 @@ /* internal exports only */ #endif /* __USERPREF_INTERN_H__ */ - diff --git a/source/blender/editors/space_userpref/userpref_ops.c b/source/blender/editors/space_userpref/userpref_ops.c index c5a62f46c362..6666a6cfc166 100644 --- a/source/blender/editors/space_userpref/userpref_ops.c +++ b/source/blender/editors/space_userpref/userpref_ops.c @@ -31,5 +31,3 @@ #include #include - - diff --git a/source/blender/editors/space_view3d/drawmesh.c b/source/blender/editors/space_view3d/drawmesh.c index dcf2c55b0672..c388d6af8d1c 100644 --- a/source/blender/editors/space_view3d/drawmesh.c +++ b/source/blender/editors/space_view3d/drawmesh.c @@ -1253,4 +1253,3 @@ void draw_mesh_paint(View3D *v3d, RegionView3D *rv3d, } } } - diff --git a/source/blender/editors/space_view3d/space_view3d.c b/source/blender/editors/space_view3d/space_view3d.c index 35682e70f60a..9fafa91fcac9 100644 --- a/source/blender/editors/space_view3d/space_view3d.c +++ b/source/blender/editors/space_view3d/space_view3d.c @@ -485,74 +485,74 @@ static void view3d_main_region_init(wmWindowManager *wm, ARegion *ar) /* object ops. */ /* important to be before Pose keymap since they can both be enabled at once */ - keymap = WM_keymap_find(wm->defaultconf, "Face Mask", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Face Mask", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Weight Paint Vertex Selection", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Weight Paint Vertex Selection", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); /* pose is not modal, operator poll checks for this */ - keymap = WM_keymap_find(wm->defaultconf, "Pose", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Pose", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Object Mode", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Object Mode", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Paint Curve", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Paint Curve", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Curve", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Curve", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Image Paint", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Image Paint", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Vertex Paint", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Vertex Paint", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Weight Paint", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Weight Paint", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Sculpt", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Sculpt", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Mesh", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Mesh", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Curve", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Curve", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Armature", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Armature", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Pose", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Pose", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Metaball", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Metaball", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Lattice", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Lattice", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Particle", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Particle", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); /* editfont keymap swallows all... */ - keymap = WM_keymap_find(wm->defaultconf, "Font", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Font", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Object Non-modal", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Object Non-modal", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Frames", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Frames", 0, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); /* own keymap, last so modes can override it */ - keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "3D View", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "3D View", SPACE_VIEW3D, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); /* add drop boxes */ @@ -579,7 +579,7 @@ static void view3d_main_region_exit(wmWindowManager *wm, ARegion *ar) } } -static int view3d_ob_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool view3d_ob_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -589,7 +589,7 @@ static int view3d_ob_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent return 0; } -static int view3d_group_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool view3d_group_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -599,7 +599,7 @@ static int view3d_group_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEve return 0; } -static int view3d_mat_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool view3d_mat_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -609,7 +609,7 @@ static int view3d_mat_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent return 0; } -static int view3d_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) +static bool view3d_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event)) { if (drag->type == WM_DRAG_ID) { ID *id = drag->poin; @@ -623,7 +623,7 @@ static int view3d_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent return 0; } -static int view3d_ima_bg_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool view3d_ima_bg_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { if (event->ctrl) return false; @@ -634,7 +634,7 @@ static int view3d_ima_bg_drop_poll(bContext *C, wmDrag *drag, const wmEvent *eve return 0; } -static int view3d_ima_empty_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool view3d_ima_empty_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { Base *base = ED_view3d_give_base_under_cursor(C, event->mval); @@ -648,7 +648,7 @@ static int view3d_ima_empty_drop_poll(bContext *C, wmDrag *drag, const wmEvent * return 0; } -static int view3d_ima_mesh_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) +static bool view3d_ima_mesh_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event) { Base *base = ED_view3d_give_base_under_cursor(C, event->mval); @@ -1034,7 +1034,7 @@ static void view3d_main_region_cursor(wmWindow *win, ScrArea *UNUSED(sa), ARegio /* add handlers, stuff you only do once or on area/region changes */ static void view3d_header_region_init(wmWindowManager *wm, ARegion *ar) { - wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); + wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); @@ -1083,7 +1083,7 @@ static void view3d_buttons_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -1189,7 +1189,7 @@ static void view3d_tools_region_init(wmWindowManager *wm, ARegion *ar) ED_region_panels_init(wm, ar); - keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0); WM_event_add_keymap_handler(&ar->handlers, keymap); } @@ -1236,7 +1236,7 @@ static void space_view3d_listener(bScreen *UNUSED(sc), ScrArea *sa, struct wmNot switch (wmn->data) { case ND_WORLD_DRAW: case ND_WORLD: - if (v3d->flag3 & V3D_SHOW_WORLD) + if (v3d->flag2 & V3D_SHOW_WORLD) ED_area_tag_redraw_regiontype(sa, RGN_TYPE_WINDOW); break; } @@ -1528,4 +1528,3 @@ void ED_spacetype_view3d(void) BKE_spacetype_register(st); } - diff --git a/source/blender/editors/space_view3d/view3d_buttons.c b/source/blender/editors/space_view3d/view3d_buttons.c index fbbc5bd7bb9c..63786e87b1f3 100644 --- a/source/blender/editors/space_view3d/view3d_buttons.c +++ b/source/blender/editors/space_view3d/view3d_buttons.c @@ -784,7 +784,7 @@ static void do_view3d_vgroup_buttons(bContext *C, void *UNUSED(arg), int event) } } -static int view3d_panel_vgroup_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool view3d_panel_vgroup_poll(const bContext *C, PanelType *UNUSED(pt)) { Scene *scene = CTX_data_scene(C); Object *ob = OBACT; @@ -1117,7 +1117,7 @@ static void do_view3d_region_buttons(bContext *C, void *UNUSED(index), int event WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d); } -static int view3d_panel_transform_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool view3d_panel_transform_poll(const bContext *C, PanelType *UNUSED(pt)) { Scene *scene = CTX_data_scene(C); return (scene->basact != NULL); diff --git a/source/blender/editors/space_view3d/view3d_draw.c b/source/blender/editors/space_view3d/view3d_draw.c index 5a03fa99f477..caa4d2c0136f 100644 --- a/source/blender/editors/space_view3d/view3d_draw.c +++ b/source/blender/editors/space_view3d/view3d_draw.c @@ -2695,7 +2695,7 @@ static void gpu_update_lamps_shadows_world(Main *bmain, Scene *scene, View3D *v3 /* update world values */ if (world) { - GPU_mist_update_enable(world->mode & WO_MIST && v3d->flag3 & V3D_SHOW_MIST); + GPU_mist_update_enable(world->mode & WO_MIST && v3d->flag2 & V3D_SHOW_MIST); GPU_mist_update_values(world->mistype, world->miststa, world->mistdist, world->misi, &world->horr); GPU_horizon_update_color(&world->horr); GPU_ambient_update_color(&world->ambr); @@ -3032,7 +3032,7 @@ static void view3d_draw_objects( } if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) { - GPU_free_images_old(); + GPU_free_images_old(bmain); } } @@ -3102,7 +3102,7 @@ void ED_view3d_draw_offscreen_init(Main *bmain, Scene *scene, View3D *v3d) */ static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar) { - if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) { + if (scene->world && (v3d->flag2 & V3D_SHOW_WORLD)) { RegionView3D *rv3d = ar->regiondata; GPUMaterial *gpumat = GPU_material_world(scene, scene->world); @@ -3217,7 +3217,7 @@ void ED_view3d_draw_offscreen( if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) { /* free images which can have changed on frame-change * warning! can be slow so only free animated images - campbell */ - GPU_free_images_anim(); + GPU_free_images_anim(bmain); } /* setup view matrices before fx or unbinding the offscreen buffers will cause issues */ @@ -3271,7 +3271,7 @@ void ED_view3d_draw_offscreen( } /* freeing the images again here could be done after the operator runs, leaving for now */ - GPU_free_images_anim(); + GPU_free_images_anim(bmain); } /* restore size */ @@ -3508,7 +3508,7 @@ ImBuf *ED_view3d_draw_offscreen_imbuf_simple( v3d.flag2 |= V3D_SOLID_TEX; } if (draw_flags & V3D_OFSDRAW_USE_BACKGROUND) { - v3d.flag3 |= V3D_SHOW_WORLD; + v3d.flag2 |= V3D_SHOW_WORLD; } if (draw_flags & V3D_OFSDRAW_USE_CAMERA_DOF) { if (camera->type == OB_CAMERA) { diff --git a/source/blender/editors/space_view3d/view3d_edit.c b/source/blender/editors/space_view3d/view3d_edit.c index 54d56dff903a..b02e4ad97648 100644 --- a/source/blender/editors/space_view3d/view3d_edit.c +++ b/source/blender/editors/space_view3d/view3d_edit.c @@ -555,8 +555,8 @@ void viewrotate_modal_keymap(wmKeyConfig *keyconf) static const EnumPropertyItem modal_items[] = { {VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""}, - {VIEWROT_MODAL_AXIS_SNAP_ENABLE, "AXIS_SNAP_ENABLE", 0, "Enable Axis Snap", ""}, - {VIEWROT_MODAL_AXIS_SNAP_DISABLE, "AXIS_SNAP_DISABLE", 0, "Disable Axis Snap", ""}, + {VIEWROT_MODAL_AXIS_SNAP_ENABLE, "AXIS_SNAP_ENABLE", 0, "Axis Snap", ""}, + {VIEWROT_MODAL_AXIS_SNAP_DISABLE, "AXIS_SNAP_DISABLE", 0, "Axis Snap (Off)", ""}, {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"}, {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"}, @@ -928,7 +928,7 @@ static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event) } /* test for unlocked camera view in quad view */ -static int view3d_camera_user_poll(bContext *C) +static bool view3d_camera_user_poll(bContext *C) { View3D *v3d; ARegion *ar; @@ -943,7 +943,7 @@ static int view3d_camera_user_poll(bContext *C) return 0; } -static int view3d_lock_poll(bContext *C) +static bool view3d_lock_poll(bContext *C) { View3D *v3d = CTX_wm_view3d(C); if (v3d) { @@ -1797,7 +1797,7 @@ static void view_zoom_to_window_xy_camera( { RegionView3D *rv3d = ar->regiondata; const float zoomfac = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom); - const float zoomfac_new = CLAMPIS(zoomfac * (1.0f / dfac), RV3D_CAMZOOM_MIN_FACTOR, RV3D_CAMZOOM_MAX_FACTOR); + const float zoomfac_new = clamp_f(zoomfac * (1.0f / dfac), RV3D_CAMZOOM_MIN_FACTOR, RV3D_CAMZOOM_MAX_FACTOR); const float camzoom_new = BKE_screen_view3d_zoom_from_fac(zoomfac_new); @@ -4529,7 +4529,7 @@ void VIEW3D_OT_clip_border(wmOperatorType *ot) /* cursor position in vec, result in vec, mval in region coords */ /* note: cannot use event->mval here (called by object_add() */ -void ED_view3d_cursor3d_position(bContext *C, float fp[3], const int mval[2]) +void ED_view3d_cursor3d_position(bContext *C, const int mval[2], float cursor_co[3]) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); @@ -4544,25 +4544,25 @@ void ED_view3d_cursor3d_position(bContext *C, float fp[3], const int mval[2]) if (rv3d == NULL) return; - ED_view3d_calc_zfac(rv3d, fp, &flip); + ED_view3d_calc_zfac(rv3d, cursor_co, &flip); /* reset the depth based on the view offset (we _know_ the offset is infront of us) */ if (flip) { - negate_v3_v3(fp, rv3d->ofs); + negate_v3_v3(cursor_co, rv3d->ofs); /* re initialize, no need to check flip again */ - ED_view3d_calc_zfac(rv3d, fp, NULL /* &flip */ ); + ED_view3d_calc_zfac(rv3d, cursor_co, NULL /* &flip */ ); } if (U.uiflag & USER_DEPTH_CURSOR) { /* maybe this should be accessed some other way */ view3d_operator_needs_opengl(C); - if (ED_view3d_autodist(bmain, scene, ar, v3d, mval, fp, true, NULL)) + if (ED_view3d_autodist(bmain, scene, ar, v3d, mval, cursor_co, true, NULL)) depth_used = true; } if (depth_used == false) { float depth_pt[3]; - copy_v3_v3(depth_pt, fp); - ED_view3d_win_to_3d_int(v3d, ar, depth_pt, mval, fp); + copy_v3_v3(depth_pt, cursor_co); + ED_view3d_win_to_3d_int(v3d, ar, depth_pt, mval, cursor_co); } } @@ -4571,12 +4571,12 @@ void ED_view3d_cursor3d_update(bContext *C, const int mval[2]) Scene *scene = CTX_data_scene(C); View3D *v3d = CTX_wm_view3d(C); - float *fp_curr = ED_view3d_cursor3d_get(scene, v3d); - float fp_prev[3]; + float *cursor_co_curr = ED_view3d_cursor3d_get(scene, v3d); + float cursor_co_prev[3]; - copy_v3_v3(fp_prev, fp_curr); + copy_v3_v3(cursor_co_prev, cursor_co_curr); - ED_view3d_cursor3d_position(C, fp_curr, mval); + ED_view3d_cursor3d_position(C, mval, cursor_co_curr); /* offset the cursor lock to avoid jumping to new offset */ if (v3d->ob_centre_cursor) { @@ -4585,13 +4585,15 @@ void ED_view3d_cursor3d_update(bContext *C, const int mval[2]) if (U.uiflag & USER_LOCK_CURSOR_ADJUST) { - float co_curr[2], co_prev[2]; + float co_2d_curr[2], co_2d_prev[2]; - if ((ED_view3d_project_float_global(ar, fp_prev, co_prev, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) && - (ED_view3d_project_float_global(ar, fp_curr, co_curr, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK)) + if ((ED_view3d_project_float_global( + ar, cursor_co_prev, co_2d_prev, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) && + (ED_view3d_project_float_global( + ar, cursor_co_curr, co_2d_curr, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK)) { - rv3d->ofs_lock[0] += (co_curr[0] - co_prev[0]) / (ar->winx * 0.5f); - rv3d->ofs_lock[1] += (co_curr[1] - co_prev[1]) / (ar->winy * 0.5f); + rv3d->ofs_lock[0] += (co_2d_curr[0] - co_2d_prev[0]) / (ar->winx * 0.5f); + rv3d->ofs_lock[1] += (co_2d_curr[1] - co_2d_prev[1]) / (ar->winy * 0.5f); } } else { diff --git a/source/blender/editors/space_view3d/view3d_fly.c b/source/blender/editors/space_view3d/view3d_fly.c index 65d66df4824f..c68b5e97414a 100644 --- a/source/blender/editors/space_view3d/view3d_fly.c +++ b/source/blender/editors/space_view3d/view3d_fly.c @@ -98,29 +98,30 @@ typedef enum eFlyPanState { void fly_modal_keymap(wmKeyConfig *keyconf) { static const EnumPropertyItem modal_items[] = { - {FLY_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, {FLY_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""}, - {FLY_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""}, - {FLY_MODAL_DECELERATE, "DECELERATE", 0, "Decelerate", ""}, + {FLY_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, - {FLY_MODAL_PAN_ENABLE, "PAN_ENABLE", 0, "Pan Enable", ""}, - {FLY_MODAL_PAN_DISABLE, "PAN_DISABLE", 0, "Pan Disable", ""}, + {FLY_MODAL_DIR_FORWARD, "FORWARD", 0, "Forward", ""}, + {FLY_MODAL_DIR_BACKWARD, "BACKWARD", 0, "Backward", ""}, + {FLY_MODAL_DIR_LEFT, "LEFT", 0, "Left", ""}, + {FLY_MODAL_DIR_RIGHT, "RIGHT", 0, "Right", ""}, + {FLY_MODAL_DIR_UP, "UP", 0, "Up", ""}, + {FLY_MODAL_DIR_DOWN, "DOWN", 0, "Down", ""}, - {FLY_MODAL_DIR_FORWARD, "FORWARD", 0, "Fly Forward", ""}, - {FLY_MODAL_DIR_BACKWARD, "BACKWARD", 0, "Fly Backward", ""}, - {FLY_MODAL_DIR_LEFT, "LEFT", 0, "Fly Left", ""}, - {FLY_MODAL_DIR_RIGHT, "RIGHT", 0, "Fly Right", ""}, - {FLY_MODAL_DIR_UP, "UP", 0, "Fly Up", ""}, - {FLY_MODAL_DIR_DOWN, "DOWN", 0, "Fly Down", ""}, + {FLY_MODAL_PAN_ENABLE, "PAN_ENABLE", 0, "Pan", ""}, + {FLY_MODAL_PAN_DISABLE, "PAN_DISABLE", 0, "Pan (Off)", ""}, + + {FLY_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""}, + {FLY_MODAL_DECELERATE, "DECELERATE", 0, "Decelerate", ""}, {FLY_MODAL_AXIS_LOCK_X, "AXIS_LOCK_X", 0, "X Axis Correction", "X axis correction (toggle)"}, {FLY_MODAL_AXIS_LOCK_Z, "AXIS_LOCK_Z", 0, "X Axis Correction", "Z axis correction (toggle)"}, - {FLY_MODAL_PRECISION_ENABLE, "PRECISION_ENABLE", 0, "Precision Enable", ""}, - {FLY_MODAL_PRECISION_DISABLE, "PRECISION_DISABLE", 0, "Precision Disable", ""}, + {FLY_MODAL_PRECISION_ENABLE, "PRECISION_ENABLE", 0, "Precision", ""}, + {FLY_MODAL_PRECISION_DISABLE, "PRECISION_DISABLE", 0, "Precision (Off)", ""}, - {FLY_MODAL_FREELOOK_ENABLE, "FREELOOK_ENABLE", 0, "Rotation Enable", ""}, - {FLY_MODAL_FREELOOK_DISABLE, "FREELOOK_DISABLE", 0, "Rotation Disable", ""}, + {FLY_MODAL_FREELOOK_ENABLE, "FREELOOK_ENABLE", 0, "Rotation", ""}, + {FLY_MODAL_FREELOOK_DISABLE, "FREELOOK_DISABLE", 0, "Rotation (Off)", ""}, {0, NULL, 0, NULL, NULL}}; @@ -133,8 +134,8 @@ void fly_modal_keymap(wmKeyConfig *keyconf) keymap = WM_modalkeymap_add(keyconf, "View3D Fly Modal", modal_items); /* items for modal map */ - WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, FLY_MODAL_CANCEL); WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_ANY, KM_ANY, 0, FLY_MODAL_CANCEL); + WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, FLY_MODAL_CANCEL); WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_ANY, KM_ANY, 0, FLY_MODAL_CONFIRM); WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, FLY_MODAL_CONFIRM); diff --git a/source/blender/editors/space_view3d/view3d_header.c b/source/blender/editors/space_view3d/view3d_header.c index 124bd33f2272..27dda99e7150 100644 --- a/source/blender/editors/space_view3d/view3d_header.c +++ b/source/blender/editors/space_view3d/view3d_header.c @@ -200,7 +200,7 @@ static int view3d_layers_invoke(bContext *C, wmOperator *op, const wmEvent *even return OPERATOR_FINISHED; } -static int view3d_layers_poll(bContext *C) +static bool view3d_layers_poll(bContext *C) { return (ED_operator_view3d_active(C) && CTX_wm_view3d(C)->localvd == NULL); } diff --git a/source/blender/editors/space_view3d/view3d_intern.h b/source/blender/editors/space_view3d/view3d_intern.h index cfcded70fc9f..be444ce27cdb 100644 --- a/source/blender/editors/space_view3d/view3d_intern.h +++ b/source/blender/editors/space_view3d/view3d_intern.h @@ -328,4 +328,3 @@ extern bool view3d_camera_border_hack_test; #endif #endif /* __VIEW3D_INTERN_H__ */ - diff --git a/source/blender/editors/space_view3d/view3d_ops.c b/source/blender/editors/space_view3d/view3d_ops.c index 5734fba84b5a..5d662282e56a 100644 --- a/source/blender/editors/space_view3d/view3d_ops.c +++ b/source/blender/editors/space_view3d/view3d_ops.c @@ -232,13 +232,13 @@ void view3d_keymap(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "3D View Generic", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(keyconf, "3D View Generic", SPACE_VIEW3D, 0); WM_keymap_add_item(keymap, "VIEW3D_OT_properties", NKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "VIEW3D_OT_toolshelf", TKEY, KM_PRESS, 0, 0); /* only for region 3D window */ - keymap = WM_keymap_find(keyconf, "3D View", SPACE_VIEW3D, 0); + keymap = WM_keymap_ensure(keyconf, "3D View", SPACE_VIEW3D, 0); /* Shift+LMB behavior first, so it has priority over KM_ANY item below. */ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0); @@ -558,4 +558,3 @@ void view3d_keymap(wmKeyConfig *keyconf) viewzoom_modal_keymap(keyconf); viewdolly_modal_keymap(keyconf); } - diff --git a/source/blender/editors/space_view3d/view3d_select.c b/source/blender/editors/space_view3d/view3d_select.c index c3a8374d82e3..d8c21da48a44 100644 --- a/source/blender/editors/space_view3d/view3d_select.c +++ b/source/blender/editors/space_view3d/view3d_select.c @@ -269,7 +269,7 @@ static void view3d_userdata_lassoselect_init( r_data->is_changed = false; } -static int view3d_selectable_data(bContext *C) +static bool view3d_selectable_data(bContext *C) { Object *ob = CTX_data_active_object(C); @@ -2495,7 +2495,7 @@ static void paint_vertsel_circle_select(ViewContext *vc, const bool select, cons meshobject_foreachScreenVert(vc, paint_vertsel_circle_select_doSelectVert, &data, V3D_PROJ_TEST_CLIP_DEFAULT); } - if (select != LEFTMOUSE) { + if (select == false) { BKE_mesh_mselect_validate(me); } paintvert_flush_flags(ob); diff --git a/source/blender/editors/space_view3d/view3d_toolbar.c b/source/blender/editors/space_view3d/view3d_toolbar.c index e7ae0d39a2bc..02136af958bb 100644 --- a/source/blender/editors/space_view3d/view3d_toolbar.c +++ b/source/blender/editors/space_view3d/view3d_toolbar.c @@ -67,7 +67,7 @@ static void view3d_panel_operator_redo_buts(const bContext *C, Panel *pa, wmOperator *op) { - uiTemplateOperatorPropertyButs(C, pa->layout, op, NULL, 'V', 0); + uiTemplateOperatorPropertyButs(C, pa->layout, op, 'V', 0); } static void view3d_panel_operator_redo_header(const bContext *C, Panel *pa) @@ -277,4 +277,3 @@ void VIEW3D_OT_toolshelf(wmOperatorType *ot) /* flags */ ot->flag = 0; } - diff --git a/source/blender/editors/space_view3d/view3d_view.c b/source/blender/editors/space_view3d/view3d_view.c index cff3e0644475..7dc087b30af4 100644 --- a/source/blender/editors/space_view3d/view3d_view.c +++ b/source/blender/editors/space_view3d/view3d_view.c @@ -460,7 +460,7 @@ static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op)) } -static int view3d_camera_to_view_poll(bContext *C) +static bool view3d_camera_to_view_poll(bContext *C) { View3D *v3d; ARegion *ar; @@ -658,7 +658,7 @@ static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -int ED_operator_rv3d_user_region_poll(bContext *C) +bool ED_operator_rv3d_user_region_poll(bContext *C) { View3D *v3d_dummy; ARegion *ar_dummy; @@ -1007,7 +1007,7 @@ static unsigned int free_localbit(Main *bmain) return 0; } -int ED_view3d_scene_layer_set(int lay, const int *values, int *active) +int ED_view3d_scene_layer_set(int lay, const bool *values, int *active) { int i, tot = 0; @@ -1319,12 +1319,13 @@ void VIEW3D_OT_localview(wmOperatorType *ot) static ListBase queue_back; static void game_engine_save_state(bContext *C, wmWindow *win) { + Main *bmain = CTX_data_main(C); Object *obact = CTX_data_active_object(C); glPushAttrib(GL_ALL_ATTRIB_BITS); if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) - GPU_paint_set_mipmap(1); + GPU_paint_set_mipmap(bmain, 1); queue_back = win->queue; @@ -1333,10 +1334,11 @@ static void game_engine_save_state(bContext *C, wmWindow *win) static void game_engine_restore_state(bContext *C, wmWindow *win) { + Main *bmain = CTX_data_main(C); Object *obact = CTX_data_active_object(C); if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) - GPU_paint_set_mipmap(0); + GPU_paint_set_mipmap(bmain, 0); /* check because closing win can set to NULL */ if (win) { @@ -1358,7 +1360,7 @@ static void game_set_commmandline_options(GameData *gm) if ((syshandle = SYS_GetSystem())) { /* User defined settings */ test = (U.gameflags & USER_DISABLE_MIPMAP); - GPU_set_mipmap(!test); + GPU_set_mipmap(G_MAIN, !test); SYS_WriteCommandLineInt(syshandle, "nomipmap", test); /* File specific settings: */ @@ -1392,7 +1394,7 @@ static void game_set_commmandline_options(GameData *gm) #endif /* WITH_GAMEENGINE */ -static int game_engine_poll(bContext *C) +static bool game_engine_poll(bContext *C) { bScreen *screen; /* we need a context and area to launch BGE diff --git a/source/blender/editors/space_view3d/view3d_walk.c b/source/blender/editors/space_view3d/view3d_walk.c index f780ca35f30d..97c00f1be378 100644 --- a/source/blender/editors/space_view3d/view3d_walk.c +++ b/source/blender/editors/space_view3d/view3d_walk.c @@ -129,18 +129,15 @@ typedef enum eWalkGravityState { void walk_modal_keymap(wmKeyConfig *keyconf) { static const EnumPropertyItem modal_items[] = { - {WALK_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, {WALK_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""}, + {WALK_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, - {WALK_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""}, - {WALK_MODAL_DECELERATE, "DECELERATE", 0, "Decelerate", ""}, - - {WALK_MODAL_DIR_FORWARD, "FORWARD", 0, "Move Forward", ""}, - {WALK_MODAL_DIR_BACKWARD, "BACKWARD", 0, "Move Backward", ""}, - {WALK_MODAL_DIR_LEFT, "LEFT", 0, "Move Left (Strafe)", ""}, - {WALK_MODAL_DIR_RIGHT, "RIGHT", 0, "Move Right (Strafe)", ""}, - {WALK_MODAL_DIR_UP, "UP", 0, "Move Up", ""}, - {WALK_MODAL_DIR_DOWN, "DOWN", 0, "Move Down", ""}, + {WALK_MODAL_DIR_FORWARD, "FORWARD", 0, "Forward", ""}, + {WALK_MODAL_DIR_BACKWARD, "BACKWARD", 0, "Backward", ""}, + {WALK_MODAL_DIR_LEFT, "LEFT", 0, "Left (Strafe)", ""}, + {WALK_MODAL_DIR_RIGHT, "RIGHT", 0, "Right (Strafe)", ""}, + {WALK_MODAL_DIR_UP, "UP", 0, "Up", ""}, + {WALK_MODAL_DIR_DOWN, "DOWN", 0, "Down", ""}, {WALK_MODAL_DIR_FORWARD_STOP, "FORWARD_STOP", 0, "Stop Move Forward", ""}, {WALK_MODAL_DIR_BACKWARD_STOP, "BACKWARD_STOP", 0, "Stop Mode Backward", ""}, @@ -151,14 +148,17 @@ void walk_modal_keymap(wmKeyConfig *keyconf) {WALK_MODAL_TELEPORT, "TELEPORT", 0, "Teleport", "Move forward a few units at once"}, - {WALK_MODAL_FAST_ENABLE, "FAST_ENABLE", 0, "Fast Enable", "Move faster (walk or fly)"}, - {WALK_MODAL_FAST_DISABLE, "FAST_DISABLE", 0, "Fast Disable", "Resume regular speed"}, + {WALK_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""}, + {WALK_MODAL_DECELERATE, "DECELERATE", 0, "Decelerate", ""}, + + {WALK_MODAL_FAST_ENABLE, "FAST_ENABLE", 0, "Fast", "Move faster (walk or fly)"}, + {WALK_MODAL_FAST_DISABLE, "FAST_DISABLE", 0, "Fast (Off)", "Resume regular speed"}, - {WALK_MODAL_SLOW_ENABLE, "SLOW_ENABLE", 0, "Slow Enable", "Move slower (walk or fly)"}, - {WALK_MODAL_SLOW_DISABLE, "SLOW_DISABLE", 0, "Slow Disable", "Resume regular speed"}, + {WALK_MODAL_SLOW_ENABLE, "SLOW_ENABLE", 0, "Slow", "Move slower (walk or fly)"}, + {WALK_MODAL_SLOW_DISABLE, "SLOW_DISABLE", 0, "Slow (Off)", "Resume regular speed"}, {WALK_MODAL_JUMP, "JUMP", 0, "Jump", "Jump when in walk mode"}, - {WALK_MODAL_JUMP_STOP, "JUMP_STOP", 0, "Jump Stop", "Stop pushing jump"}, + {WALK_MODAL_JUMP_STOP, "JUMP_STOP", 0, "Jump (Off)", "Stop pushing jump"}, {WALK_MODAL_TOGGLE, "GRAVITY_TOGGLE", 0, "Toggle Gravity", "Toggle gravity effect"}, @@ -173,8 +173,8 @@ void walk_modal_keymap(wmKeyConfig *keyconf) keymap = WM_modalkeymap_add(keyconf, "View3D Walk Modal", modal_items); /* items for modal map */ - WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, WALK_MODAL_CANCEL); WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_ANY, KM_ANY, 0, WALK_MODAL_CANCEL); + WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, WALK_MODAL_CANCEL); WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_ANY, KM_ANY, 0, WALK_MODAL_CONFIRM); WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, WALK_MODAL_CONFIRM); diff --git a/source/blender/editors/transform/transform.c b/source/blender/editors/transform/transform.c index ac9b2f2900c8..79d06de8b41a 100644 --- a/source/blender/editors/transform/transform.c +++ b/source/blender/editors/transform/transform.c @@ -802,21 +802,18 @@ enum { wmKeyMap *transform_modal_keymap(wmKeyConfig *keyconf) { static const EnumPropertyItem modal_items[] = { - {TFM_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, {TFM_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""}, - {TFM_MODAL_TRANSLATE, "TRANSLATE", 0, "Translate", ""}, - {TFM_MODAL_ROTATE, "ROTATE", 0, "Rotate", ""}, - {TFM_MODAL_RESIZE, "RESIZE", 0, "Resize", ""}, - {TFM_MODAL_SNAP_INV_ON, "SNAP_INV_ON", 0, "Invert Snap On", ""}, - {TFM_MODAL_SNAP_INV_OFF, "SNAP_INV_OFF", 0, "Invert Snap Off", ""}, + {TFM_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, + {TFM_MODAL_AXIS_X, "AXIS_X", 0, "X axis", ""}, + {TFM_MODAL_AXIS_Y, "AXIS_Y", 0, "Y axis", ""}, + {TFM_MODAL_AXIS_Z, "AXIS_Z", 0, "Z axis", ""}, + {TFM_MODAL_PLANE_X, "PLANE_X", 0, "X plane", ""}, + {TFM_MODAL_PLANE_Y, "PLANE_Y", 0, "Y plane", ""}, + {TFM_MODAL_PLANE_Z, "PLANE_Z", 0, "Z plane", ""}, + {TFM_MODAL_CONS_OFF, "CONS_OFF", 0, "Clear Constraints", ""}, + {TFM_MODAL_SNAP_INV_ON, "SNAP_INV_ON", 0, "Snap Invert", ""}, + {TFM_MODAL_SNAP_INV_OFF, "SNAP_INV_OFF", 0, "Snap Invert (Off)", ""}, {TFM_MODAL_SNAP_TOGGLE, "SNAP_TOGGLE", 0, "Snap Toggle", ""}, - {TFM_MODAL_AXIS_X, "AXIS_X", 0, "Orientation X axis", ""}, - {TFM_MODAL_AXIS_Y, "AXIS_Y", 0, "Orientation Y axis", ""}, - {TFM_MODAL_AXIS_Z, "AXIS_Z", 0, "Orientation Z axis", ""}, - {TFM_MODAL_PLANE_X, "PLANE_X", 0, "Orientation X plane", ""}, - {TFM_MODAL_PLANE_Y, "PLANE_Y", 0, "Orientation Y plane", ""}, - {TFM_MODAL_PLANE_Z, "PLANE_Z", 0, "Orientation Z plane", ""}, - {TFM_MODAL_CONS_OFF, "CONS_OFF", 0, "Remove Constraints", ""}, {TFM_MODAL_ADD_SNAP, "ADD_SNAP", 0, "Add Snap Point", ""}, {TFM_MODAL_REMOVE_SNAP, "REMOVE_SNAP", 0, "Remove Last Snap Point", ""}, {NUM_MODAL_INCREMENT_UP, "INCREMENT_UP", 0, "Numinput Increment Up", ""}, @@ -829,6 +826,9 @@ wmKeyMap *transform_modal_keymap(wmKeyConfig *keyconf) {TFM_MODAL_EDGESLIDE_DOWN, "EDGESLIDE_PREV_NEXT", 0, "Select previous Edge Slide Edge", ""}, {TFM_MODAL_PROPSIZE, "PROPORTIONAL_SIZE", 0, "Adjust Proportional Influence", ""}, {TFM_MODAL_INSERTOFS_TOGGLE_DIR, "INSERTOFS_TOGGLE_DIR", 0, "Toggle Direction for Node Auto-offset", ""}, + {TFM_MODAL_TRANSLATE, "TRANSLATE", 0, "Translate", ""}, + {TFM_MODAL_ROTATE, "ROTATE", 0, "Rotate", ""}, + {TFM_MODAL_RESIZE, "RESIZE", 0, "Resize", ""}, {0, NULL, 0, NULL, NULL} }; @@ -840,10 +840,21 @@ wmKeyMap *transform_modal_keymap(wmKeyConfig *keyconf) keymap = WM_modalkeymap_add(keyconf, "Transform Modal Map", modal_items); /* items for modal map */ - WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_CANCEL); - WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); - WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); - WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); + WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); + WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); + WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM); + WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_PRESS, KM_ANY, 0, TFM_MODAL_CANCEL); + WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_CANCEL); + + WM_modalkeymap_add_item(keymap, XKEY, KM_PRESS, 0, 0, TFM_MODAL_AXIS_X); + WM_modalkeymap_add_item(keymap, YKEY, KM_PRESS, 0, 0, TFM_MODAL_AXIS_Y); + WM_modalkeymap_add_item(keymap, ZKEY, KM_PRESS, 0, 0, TFM_MODAL_AXIS_Z); + + WM_modalkeymap_add_item(keymap, XKEY, KM_PRESS, KM_SHIFT, 0, TFM_MODAL_PLANE_X); + WM_modalkeymap_add_item(keymap, YKEY, KM_PRESS, KM_SHIFT, 0, TFM_MODAL_PLANE_Y); + WM_modalkeymap_add_item(keymap, ZKEY, KM_PRESS, KM_SHIFT, 0, TFM_MODAL_PLANE_Z); + + WM_modalkeymap_add_item(keymap, CKEY, KM_PRESS, 0, 0, TFM_MODAL_CONS_OFF); WM_modalkeymap_add_item(keymap, GKEY, KM_PRESS, 0, 0, TFM_MODAL_TRANSLATE); WM_modalkeymap_add_item(keymap, RKEY, KM_PRESS, 0, 0, TFM_MODAL_ROTATE); @@ -884,7 +895,7 @@ wmKeyMap *transform_modal_keymap(wmKeyConfig *keyconf) return keymap; } -static void transform_event_xyz_constraint(TransInfo *t, short key_type, char cmode) +static void transform_event_xyz_constraint(TransInfo *t, short key_type, char cmode, bool is_plane) { if (!(t->flag & T_NO_CONSTRAINT)) { int constraint_axis, constraint_plane; @@ -937,17 +948,21 @@ static void transform_event_xyz_constraint(TransInfo *t, short key_type, char cm else { short orientation = (t->current_orientation != V3D_MANIP_GLOBAL ? t->current_orientation : V3D_MANIP_LOCAL); - if (!(t->modifiers & MOD_CONSTRAINT_PLANE)) + if (is_plane == false) { setUserConstraint(t, orientation, constraint_axis, msg2); - else if (t->modifiers & MOD_CONSTRAINT_PLANE) + } + else { setUserConstraint(t, orientation, constraint_plane, msg3); + } } } else { - if (!(t->modifiers & MOD_CONSTRAINT_PLANE)) + if (is_plane == false) { setUserConstraint(t, V3D_MANIP_GLOBAL, constraint_axis, msg2); - else if (t->modifiers & MOD_CONSTRAINT_PLANE) + } + else { setUserConstraint(t, V3D_MANIP_GLOBAL, constraint_plane, msg3); + } } } t->redraw |= TREDRAW_HARD; @@ -1125,57 +1140,42 @@ int transformEvent(TransInfo *t, const wmEvent *event) break; case TFM_MODAL_AXIS_X: if (!(t->flag & T_NO_CONSTRAINT)) { - transform_event_xyz_constraint(t, XKEY, cmode); + transform_event_xyz_constraint(t, XKEY, cmode, false); t->redraw |= TREDRAW_HARD; handled = true; } break; case TFM_MODAL_AXIS_Y: if ((t->flag & T_NO_CONSTRAINT) == 0) { - transform_event_xyz_constraint(t, YKEY, cmode); + transform_event_xyz_constraint(t, YKEY, cmode, false); t->redraw |= TREDRAW_HARD; handled = true; } break; case TFM_MODAL_AXIS_Z: if ((t->flag & (T_NO_CONSTRAINT)) == 0) { - transform_event_xyz_constraint(t, ZKEY, cmode); + transform_event_xyz_constraint(t, ZKEY, cmode, false); t->redraw |= TREDRAW_HARD; handled = true; } break; case TFM_MODAL_PLANE_X: if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) { - if (cmode == 'X') { - stopConstraint(t); - } - else { - setUserConstraint(t, t->current_orientation, (CON_AXIS1 | CON_AXIS2), IFACE_("locking %s X")); - } + transform_event_xyz_constraint(t, XKEY, cmode, true); t->redraw |= TREDRAW_HARD; handled = true; } break; case TFM_MODAL_PLANE_Y: if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) { - if (cmode == 'Y') { - stopConstraint(t); - } - else { - setUserConstraint(t, t->current_orientation, (CON_AXIS0 | CON_AXIS2), IFACE_("locking %s Y")); - } + transform_event_xyz_constraint(t, YKEY, cmode, true); t->redraw |= TREDRAW_HARD; handled = true; } break; case TFM_MODAL_PLANE_Z: if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) { - if (cmode == 'Z') { - stopConstraint(t); - } - else { - setUserConstraint(t, t->current_orientation, (CON_AXIS0 | CON_AXIS1), IFACE_("locking %s Z")); - } + transform_event_xyz_constraint(t, ZKEY, cmode, true); t->redraw |= TREDRAW_HARD; handled = true; } @@ -1393,21 +1393,6 @@ int transformEvent(TransInfo *t, const wmEvent *event) handled = true; } } - else { - if (!(t->flag & T_NO_CONSTRAINT)) { - stopConstraint(t); - t->redraw |= TREDRAW_HARD; - handled = true; - } - } - break; - case XKEY: - case YKEY: - case ZKEY: - if (!(t->flag & T_NO_CONSTRAINT)) { - transform_event_xyz_constraint(t, event->type, cmode); - handled = true; - } break; case OKEY: if (t->flag & T_PROP_EDIT && event->shift) { @@ -1680,7 +1665,7 @@ static void drawArc(float size, float angle_start, float angle_end, int segments glEnd(); } -static int helpline_poll(bContext *C) +static bool helpline_poll(bContext *C) { ARegion *ar = CTX_wm_region(C); @@ -1887,7 +1872,7 @@ static void drawTransformPixel(const struct bContext *UNUSED(C), ARegion *ar, vo void saveTransform(bContext *C, TransInfo *t, wmOperator *op) { ToolSettings *ts = CTX_data_tool_settings(C); - int constraint_axis[3] = {0, 0, 0}; + bool constraint_axis[3] = {false, false, false}; int proportional = 0; PropertyRNA *prop; @@ -2004,17 +1989,21 @@ void saveTransform(bContext *C, TransInfo *t, wmOperator *op) if (t->con.mode & CON_APPLY) { if (t->con.mode & CON_AXIS0) { - constraint_axis[0] = 1; + constraint_axis[0] = true; } if (t->con.mode & CON_AXIS1) { - constraint_axis[1] = 1; + constraint_axis[1] = true; } if (t->con.mode & CON_AXIS2) { - constraint_axis[2] = 1; + constraint_axis[2] = true; } } - RNA_property_boolean_set_array(op->ptr, prop, constraint_axis); + /* Only set if needed, so we can hide in the UI when nothing is set. + * See 'transform_poll_property'. */ + if (ELEM(true, UNPACK3(constraint_axis))) { + RNA_property_boolean_set_array(op->ptr, prop, constraint_axis); + } } { @@ -2313,7 +2302,7 @@ bool initTransform(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve /* Constraint init from operator */ if ((prop = RNA_struct_find_property(op->ptr, "constraint_axis")) && RNA_property_is_set(op->ptr, prop)) { - int constraint_axis[3]; + bool constraint_axis[3]; RNA_property_boolean_get_array(op->ptr, prop, constraint_axis); @@ -8616,7 +8605,7 @@ static void applyTimeScale(TransInfo *t, const int UNUSED(mval[2])) /** \} */ -/* TODO, move to: transform_queries.c */ +/* TODO, move to: transform_query.c */ bool checkUseAxisMatrix(TransInfo *t) { /* currently only checks for editmode */ diff --git a/source/blender/editors/transform/transform.h b/source/blender/editors/transform/transform.h index b1b1dd36bf09..5f7388045791 100644 --- a/source/blender/editors/transform/transform.h +++ b/source/blender/editors/transform/transform.h @@ -695,8 +695,8 @@ void snapGridIncrementAction(TransInfo *t, float *val, GearsType action); void snapSequenceBounds(TransInfo *t, const int mval[2]); -bool activeSnap(TransInfo *t); -bool validSnap(TransInfo *t); +bool activeSnap(const TransInfo *t); +bool validSnap(const TransInfo *t); void initSnapping(struct TransInfo *t, struct wmOperator *op); void freeSnapping(struct TransInfo *t); @@ -706,10 +706,10 @@ void applySnapping(TransInfo *t, float *vec); void resetSnapping(TransInfo *t); eRedrawFlag handleSnapping(TransInfo *t, const struct wmEvent *event); void drawSnapping(const struct bContext *C, TransInfo *t); -bool usingSnappingNormal(TransInfo *t); -bool validSnappingNormal(TransInfo *t); +bool usingSnappingNormal(const TransInfo *t); +bool validSnappingNormal(const TransInfo *t); -void getSnapPoint(TransInfo *t, float vec[3]); +void getSnapPoint(const TransInfo *t, float vec[3]); void addSnapPoint(TransInfo *t); eRedrawFlag updateSelectedSnapPoint(TransInfo *t); void removeSnapPoint(TransInfo *t); @@ -809,7 +809,7 @@ void freeVertSlideVerts(TransInfo *t, TransCustomData *custom_data); void projectVertSlideData(TransInfo *t, bool is_final); -/* TODO. transform_queries.c */ +/* TODO. transform_query.c */ bool checkUseAxisMatrix(TransInfo *t); #define TRANSFORM_DIST_MAX_PX 1000.0f diff --git a/source/blender/editors/transform/transform_generics.c b/source/blender/editors/transform/transform_generics.c index 477e1abf80f6..9a2c3674d2af 100644 --- a/source/blender/editors/transform/transform_generics.c +++ b/source/blender/editors/transform/transform_generics.c @@ -2170,4 +2170,3 @@ void transform_data_ext_rotate(TransData *td, float mat[3][3], bool use_drot) copy_v3_v3(td->ext->rot, eul); } } - diff --git a/source/blender/editors/transform/transform_manipulator.c b/source/blender/editors/transform/transform_manipulator.c index ca133de1247e..79785f982c8f 100644 --- a/source/blender/editors/transform/transform_manipulator.c +++ b/source/blender/editors/transform/transform_manipulator.c @@ -1849,7 +1849,7 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op) ScrArea *sa = CTX_wm_area(C); View3D *v3d = sa->spacedata.first; ARegion *ar = CTX_wm_region(C); - int constraint_axis[3] = {0, 0, 0}; + bool constraint_axis[3] = {false, false, false}; int val; const bool use_planar = RNA_boolean_get(op->ptr, "use_planar_constraint"); @@ -1980,4 +1980,3 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op) return val; } - diff --git a/source/blender/editors/transform/transform_ops.c b/source/blender/editors/transform/transform_ops.c index 4157b69fded1..7120158ab46b 100644 --- a/source/blender/editors/transform/transform_ops.c +++ b/source/blender/editors/transform/transform_ops.c @@ -221,7 +221,7 @@ static int delete_orientation_invoke(bContext *C, wmOperator *op, const wmEvent return delete_orientation_exec(C, op); } -static int delete_orientation_poll(bContext *C) +static bool delete_orientation_poll(bContext *C) { int selected_index = -1; View3D *v3d = CTX_wm_view3d(C); @@ -305,7 +305,7 @@ static void transformops_loopsel_hack(bContext *C, wmOperator *op) if (op->opm && op->opm->opm && op->opm->opm->prev) { wmOperator *op_prev = op->opm->opm->prev; Scene *scene = CTX_data_scene(C); - int mesh_select_mode[3]; + bool mesh_select_mode[3]; PropertyRNA *prop = RNA_struct_find_property(op_prev->ptr, "mesh_select_mode_init"); if (prop && RNA_property_is_set(op_prev->ptr, prop)) { @@ -495,6 +495,36 @@ static int transform_invoke(bContext *C, wmOperator *op, const wmEvent *event) } } +static bool transform_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop) +{ + const char *prop_id = RNA_property_identifier(prop); + + /* Orientation/Constraints. */ + { + /* Hide orientation axis if no constraints are set, since it wont be used. */ + PropertyRNA *prop_con = RNA_struct_find_property(op->ptr, "constraint_axis"); + if (prop_con && !RNA_property_is_set(op->ptr, prop_con)) { + if (STRPREFIX(prop_id, "constraint")) { + return false; + } + } + } + + /* Proportional Editing. */ + { + PropertyRNA *prop_pet = RNA_struct_find_property(op->ptr, "proportional"); + if (prop_pet && (prop_pet != prop) && + (RNA_property_enum_get(op->ptr, prop_pet) == PROP_EDIT_OFF)) + { + if (STRPREFIX(prop_id, "proportional")) { + return false; + } + } + } + + return true; +} + void Transform_Properties(struct wmOperatorType *ot, int flags) { PropertyRNA *prop; @@ -596,8 +626,9 @@ static void TRANSFORM_OT_translate(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; - RNA_def_float_vector_xyz(ot->srna, "value", 3, NULL, -FLT_MAX, FLT_MAX, "Vector", "", -FLT_MAX, FLT_MAX); + RNA_def_float_vector_xyz(ot->srna, "value", 3, NULL, -FLT_MAX, FLT_MAX, "Move", "", -FLT_MAX, FLT_MAX); Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_ALIGN_SNAP | P_OPTIONS | P_GPENCIL_EDIT); } @@ -616,14 +647,15 @@ static void TRANSFORM_OT_resize(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; - RNA_def_float_vector(ot->srna, "value", 3, VecOne, -FLT_MAX, FLT_MAX, "Vector", "", -FLT_MAX, FLT_MAX); + RNA_def_float_vector(ot->srna, "value", 3, VecOne, -FLT_MAX, FLT_MAX, "Scale", "", -FLT_MAX, FLT_MAX); Transform_Properties( ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_OPTIONS | P_GPENCIL_EDIT | P_CENTER); } -static int skin_resize_poll(bContext *C) +static bool skin_resize_poll(bContext *C) { struct Object *obedit = CTX_data_edit_object(C); if (obedit && obedit->type == OB_MESH) { @@ -647,8 +679,9 @@ static void TRANSFORM_OT_skin_resize(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = skin_resize_poll; + ot->poll_property = transform_poll_property; - RNA_def_float_vector(ot->srna, "value", 3, VecOne, -FLT_MAX, FLT_MAX, "Vector", "", -FLT_MAX, FLT_MAX); + RNA_def_float_vector(ot->srna, "value", 3, VecOne, -FLT_MAX, FLT_MAX, "Scale", "", -FLT_MAX, FLT_MAX); Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_OPTIONS | P_NO_TEXSPACE); } @@ -667,6 +700,7 @@ static void TRANSFORM_OT_trackball(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; /* Maybe we could use float_vector_xyz here too? */ RNA_def_float_rotation(ot->srna, "value", 2, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -FLT_MAX, FLT_MAX); @@ -688,6 +722,7 @@ static void TRANSFORM_OT_rotate(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; RNA_def_float_rotation(ot->srna, "value", 0, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2); @@ -712,6 +747,7 @@ static void TRANSFORM_OT_tilt(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_editcurve_3d; + ot->poll_property = transform_poll_property; RNA_def_float_rotation(ot->srna, "value", 0, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2); @@ -732,6 +768,7 @@ static void TRANSFORM_OT_bend(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_region_view3d_active; + ot->poll_property = transform_poll_property; RNA_def_float_rotation(ot->srna, "value", 1, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2); @@ -752,6 +789,7 @@ static void TRANSFORM_OT_shear(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; RNA_def_float(ot->srna, "value", 0, -FLT_MAX, FLT_MAX, "Offset", "", -FLT_MAX, FLT_MAX); @@ -773,6 +811,7 @@ static void TRANSFORM_OT_push_pull(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; RNA_def_float(ot->srna, "value", 0, -FLT_MAX, FLT_MAX, "Distance", "", -FLT_MAX, FLT_MAX); @@ -793,6 +832,7 @@ static void TRANSFORM_OT_shrink_fatten(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_editmesh; + ot->poll_property = transform_poll_property; RNA_def_float(ot->srna, "value", 0, -FLT_MAX, FLT_MAX, "Offset", "", -FLT_MAX, FLT_MAX); @@ -816,6 +856,7 @@ static void TRANSFORM_OT_tosphere(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; RNA_def_float_factor(ot->srna, "value", 0, 0, 1, "Factor", "", 0, 1); @@ -836,6 +877,7 @@ static void TRANSFORM_OT_mirror(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_GPENCIL_EDIT | P_CENTER); } @@ -856,6 +898,7 @@ static void TRANSFORM_OT_edge_slide(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_editmesh_region_view3d; + ot->poll_property = transform_poll_property; RNA_def_float_factor(ot->srna, "value", 0, -10.0f, 10.0f, "Factor", "", -1.0f, 1.0f); @@ -885,6 +928,7 @@ static void TRANSFORM_OT_vert_slide(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_editmesh_region_view3d; + ot->poll_property = transform_poll_property; RNA_def_float_factor(ot->srna, "value", 0, -10.0f, 10.0f, "Factor", "", -1.0f, 1.0f); RNA_def_boolean(ot->srna, "use_even", false, "Even", @@ -911,6 +955,7 @@ static void TRANSFORM_OT_edge_crease(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_editmesh; + ot->poll_property = transform_poll_property; RNA_def_float_factor(ot->srna, "value", 0, -1.0f, 1.0f, "Factor", "", -1.0f, 1.0f); @@ -973,7 +1018,7 @@ static void TRANSFORM_OT_seq_slide(struct wmOperatorType *ot) ot->cancel = transform_cancel; ot->poll = ED_operator_sequencer_active; - RNA_def_float_vector_xyz(ot->srna, "value", 2, NULL, -FLT_MAX, FLT_MAX, "Vector", "", -FLT_MAX, FLT_MAX); + RNA_def_float_vector_xyz(ot->srna, "value", 2, NULL, -FLT_MAX, FLT_MAX, "Offset", "", -FLT_MAX, FLT_MAX); Transform_Properties(ot, P_SNAP); } @@ -994,6 +1039,7 @@ static void TRANSFORM_OT_transform(struct wmOperatorType *ot) ot->modal = transform_modal; ot->cancel = transform_cancel; ot->poll = ED_operator_screenactive; + ot->poll_property = transform_poll_property; prop = RNA_def_enum(ot->srna, "mode", rna_enum_transform_mode_types, TFM_TRANSLATION, "Mode", ""); RNA_def_property_flag(prop, PROP_HIDDEN); @@ -1183,4 +1229,3 @@ void transform_keymap_for_space(wmKeyConfig *keyconf, wmKeyMap *keymap, int spac break; } } - diff --git a/source/blender/editors/transform/transform_snap.c b/source/blender/editors/transform/transform_snap.c index 5ea826521ed8..8bc53127b4ce 100644 --- a/source/blender/editors/transform/transform_snap.c +++ b/source/blender/editors/transform/transform_snap.c @@ -122,13 +122,13 @@ int BIF_snappingSupported(Object *obedit) } #endif -bool validSnap(TransInfo *t) +bool validSnap(const TransInfo *t) { return (t->tsnap.status & (POINT_INIT | TARGET_INIT)) == (POINT_INIT | TARGET_INIT) || (t->tsnap.status & (MULTI_POINTS | TARGET_INIT)) == (MULTI_POINTS | TARGET_INIT); } -bool activeSnap(TransInfo *t) +bool activeSnap(const TransInfo *t) { return ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP) || ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP_INVERT); @@ -471,12 +471,12 @@ void resetSnapping(TransInfo *t) t->tsnap.snapNodeBorder = 0; } -bool usingSnappingNormal(TransInfo *t) +bool usingSnappingNormal(const TransInfo *t) { return t->tsnap.align; } -bool validSnappingNormal(TransInfo *t) +bool validSnappingNormal(const TransInfo *t) { if (validSnap(t)) { if (!is_zero_v3(t->tsnap.snapNormal)) { @@ -807,7 +807,7 @@ void removeSnapPoint(TransInfo *t) } } -void getSnapPoint(TransInfo *t, float vec[3]) +void getSnapPoint(const TransInfo *t, float vec[3]) { if (t->tsnap.points.first) { TransSnapPoint *p; diff --git a/source/blender/editors/undo/ed_undo.c b/source/blender/editors/undo/ed_undo.c index 4472b8f9a098..621c5d73d5af 100644 --- a/source/blender/editors/undo/ed_undo.c +++ b/source/blender/editors/undo/ed_undo.c @@ -38,6 +38,8 @@ #include "DNA_scene_types.h" #include "BLI_utildefines.h" +#include "BLI_callbacks.h" +#include "BLI_listbase.h" #include "BLT_translation.h" @@ -109,9 +111,7 @@ static int ed_undo_step(bContext *C, int step, const char *undoname) /* undo during jobs are running can easily lead to freeing data using by jobs, * or they can just lead to freezing job in some other cases */ - if (WM_jobs_test(wm, scene, WM_JOB_TYPE_ANY)) { - return OPERATOR_CANCELLED; - } + WM_jobs_kill_all(wm); /* TODO(campbell): undo_system: use undo system */ /* grease pencil can be can be used in plenty of spaces, so check it first */ @@ -119,17 +119,50 @@ static int ed_undo_step(bContext *C, int step, const char *undoname) return ED_undo_gpencil_step(C, step, undoname); } + UndoStep *step_data_from_name = NULL; + int step_for_callback = step; + if (undoname != NULL) { + step_data_from_name = BKE_undosys_step_find_by_name(wm->undo_stack, undoname); + if (step_data_from_name == NULL) { + return OPERATOR_CANCELLED; + } + + /* TODO(campbell), could use simple optimization. */ + /* Pointers match on redo. */ + step_for_callback = ( + BLI_findindex(&wm->undo_stack->steps, step_data_from_name) < + BLI_findindex(&wm->undo_stack->steps, wm->undo_stack->step_active)) ? 1 : -1; + } + + /* App-Handlers (pre). */ + { + /* Note: ignore grease pencil for now. */ + Main *bmain = CTX_data_main(C); + wm->op_undo_depth++; + BLI_callback_exec(bmain, &scene->id, (step_for_callback > 0) ? BLI_CB_EVT_UNDO_PRE : BLI_CB_EVT_REDO_PRE); + wm->op_undo_depth--; + } + + /* Undo System */ { if (undoname) { - UndoStep *step_data = BKE_undosys_step_find_by_name(wm->undo_stack, undoname); - BKE_undosys_step_undo_with_data(wm->undo_stack, C, step_data); + BKE_undosys_step_undo_with_data(wm->undo_stack, C, step_data_from_name); } else { BKE_undosys_step_undo_compat_only(wm->undo_stack, C, step); } } + /* App-Handlers (post). */ + { + Main *bmain = CTX_data_main(C); + scene = CTX_data_scene(C); + wm->op_undo_depth++; + BLI_callback_exec(bmain, &scene->id, step_for_callback > 0 ? BLI_CB_EVT_UNDO_PRE : BLI_CB_EVT_REDO_PRE); + wm->op_undo_depth--; + } + WM_event_add_notifier(C, NC_WINDOW, NULL); WM_event_add_notifier(C, NC_WM | ND_UNDO, NULL); @@ -237,7 +270,7 @@ static int ed_undo_redo_exec(bContext *C, wmOperator *UNUSED(op)) return ret ? OPERATOR_FINISHED : OPERATOR_CANCELLED; } -static int ed_undo_redo_poll(bContext *C) +static bool ed_undo_redo_poll(bContext *C) { wmOperator *last_op = WM_operator_last_redo(C); return last_op && ED_operator_screenactive(C) && diff --git a/source/blender/editors/util/CMakeLists.txt b/source/blender/editors/util/CMakeLists.txt index 8657c876d473..c0a6fe676f1a 100644 --- a/source/blender/editors/util/CMakeLists.txt +++ b/source/blender/editors/util/CMakeLists.txt @@ -84,6 +84,7 @@ set(SRC ../include/ED_transform_snap_object_context.h ../include/ED_transverts.h ../include/ED_types.h + ../include/ED_undo.h ../include/ED_util.h ../include/ED_uvedit.h ../include/ED_view3d.h diff --git a/source/blender/editors/util/ed_transverts.c b/source/blender/editors/util/ed_transverts.c index c3fb653979cf..e6b13569d6ad 100644 --- a/source/blender/editors/util/ed_transverts.c +++ b/source/blender/editors/util/ed_transverts.c @@ -496,7 +496,7 @@ void ED_transverts_free(TransVertStore *tvs) tvs->transverts_tot = 0; } -int ED_transverts_poll(bContext *C) +bool ED_transverts_poll(bContext *C) { Object *obedit = CTX_data_edit_object(C); if (obedit) { diff --git a/source/blender/editors/uvedit/uvedit_buttons.c b/source/blender/editors/uvedit/uvedit_buttons.c index 92e0920da6b6..f9c5dd89179f 100644 --- a/source/blender/editors/uvedit/uvedit_buttons.c +++ b/source/blender/editors/uvedit/uvedit_buttons.c @@ -214,7 +214,7 @@ static void do_uvedit_vertex(bContext *C, void *UNUSED(arg), int event) /* Panels */ -static int image_panel_uv_poll(const bContext *C, PanelType *UNUSED(pt)) +static bool image_panel_uv_poll(const bContext *C, PanelType *UNUSED(pt)) { Object *obedit = CTX_data_edit_object(C); return ED_uvedit_test(obedit); @@ -241,4 +241,3 @@ void ED_uvedit_buttons_register(ARegionType *art) pt->poll = image_panel_uv_poll; BLI_addtail(&art->paneltypes, pt); } - diff --git a/source/blender/editors/uvedit/uvedit_draw.c b/source/blender/editors/uvedit/uvedit_draw.c index 79dcfb3299fe..a9f650a6d7a1 100644 --- a/source/blender/editors/uvedit/uvedit_draw.c +++ b/source/blender/editors/uvedit/uvedit_draw.c @@ -993,4 +993,3 @@ void ED_uvedit_draw_main(SpaceImage *sima, ARegion *ar, Scene *scene, Object *ob ED_image_draw_cursor(ar, sima->cursor); } } - diff --git a/source/blender/editors/uvedit/uvedit_ops.c b/source/blender/editors/uvedit/uvedit_ops.c index 0fa5fb9a48df..c0378f967ad0 100644 --- a/source/blender/editors/uvedit/uvedit_ops.c +++ b/source/blender/editors/uvedit/uvedit_ops.c @@ -112,7 +112,7 @@ bool ED_uvedit_test(Object *obedit) return ret; } -static int ED_operator_uvedit_can_uv_sculpt(struct bContext *C) +static bool ED_operator_uvedit_can_uv_sculpt(struct bContext *C) { SpaceImage *sima = CTX_wm_space_image(C); ToolSettings *toolsettings = CTX_data_tool_settings(C); @@ -1043,7 +1043,7 @@ static UvMapVert *uv_select_edgeloop_vertex_map_get(UvVertMap *vmap, BMFace *efa for (iterv = first; iterv; iterv = iterv->next) { if (iterv->separate) first = iterv; - if (iterv->f == BM_elem_index_get(efa)) + if (iterv->poly_index == BM_elem_index_get(efa)) return first; } @@ -1065,9 +1065,9 @@ static bool uv_select_edgeloop_edge_tag_faces(BMEditMesh *em, UvMapVert *first1, if (iterv2->separate && iterv2 != first2) break; - if (iterv1->f == iterv2->f) { + if (iterv1->poly_index == iterv2->poly_index) { /* if face already tagged, don't do this edge */ - efa = BM_face_at_index(em->bm, iterv1->f); + efa = BM_face_at_index(em->bm, iterv1->poly_index); if (BM_elem_flag_test(efa, BM_ELEM_TAG)) return false; @@ -1091,8 +1091,8 @@ static bool uv_select_edgeloop_edge_tag_faces(BMEditMesh *em, UvMapVert *first1, if (iterv2->separate && iterv2 != first2) break; - if (iterv1->f == iterv2->f) { - efa = BM_face_at_index(em->bm, iterv1->f); + if (iterv1->poly_index == iterv2->poly_index) { + efa = BM_face_at_index(em->bm, iterv1->poly_index); BM_elem_flag_enable(efa, BM_ELEM_TAG); break; } @@ -1301,16 +1301,16 @@ static void uv_select_linked( for (iterv = vlist; iterv; iterv = iterv->next) { if (iterv->separate) startv = iterv; - if (iterv->f == a) + if (iterv->poly_index == a) break; } for (iterv = startv; iterv; iterv = iterv->next) { if ((startv != iterv) && (iterv->separate)) break; - else if (!flag[iterv->f]) { - flag[iterv->f] = 1; - stack[stacksize] = iterv->f; + else if (!flag[iterv->poly_index]) { + flag[iterv->poly_index] = 1; + stack[stacksize] = iterv->poly_index; stacksize++; } } @@ -2750,7 +2750,7 @@ static void uv_select_flush_from_tag_sticky_loc_internal( if (vlist_iter->separate) start_vlist = vlist_iter; - if (efa_index == vlist_iter->f) + if (efa_index == vlist_iter->poly_index) break; vlist_iter = vlist_iter->next; @@ -2762,12 +2762,12 @@ static void uv_select_flush_from_tag_sticky_loc_internal( if (vlist_iter != start_vlist && vlist_iter->separate) break; - if (efa_index != vlist_iter->f) { + if (efa_index != vlist_iter->poly_index) { BMLoop *l_other; - efa_vlist = BM_face_at_index(em->bm, vlist_iter->f); + efa_vlist = BM_face_at_index(em->bm, vlist_iter->poly_index); /* tf_vlist = BM_ELEM_CD_GET_VOID_P(efa_vlist, cd_poly_tex_offset); */ /* UNUSED */ - l_other = BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->tfindex); + l_other = BM_iter_at_index(em->bm, BM_LOOPS_OF_FACE, efa_vlist, vlist_iter->loop_of_poly_index); uvedit_uv_select_set(em, scene, l_other, select, false, cd_loop_uv_offset); } @@ -4053,7 +4053,7 @@ static void UV_OT_reveal(wmOperatorType *ot) /** \name Set 2D Cursor Operator * \{ */ -static int uv_set_2d_cursor_poll(bContext *C) +static bool uv_set_2d_cursor_poll(bContext *C) { return ED_operator_uvedit_space_image(C) || ED_space_image_maskedit_poll(C) || @@ -4241,14 +4241,14 @@ static int uv_seams_from_islands_exec(bContext *C, wmOperator *op) v1coincident = 0; separated2 = 0; - efa1 = BM_face_at_index(bm, mv1->f); + efa1 = BM_face_at_index(bm, mv1->poly_index); mvinit2 = vmap->vert[BM_elem_index_get(editedge->v2)]; for (mv2 = mvinit2; mv2; mv2 = mv2->next) { if (mv2->separate) mv2sep = mv2; - efa2 = BM_face_at_index(bm, mv2->f); + efa2 = BM_face_at_index(bm, mv2->poly_index); if (efa1 == efa2) { /* if v1 is not coincident no point in comparing */ if (v1coincident) { @@ -4458,7 +4458,7 @@ void ED_keymap_uvedit(wmKeyConfig *keyconf) wmKeyMap *keymap; wmKeyMapItem *kmi; - keymap = WM_keymap_find(keyconf, "UV Editor", 0, 0); + keymap = WM_keymap_ensure(keyconf, "UV Editor", 0, 0); keymap->poll = ED_operator_uvedit_can_uv_sculpt; /* Uv sculpt toggle */ diff --git a/source/blender/editors/uvedit/uvedit_parametrizer.c b/source/blender/editors/uvedit/uvedit_parametrizer.c index 1d2583cf9d40..79e804725e5b 100644 --- a/source/blender/editors/uvedit/uvedit_parametrizer.c +++ b/source/blender/editors/uvedit/uvedit_parametrizer.c @@ -4702,4 +4702,3 @@ void param_flush_restore(ParamHandle *handle) p_face_restore_uvs(f); } } - diff --git a/source/blender/editors/uvedit/uvedit_parametrizer.h b/source/blender/editors/uvedit/uvedit_parametrizer.h index 50b4ee666447..2714bc33769f 100644 --- a/source/blender/editors/uvedit/uvedit_parametrizer.h +++ b/source/blender/editors/uvedit/uvedit_parametrizer.h @@ -120,4 +120,3 @@ void param_flush_restore(ParamHandle *handle); #endif #endif /*__UVEDIT_PARAMETRIZER_H__*/ - diff --git a/source/blender/editors/uvedit/uvedit_smart_stitch.c b/source/blender/editors/uvedit/uvedit_smart_stitch.c index e4452af47903..0b768350942f 100644 --- a/source/blender/editors/uvedit/uvedit_smart_stitch.c +++ b/source/blender/editors/uvedit/uvedit_smart_stitch.c @@ -483,9 +483,10 @@ static void stitch_calculate_island_snapping( int face_preview_pos = preview_position[BM_elem_index_get(element->l->f)].data_position; stitch_uv_rotate(rotation_mat, island_stitch_data[i].medianPoint, - preview->preview_polys + face_preview_pos + 2 * element->tfindex, state->aspect); + preview->preview_polys + face_preview_pos + 2 * element->loop_of_poly_index, + state->aspect); - add_v2_v2(preview->preview_polys + face_preview_pos + 2 * element->tfindex, + add_v2_v2(preview->preview_polys + face_preview_pos + 2 * element->loop_of_poly_index, island_stitch_data[i].translation); } } @@ -901,7 +902,7 @@ static void stitch_propagate_uv_final_position( else { int face_preview_pos = preview_position[BM_elem_index_get(element_iter->l->f)].data_position; if (face_preview_pos != STITCH_NO_PREVIEW) { - copy_v2_v2(preview->preview_polys + face_preview_pos + 2 * element_iter->tfindex, + copy_v2_v2(preview->preview_polys + face_preview_pos + 2 * element_iter->loop_of_poly_index, final_position[index].uv); } } @@ -2013,7 +2014,7 @@ static void stitch_exit(bContext *C, wmOperator *op, int finished) RNA_collection_add(op->ptr, "selection", &itemptr); RNA_int_set(&itemptr, "face_index", BM_elem_index_get(element->l->f)); - RNA_int_set(&itemptr, "element_index", element->tfindex); + RNA_int_set(&itemptr, "element_index", element->loop_of_poly_index); } uvedit_live_unwrap_update(sima, scene, obedit); diff --git a/source/blender/editors/uvedit/uvedit_unwrap_ops.c b/source/blender/editors/uvedit/uvedit_unwrap_ops.c index dbe8796ba8b1..06eae0ee63db 100644 --- a/source/blender/editors/uvedit/uvedit_unwrap_ops.c +++ b/source/blender/editors/uvedit/uvedit_unwrap_ops.c @@ -1398,7 +1398,7 @@ static int uv_from_view_exec(bContext *C, wmOperator *op) return OPERATOR_FINISHED; } -static int uv_from_view_poll(bContext *C) +static bool uv_from_view_poll(bContext *C) { RegionView3D *rv3d = CTX_wm_region_view3d(C); diff --git a/source/blender/freestyle/intern/application/AppCanvas.cpp b/source/blender/freestyle/intern/application/AppCanvas.cpp index f621f45ff776..aca725a03845 100644 --- a/source/blender/freestyle/intern/application/AppCanvas.cpp +++ b/source/blender/freestyle/intern/application/AppCanvas.cpp @@ -64,7 +64,7 @@ void AppCanvas::setViewer(AppView *iViewer) _pViewer = iViewer; } -int AppCanvas::width() const +int AppCanvas::width() const { return _pViewer->width(); } @@ -84,7 +84,7 @@ float AppCanvas::thickness() const return _pViewer->thickness(); } -BBox AppCanvas::scene3DBBox() const +BBox AppCanvas::scene3DBBox() const { return _pViewer->scene3DBBox(); } diff --git a/source/blender/freestyle/intern/application/Controller.cpp b/source/blender/freestyle/intern/application/Controller.cpp index beb857982237..46db99a8d516 100644 --- a/source/blender/freestyle/intern/application/Controller.cpp +++ b/source/blender/freestyle/intern/application/Controller.cpp @@ -471,11 +471,11 @@ void Controller::ComputeViewMap() // retrieve the 3D viewpoint and transformations information //---------------------------------------------------------- - // Save the viewpoint context at the view level in order + // Save the viewpoint context at the view level in order // to be able to restore it later: // Restore the context of view: - // we need to perform all these operations while the + // we need to perform all these operations while the // 3D context is on. Vec3f vp(UNPACK3(g_freestyle.viewpoint)); @@ -928,7 +928,7 @@ Render *Controller::RenderStrokes(Render *re, bool render) void Controller::InsertStyleModule(unsigned index, const char *iFileName) { - if (!BLI_testextensie(iFileName, ".py")) { + if (!BLI_path_extension_check(iFileName, ".py")) { cerr << "Error: Cannot load \"" << string(iFileName) << "\", unknown extension" << endl; return; } diff --git a/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp b/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp index 1f5e2b63bfae..7248bde0d102 100644 --- a/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp +++ b/source/blender/freestyle/intern/blender_interface/BlenderFileLoader.cpp @@ -158,24 +158,24 @@ int BlenderFileLoader::countClippedFaces(float v1[3], float v2[3], float v3[3], sum += clip[i]; } switch (numClipped) { - case 0: - numTris = 1; // triangle - break; - case 1: - numTris = 2; // tetragon - break; - case 2: - if (sum == 0) - numTris = 3; // pentagon - else + case 0: numTris = 1; // triangle - break; - case 3: - if (sum == 3 || sum == -3) - numTris = 0; - else + break; + case 1: numTris = 2; // tetragon - break; + break; + case 2: + if (sum == 0) + numTris = 3; // pentagon + else + numTris = 1; // triangle + break; + case 3: + if (sum == 3 || sum == -3) + numTris = 0; + else + numTris = 2; // tetragon + break; } return numTris; } @@ -668,7 +668,7 @@ void BlenderFileLoader::insertShapeNode(ObjectInstanceRen *obi, int id) } } - // We might have several times the same vertex. We want a clean + // We might have several times the same vertex. We want a clean // shape with no real-vertex. Here, we are making a cleaning pass. float *cleanVertices = NULL; unsigned int cvSize; diff --git a/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp b/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp index 71c77b60a071..9c3ff8999b7c 100644 --- a/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp +++ b/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp @@ -113,7 +113,7 @@ BlenderStrokeRenderer::BlenderStrokeRenderer(Render *re, int render_count) : Str freestyle_scene->r.gauss = old_scene->r.gauss; freestyle_scene->r.dither_intensity = old_scene->r.dither_intensity; BLI_strncpy(freestyle_scene->r.engine, old_scene->r.engine, sizeof(freestyle_scene->r.engine)); - freestyle_scene->r.im_format.planes = R_IMF_PLANES_RGBA; + freestyle_scene->r.im_format.planes = R_IMF_PLANES_RGBA; freestyle_scene->r.im_format.imtype = R_IMF_IMTYPE_PNG; if (G.debug & G_DEBUG_FREESTYLE) { @@ -176,17 +176,17 @@ BlenderStrokeRenderer::~BlenderStrokeRenderer() } #endif switch (ob->type) { - case OB_MESH: - BKE_libblock_free(freestyle_bmain, ob); - BKE_libblock_free(freestyle_bmain, data); - break; - case OB_CAMERA: - BKE_libblock_free(freestyle_bmain, ob); - BKE_libblock_free(freestyle_bmain, data); - freestyle_scene->camera = NULL; - break; - default: - cerr << "Warning: unexpected object in the scene: " << name[0] << name[1] << ":" << (name + 2) << endl; + case OB_MESH: + BKE_libblock_free(freestyle_bmain, ob); + BKE_libblock_free(freestyle_bmain, data); + break; + case OB_CAMERA: + BKE_libblock_free(freestyle_bmain, ob); + BKE_libblock_free(freestyle_bmain, data); + freestyle_scene->camera = NULL; + break; + default: + cerr << "Warning: unexpected object in the scene: " << name[0] << name[1] << ":" << (name + 2) << endl; } } BLI_freelistN(&freestyle_scene->base); diff --git a/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp b/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp index ea22633c50e3..6e65b021805a 100644 --- a/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp +++ b/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp @@ -96,7 +96,7 @@ static bCallbackFuncStore load_post_callback_funcstore = { }; //======================================================= -// Initialization +// Initialization //======================================================= void FRS_initialize() @@ -133,7 +133,7 @@ void FRS_exit() } //======================================================= -// Rendering +// Rendering //======================================================= static void init_view(Render *re) @@ -147,12 +147,12 @@ static void init_view(Render *re) float thickness = 1.0f; switch (re->r.line_thickness_mode) { - case R_LINE_THICKNESS_ABSOLUTE: - thickness = re->r.unit_line_thickness * (re->r.size / 100.f); - break; - case R_LINE_THICKNESS_RELATIVE: - thickness = height / 480.f; - break; + case R_LINE_THICKNESS_ABSOLUTE: + thickness = re->r.unit_line_thickness * (re->r.size / 100.f); + break; + case R_LINE_THICKNESS_RELATIVE: + thickness = height / 480.f; + break; } g_freestyle.viewport[0] = g_freestyle.viewport[1] = 0; @@ -303,115 +303,115 @@ static void prepare(Render *re, SceneRenderLayer *srl) int layer_count = 0; switch (config->mode) { - case FREESTYLE_CONTROL_SCRIPT_MODE: - if (G.debug & G_DEBUG_FREESTYLE) { - cout << "Modules :" << endl; - } - for (FreestyleModuleConfig *module_conf = (FreestyleModuleConfig *)config->modules.first; - module_conf; - module_conf = module_conf->next) - { - if (module_conf->script && module_conf->is_displayed) { - const char *id_name = module_conf->script->id.name + 2; - if (G.debug & G_DEBUG_FREESTYLE) { - cout << " " << layer_count + 1 << ": " << id_name; - if (module_conf->script->name) - cout << " (" << module_conf->script->name << ")"; - cout << endl; - } - controller->InsertStyleModule(layer_count, id_name, module_conf->script); - controller->toggleLayer(layer_count, true); - layer_count++; + case FREESTYLE_CONTROL_SCRIPT_MODE: + if (G.debug & G_DEBUG_FREESTYLE) { + cout << "Modules :" << endl; } - } - if (G.debug & G_DEBUG_FREESTYLE) { - cout << endl; - } - controller->setComputeRidgesAndValleysFlag((config->flags & FREESTYLE_RIDGES_AND_VALLEYS_FLAG) ? true : false); - controller->setComputeSuggestiveContoursFlag((config->flags & FREESTYLE_SUGGESTIVE_CONTOURS_FLAG) ? true : false); - controller->setComputeMaterialBoundariesFlag((config->flags & FREESTYLE_MATERIAL_BOUNDARIES_FLAG) ? true : false); - break; - case FREESTYLE_CONTROL_EDITOR_MODE: - int use_ridges_and_valleys = 0; - int use_suggestive_contours = 0; - int use_material_boundaries = 0; - struct edge_type_condition conditions[] = { - {FREESTYLE_FE_SILHOUETTE, 0}, - {FREESTYLE_FE_BORDER, 0}, - {FREESTYLE_FE_CREASE, 0}, - {FREESTYLE_FE_RIDGE_VALLEY, 0}, - {FREESTYLE_FE_SUGGESTIVE_CONTOUR, 0}, - {FREESTYLE_FE_MATERIAL_BOUNDARY, 0}, - {FREESTYLE_FE_CONTOUR, 0}, - {FREESTYLE_FE_EXTERNAL_CONTOUR, 0}, - {FREESTYLE_FE_EDGE_MARK, 0} - }; - int num_edge_types = sizeof(conditions) / sizeof(struct edge_type_condition); - if (G.debug & G_DEBUG_FREESTYLE) { - cout << "Linesets:" << endl; - } - for (FreestyleLineSet *lineset = (FreestyleLineSet *)config->linesets.first; - lineset; - lineset = lineset->next) - { - if (lineset->flags & FREESTYLE_LINESET_ENABLED) { - if (G.debug & G_DEBUG_FREESTYLE) { - cout << " " << layer_count+1 << ": " << lineset->name << " - " << - (lineset->linestyle ? (lineset->linestyle->id.name + 2) : "") << endl; - } - char *buffer = create_lineset_handler(srl->name, lineset->name); - controller->InsertStyleModule(layer_count, lineset->name, buffer); - controller->toggleLayer(layer_count, true); - MEM_freeN(buffer); - if (!(lineset->selection & FREESTYLE_SEL_EDGE_TYPES) || !lineset->edge_types) { - ++use_ridges_and_valleys; - ++use_suggestive_contours; - ++use_material_boundaries; - } - else { - // conditions for feature edge selection by edge types - for (int i = 0; i < num_edge_types; i++) { - if (!(lineset->edge_types & conditions[i].edge_type)) - conditions[i].value = 0; // no condition specified - else if (!(lineset->exclude_edge_types & conditions[i].edge_type)) - conditions[i].value = 1; // condition: X - else - conditions[i].value = -1; // condition: NOT X + for (FreestyleModuleConfig *module_conf = (FreestyleModuleConfig *)config->modules.first; + module_conf; + module_conf = module_conf->next) + { + if (module_conf->script && module_conf->is_displayed) { + const char *id_name = module_conf->script->id.name + 2; + if (G.debug & G_DEBUG_FREESTYLE) { + cout << " " << layer_count + 1 << ": " << id_name; + if (module_conf->script->name) + cout << " (" << module_conf->script->name << ")"; + cout << endl; } - // logical operator for the selection conditions - bool logical_and = ((lineset->flags & FREESTYLE_LINESET_FE_AND) != 0); - // negation operator - if (lineset->flags & FREESTYLE_LINESET_FE_NOT) { - // convert an Exclusive condition into an Inclusive equivalent using De Morgan's laws: - // NOT (X OR Y) --> (NOT X) AND (NOT Y) - // NOT (X AND Y) --> (NOT X) OR (NOT Y) - for (int i = 0; i < num_edge_types; i++) - conditions[i].value *= -1; - logical_and = !logical_and; + controller->InsertStyleModule(layer_count, id_name, module_conf->script); + controller->toggleLayer(layer_count, true); + layer_count++; + } + } + if (G.debug & G_DEBUG_FREESTYLE) { + cout << endl; + } + controller->setComputeRidgesAndValleysFlag((config->flags & FREESTYLE_RIDGES_AND_VALLEYS_FLAG) ? true : false); + controller->setComputeSuggestiveContoursFlag((config->flags & FREESTYLE_SUGGESTIVE_CONTOURS_FLAG) ? true : false); + controller->setComputeMaterialBoundariesFlag((config->flags & FREESTYLE_MATERIAL_BOUNDARIES_FLAG) ? true : false); + break; + case FREESTYLE_CONTROL_EDITOR_MODE: + int use_ridges_and_valleys = 0; + int use_suggestive_contours = 0; + int use_material_boundaries = 0; + struct edge_type_condition conditions[] = { + {FREESTYLE_FE_SILHOUETTE, 0}, + {FREESTYLE_FE_BORDER, 0}, + {FREESTYLE_FE_CREASE, 0}, + {FREESTYLE_FE_RIDGE_VALLEY, 0}, + {FREESTYLE_FE_SUGGESTIVE_CONTOUR, 0}, + {FREESTYLE_FE_MATERIAL_BOUNDARY, 0}, + {FREESTYLE_FE_CONTOUR, 0}, + {FREESTYLE_FE_EXTERNAL_CONTOUR, 0}, + {FREESTYLE_FE_EDGE_MARK, 0} + }; + int num_edge_types = sizeof(conditions) / sizeof(struct edge_type_condition); + if (G.debug & G_DEBUG_FREESTYLE) { + cout << "Linesets:" << endl; + } + for (FreestyleLineSet *lineset = (FreestyleLineSet *)config->linesets.first; + lineset; + lineset = lineset->next) + { + if (lineset->flags & FREESTYLE_LINESET_ENABLED) { + if (G.debug & G_DEBUG_FREESTYLE) { + cout << " " << layer_count+1 << ": " << lineset->name << " - " << + (lineset->linestyle ? (lineset->linestyle->id.name + 2) : "") << endl; } - if (test_edge_type_conditions(conditions, num_edge_types, logical_and, - FREESTYLE_FE_RIDGE_VALLEY, true)) - { + char *buffer = create_lineset_handler(srl->name, lineset->name); + controller->InsertStyleModule(layer_count, lineset->name, buffer); + controller->toggleLayer(layer_count, true); + MEM_freeN(buffer); + if (!(lineset->selection & FREESTYLE_SEL_EDGE_TYPES) || !lineset->edge_types) { ++use_ridges_and_valleys; - } - if (test_edge_type_conditions(conditions, num_edge_types, logical_and, - FREESTYLE_FE_SUGGESTIVE_CONTOUR, true)) - { ++use_suggestive_contours; - } - if (test_edge_type_conditions(conditions, num_edge_types, logical_and, - FREESTYLE_FE_MATERIAL_BOUNDARY, true)) - { ++use_material_boundaries; } + else { + // conditions for feature edge selection by edge types + for (int i = 0; i < num_edge_types; i++) { + if (!(lineset->edge_types & conditions[i].edge_type)) + conditions[i].value = 0; // no condition specified + else if (!(lineset->exclude_edge_types & conditions[i].edge_type)) + conditions[i].value = 1; // condition: X + else + conditions[i].value = -1; // condition: NOT X + } + // logical operator for the selection conditions + bool logical_and = ((lineset->flags & FREESTYLE_LINESET_FE_AND) != 0); + // negation operator + if (lineset->flags & FREESTYLE_LINESET_FE_NOT) { + // convert an Exclusive condition into an Inclusive equivalent using De Morgan's laws: + // NOT (X OR Y) --> (NOT X) AND (NOT Y) + // NOT (X AND Y) --> (NOT X) OR (NOT Y) + for (int i = 0; i < num_edge_types; i++) + conditions[i].value *= -1; + logical_and = !logical_and; + } + if (test_edge_type_conditions(conditions, num_edge_types, logical_and, + FREESTYLE_FE_RIDGE_VALLEY, true)) + { + ++use_ridges_and_valleys; + } + if (test_edge_type_conditions(conditions, num_edge_types, logical_and, + FREESTYLE_FE_SUGGESTIVE_CONTOUR, true)) + { + ++use_suggestive_contours; + } + if (test_edge_type_conditions(conditions, num_edge_types, logical_and, + FREESTYLE_FE_MATERIAL_BOUNDARY, true)) + { + ++use_material_boundaries; + } + } + layer_count++; } - layer_count++; } - } - controller->setComputeRidgesAndValleysFlag(use_ridges_and_valleys > 0); - controller->setComputeSuggestiveContoursFlag(use_suggestive_contours > 0); - controller->setComputeMaterialBoundariesFlag(use_material_boundaries > 0); - break; + controller->setComputeRidgesAndValleysFlag(use_ridges_and_valleys > 0); + controller->setComputeSuggestiveContoursFlag(use_suggestive_contours > 0); + controller->setComputeMaterialBoundariesFlag(use_material_boundaries > 0); + break; } // set parameters @@ -541,24 +541,24 @@ static int displayed_layer_count(SceneRenderLayer *srl) int count = 0; switch (srl->freestyleConfig.mode) { - case FREESTYLE_CONTROL_SCRIPT_MODE: - for (FreestyleModuleConfig *module = (FreestyleModuleConfig *)srl->freestyleConfig.modules.first; - module; - module = module->next) - { - if (module->script && module->is_displayed) - count++; - } - break; - case FREESTYLE_CONTROL_EDITOR_MODE: - for (FreestyleLineSet *lineset = (FreestyleLineSet *)srl->freestyleConfig.linesets.first; - lineset; - lineset = lineset->next) - { - if (lineset->flags & FREESTYLE_LINESET_ENABLED) - count++; - } - break; + case FREESTYLE_CONTROL_SCRIPT_MODE: + for (FreestyleModuleConfig *module = (FreestyleModuleConfig *)srl->freestyleConfig.modules.first; + module; + module = module->next) + { + if (module->script && module->is_displayed) + count++; + } + break; + case FREESTYLE_CONTROL_EDITOR_MODE: + for (FreestyleLineSet *lineset = (FreestyleLineSet *)srl->freestyleConfig.linesets.first; + lineset; + lineset = lineset->next) + { + if (lineset->flags & FREESTYLE_LINESET_ENABLED) + count++; + } + break; } return count; } diff --git a/source/blender/freestyle/intern/geometry/FastGrid.h b/source/blender/freestyle/intern/geometry/FastGrid.h index 355a6e533990..75624bb9d9c3 100644 --- a/source/blender/freestyle/intern/geometry/FastGrid.h +++ b/source/blender/freestyle/intern/geometry/FastGrid.h @@ -32,7 +32,7 @@ namespace Freestyle { -/*! Class to define a regular grid used for ray casting computations +/*! Class to define a regular grid used for ray casting computations * We don't use a hashtable here. The grid is explicitly stored for faster computations. * However, this might result in significant increase in memory usage (compared to the regular grid) */ diff --git a/source/blender/freestyle/intern/geometry/FitCurve.cpp b/source/blender/freestyle/intern/geometry/FitCurve.cpp index fbfa5b331e66..fd7d63bbd28c 100644 --- a/source/blender/freestyle/intern/geometry/FitCurve.cpp +++ b/source/blender/freestyle/intern/geometry/FitCurve.cpp @@ -61,7 +61,7 @@ static double V2SquaredLength(Vector2 *a) } /* returns length of input vector */ -static double V2Length(Vector2 *a) +static double V2Length(Vector2 *a) { return (sqrt(V2SquaredLength(a))); } @@ -96,7 +96,7 @@ static Vector2 *V2Add(Vector2 *a, Vector2 *b, Vector2 *c) (*c)[0] = (*a)[0] + (*b)[0]; (*c)[1] = (*a)[1] + (*b)[1]; return c; -} +} /* normalizes the input vector and returns it */ static Vector2 *V2Normalize(Vector2 *v) diff --git a/source/blender/freestyle/intern/geometry/FitCurve.h b/source/blender/freestyle/intern/geometry/FitCurve.h index 2268f6be1b76..c402f431c277 100644 --- a/source/blender/freestyle/intern/geometry/FitCurve.h +++ b/source/blender/freestyle/intern/geometry/FitCurve.h @@ -90,7 +90,7 @@ class FitCurveWrapper * Control points of the sets of bezier curve segments. * Each segment is made of 4 points (polynomial degree of curve = 3) * error - * max error tolerance between resulting curve and input data + * max error tolerance between resulting curve and input data */ void FitCurve(std::vector& data, std::vector& oCurve, double error); diff --git a/source/blender/freestyle/intern/geometry/GeomUtils.h b/source/blender/freestyle/intern/geometry/GeomUtils.h index 8f3abf451c94..9e7c629191fd 100644 --- a/source/blender/freestyle/intern/geometry/GeomUtils.h +++ b/source/blender/freestyle/intern/geometry/GeomUtils.h @@ -174,7 +174,7 @@ void fromWorldToImage(const Vec3r& p, Vec3r& q, const real model_view_matrix[4][ */ void fromWorldToImage(const Vec3r& p, Vec3r& q, const real transform[4][4], const int viewport[4]); -/*! Projects from world coordinates to camera coordinates +/*! Projects from world coordinates to camera coordinates * Returns the point's coordinates expressed in the camera's * coordinates system. * p @@ -220,7 +220,7 @@ void fromRetinaToImage(const Vec3r& p, Vec3r& q, const int viewport[4]); */ void fromImageToRetina(const Vec3r& p, Vec3r& q, const int viewport[4]); -/*! computes the coordinates of q in the camera coordinates system, +/*! computes the coordinates of q in the camera coordinates system, * using the known z coordinates of the 3D point. * That means that this method does not inverse any matrices, * it only computes X and Y from x,y and Z) diff --git a/source/blender/freestyle/intern/geometry/Grid.cpp b/source/blender/freestyle/intern/geometry/Grid.cpp index 371c63318dec..61cf70a0aa3b 100644 --- a/source/blender/freestyle/intern/geometry/Grid.cpp +++ b/source/blender/freestyle/intern/geometry/Grid.cpp @@ -242,7 +242,7 @@ bool Grid::nextRayCell(Vec3u& current_cell, Vec3u& next_cell) real t_min, t; unsigned i; - t_min = FLT_MAX; // init tmin with handle of the case where one or 2 _u[i] = 0. + t_min = FLT_MAX; // init tmin with handle of the case where one or 2 _u[i] = 0. unsigned coord = 0; // predominant coord(0=x, 1=y, 2=z) diff --git a/source/blender/freestyle/intern/geometry/GridHelpers.h b/source/blender/freestyle/intern/geometry/GridHelpers.h index 22efdcf1d119..4dd345e9b07d 100644 --- a/source/blender/freestyle/intern/geometry/GridHelpers.h +++ b/source/blender/freestyle/intern/geometry/GridHelpers.h @@ -73,7 +73,7 @@ T closestPointToSegment(const T& P, const T& A, const T& B, real& distance) distance = PPb.norm(); return Pb; // closest point lies on AB -} +} inline Vec3r closestPointOnPolygon(const Vec3r& point, const Polygon3r& poly) { diff --git a/source/blender/freestyle/intern/geometry/SweepLine.h b/source/blender/freestyle/intern/geometry/SweepLine.h index 039ecd7ebf48..98e860862bbb 100644 --- a/source/blender/freestyle/intern/geometry/SweepLine.h +++ b/source/blender/freestyle/intern/geometry/SweepLine.h @@ -216,7 +216,7 @@ struct binary_rule template -class SweepLine +class SweepLine { public: SweepLine() {} @@ -231,7 +231,7 @@ class SweepLine } } - inline void process(Point& p, vector*>& segments, + inline void process(Point& p, vector*>& segments, #if 0 binary_rule,Segment >& binrule = \ binary_rule, Segment >(), diff --git a/source/blender/freestyle/intern/geometry/VecMat.h b/source/blender/freestyle/intern/geometry/VecMat.h index 3c3d40875d03..e7a44e00b1bb 100644 --- a/source/blender/freestyle/intern/geometry/VecMat.h +++ b/source/blender/freestyle/intern/geometry/VecMat.h @@ -150,21 +150,21 @@ class Vec Vec res(v); res += *this; return res; - } + } inline Vec operator-(const Vec& v) const { Vec res(*this); res -= v; return res; - } + } inline Vec operator*(const typename Vec::value_type r) const { Vec res(*this); res *= r; return res; - } + } inline Vec operator/(const typename Vec::value_type r) const { @@ -172,7 +172,7 @@ class Vec if (r) res /= r; return res; - } + } // dot product inline value_type operator*(const Vec& v) const @@ -181,7 +181,7 @@ class Vec for (unsigned int i = 0; i < N; i++) sum += (*this)[i] * v[i]; return sum; - } + } template inline Vec& operator=(const Vec& v) @@ -255,7 +255,7 @@ class Vec if (this->_coord[i] == v[i]) continue; } - return false; + return false; } inline bool operator>(const Vec& v) const @@ -268,7 +268,7 @@ class Vec if (this->_coord[i] == v[i]) continue; } - return false; + return false; } protected: diff --git a/source/blender/freestyle/intern/geometry/matrix_util.cpp b/source/blender/freestyle/intern/geometry/matrix_util.cpp index 5e5854975166..40195361fe09 100644 --- a/source/blender/freestyle/intern/geometry/matrix_util.cpp +++ b/source/blender/freestyle/intern/geometry/matrix_util.cpp @@ -95,7 +95,7 @@ namespace MatrixUtil { // Ugly Fortran-porting trick: indices for v are between 1 and n v--; - // Step 3 : compute the weight of the non diagonal terms + // Step 3 : compute the weight of the non diagonal terms ij = 1; a_norm = 0.0; for (i = 1; i <= n; i++) { @@ -240,7 +240,7 @@ namespace MatrixUtil { index[i] = jj; } - // Step 7: save the eigen vectors + // Step 7: save the eigen vectors // back from Fortran to to C++ v++; diff --git a/source/blender/freestyle/intern/image/GaussianFilter.h b/source/blender/freestyle/intern/image/GaussianFilter.h index 7abd1bc18bcc..fdbfd20d764d 100644 --- a/source/blender/freestyle/intern/image/GaussianFilter.h +++ b/source/blender/freestyle/intern/image/GaussianFilter.h @@ -120,7 +120,7 @@ class GaussianFilter }; /* - + ############################################# ############################################# ############################################# @@ -130,7 +130,7 @@ class GaussianFilter ############################################# ############################################# ############################################# - + */ template diff --git a/source/blender/freestyle/intern/python/BPy_Convert.cpp b/source/blender/freestyle/intern/python/BPy_Convert.cpp index 4e1a0a119aa4..0ac116b1bd49 100644 --- a/source/blender/freestyle/intern/python/BPy_Convert.cpp +++ b/source/blender/freestyle/intern/python/BPy_Convert.cpp @@ -89,7 +89,7 @@ PyObject *Vector_from_Vec3f(Vec3f& vec) float vec_data[3]; // because vec->_coord is protected vec_data[0] = vec.x(); vec_data[1] = vec.y(); - vec_data[2] = vec.z(); + vec_data[2] = vec.z(); return Vector_CreatePyObject(vec_data, 3, NULL); } @@ -356,7 +356,7 @@ PyObject *BPy_SShape_from_SShape(SShape& ss) PyObject *py_ss = SShape_Type.tp_new(&SShape_Type, 0, 0); ((BPy_SShape *)py_ss)->ss = &ss; ((BPy_SShape *)py_ss)->borrowed = true; - return py_ss; + return py_ss; } PyObject *BPy_ViewShape_from_ViewShape(ViewShape& vs) diff --git a/source/blender/freestyle/intern/python/BPy_Convert.h b/source/blender/freestyle/intern/python/BPy_Convert.h index 35c1e58369cd..a0e0b578c101 100644 --- a/source/blender/freestyle/intern/python/BPy_Convert.h +++ b/source/blender/freestyle/intern/python/BPy_Convert.h @@ -40,7 +40,7 @@ using namespace Freestyle::Geometry; #include "../geometry/BBox.h" // FEdge, FEdgeSharp, FEdgeSmooth, SShape, SVertex, FEdgeInternal::SVertexIterator -#include "../view_map/Silhouette.h" +#include "../view_map/Silhouette.h" // Id #include "../system/Id.h" diff --git a/source/blender/freestyle/intern/python/BPy_Freestyle.cpp b/source/blender/freestyle/intern/python/BPy_Freestyle.cpp index 0b09a3c24423..23deb63ce36e 100644 --- a/source/blender/freestyle/intern/python/BPy_Freestyle.cpp +++ b/source/blender/freestyle/intern/python/BPy_Freestyle.cpp @@ -486,7 +486,7 @@ static PyModuleDef module_definition = { PyObject *Freestyle_Init(void) { PyObject *module; - + // initialize modules module = PyModule_Create(&module_definition); if (!module) @@ -509,9 +509,9 @@ PyObject *Freestyle_Init(void) else { printf("Freestyle: couldn't find 'scripts/freestyle/modules', Freestyle won't work properly.\n"); } - + // attach its classes (adding the object types to the module) - + // those classes have to be initialized before the others MediumType_Init(module); Nature_Init(module); diff --git a/source/blender/freestyle/intern/python/BPy_FrsMaterial.cpp b/source/blender/freestyle/intern/python/BPy_FrsMaterial.cpp index 1866058a1514..3695e85cd15e 100644 --- a/source/blender/freestyle/intern/python/BPy_FrsMaterial.cpp +++ b/source/blender/freestyle/intern/python/BPy_FrsMaterial.cpp @@ -157,38 +157,38 @@ static int FrsMaterial_mathutils_get(BaseMathObject *bmo, int subtype) { BPy_FrsMaterial *self = (BPy_FrsMaterial *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_LINE: - bmo->data[0] = self->m->lineR(); - bmo->data[1] = self->m->lineG(); - bmo->data[2] = self->m->lineB(); - bmo->data[3] = self->m->lineA(); - break; - case MATHUTILS_SUBTYPE_DIFFUSE: - bmo->data[0] = self->m->diffuseR(); - bmo->data[1] = self->m->diffuseG(); - bmo->data[2] = self->m->diffuseB(); - bmo->data[3] = self->m->diffuseA(); - break; - case MATHUTILS_SUBTYPE_SPECULAR: - bmo->data[0] = self->m->specularR(); - bmo->data[1] = self->m->specularG(); - bmo->data[2] = self->m->specularB(); - bmo->data[3] = self->m->specularA(); - break; - case MATHUTILS_SUBTYPE_AMBIENT: - bmo->data[0] = self->m->ambientR(); - bmo->data[1] = self->m->ambientG(); - bmo->data[2] = self->m->ambientB(); - bmo->data[3] = self->m->ambientA(); - break; - case MATHUTILS_SUBTYPE_EMISSION: - bmo->data[0] = self->m->emissionR(); - bmo->data[1] = self->m->emissionG(); - bmo->data[2] = self->m->emissionB(); - bmo->data[3] = self->m->emissionA(); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_LINE: + bmo->data[0] = self->m->lineR(); + bmo->data[1] = self->m->lineG(); + bmo->data[2] = self->m->lineB(); + bmo->data[3] = self->m->lineA(); + break; + case MATHUTILS_SUBTYPE_DIFFUSE: + bmo->data[0] = self->m->diffuseR(); + bmo->data[1] = self->m->diffuseG(); + bmo->data[2] = self->m->diffuseB(); + bmo->data[3] = self->m->diffuseA(); + break; + case MATHUTILS_SUBTYPE_SPECULAR: + bmo->data[0] = self->m->specularR(); + bmo->data[1] = self->m->specularG(); + bmo->data[2] = self->m->specularB(); + bmo->data[3] = self->m->specularA(); + break; + case MATHUTILS_SUBTYPE_AMBIENT: + bmo->data[0] = self->m->ambientR(); + bmo->data[1] = self->m->ambientG(); + bmo->data[2] = self->m->ambientB(); + bmo->data[3] = self->m->ambientA(); + break; + case MATHUTILS_SUBTYPE_EMISSION: + bmo->data[0] = self->m->emissionR(); + bmo->data[1] = self->m->emissionG(); + bmo->data[2] = self->m->emissionB(); + bmo->data[3] = self->m->emissionA(); + break; + default: + return -1; } return 0; } @@ -197,23 +197,23 @@ static int FrsMaterial_mathutils_set(BaseMathObject *bmo, int subtype) { BPy_FrsMaterial *self = (BPy_FrsMaterial *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_LINE: - self->m->setLine(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); - break; - case MATHUTILS_SUBTYPE_DIFFUSE: - self->m->setDiffuse(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); - break; - case MATHUTILS_SUBTYPE_SPECULAR: - self->m->setSpecular(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); - break; - case MATHUTILS_SUBTYPE_AMBIENT: - self->m->setAmbient(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); - break; - case MATHUTILS_SUBTYPE_EMISSION: - self->m->setEmission(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_LINE: + self->m->setLine(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); + break; + case MATHUTILS_SUBTYPE_DIFFUSE: + self->m->setDiffuse(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); + break; + case MATHUTILS_SUBTYPE_SPECULAR: + self->m->setSpecular(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); + break; + case MATHUTILS_SUBTYPE_AMBIENT: + self->m->setAmbient(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); + break; + case MATHUTILS_SUBTYPE_EMISSION: + self->m->setEmission(bmo->data[0], bmo->data[1], bmo->data[2], bmo->data[3]); + break; + default: + return -1; } return 0; } @@ -222,38 +222,38 @@ static int FrsMaterial_mathutils_get_index(BaseMathObject *bmo, int subtype, int { BPy_FrsMaterial *self = (BPy_FrsMaterial *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_LINE: - { - const float *color = self->m->line(); - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_SUBTYPE_DIFFUSE: - { - const float *color = self->m->diffuse(); - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_SUBTYPE_SPECULAR: - { - const float *color = self->m->specular(); - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_SUBTYPE_AMBIENT: - { - const float *color = self->m->ambient(); - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_SUBTYPE_EMISSION: - { - const float *color = self->m->emission(); - bmo->data[index] = color[index]; - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_LINE: + { + const float *color = self->m->line(); + bmo->data[index] = color[index]; + } + break; + case MATHUTILS_SUBTYPE_DIFFUSE: + { + const float *color = self->m->diffuse(); + bmo->data[index] = color[index]; + } + break; + case MATHUTILS_SUBTYPE_SPECULAR: + { + const float *color = self->m->specular(); + bmo->data[index] = color[index]; + } + break; + case MATHUTILS_SUBTYPE_AMBIENT: + { + const float *color = self->m->ambient(); + bmo->data[index] = color[index]; + } + break; + case MATHUTILS_SUBTYPE_EMISSION: + { + const float *color = self->m->emission(); + bmo->data[index] = color[index]; + } + break; + default: + return -1; } return 0; } @@ -263,33 +263,33 @@ static int FrsMaterial_mathutils_set_index(BaseMathObject *bmo, int subtype, int BPy_FrsMaterial *self = (BPy_FrsMaterial *)bmo->cb_user; float color[4]; switch (subtype) { - case MATHUTILS_SUBTYPE_LINE: - copy_v4_v4(color, self->m->line()); - color[index] = bmo->data[index]; - self->m->setLine(color[0], color[1], color[2], color[3]); - break; - case MATHUTILS_SUBTYPE_DIFFUSE: - copy_v4_v4(color, self->m->diffuse()); - color[index] = bmo->data[index]; - self->m->setDiffuse(color[0], color[1], color[2], color[3]); - break; - case MATHUTILS_SUBTYPE_SPECULAR: - copy_v4_v4(color, self->m->specular()); - color[index] = bmo->data[index]; - self->m->setSpecular(color[0], color[1], color[2], color[3]); - break; - case MATHUTILS_SUBTYPE_AMBIENT: - copy_v4_v4(color, self->m->ambient()); - color[index] = bmo->data[index]; - self->m->setAmbient(color[0], color[1], color[2], color[3]); - break; - case MATHUTILS_SUBTYPE_EMISSION: - copy_v4_v4(color, self->m->emission()); - color[index] = bmo->data[index]; - self->m->setEmission(color[0], color[1], color[2], color[3]); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_LINE: + copy_v4_v4(color, self->m->line()); + color[index] = bmo->data[index]; + self->m->setLine(color[0], color[1], color[2], color[3]); + break; + case MATHUTILS_SUBTYPE_DIFFUSE: + copy_v4_v4(color, self->m->diffuse()); + color[index] = bmo->data[index]; + self->m->setDiffuse(color[0], color[1], color[2], color[3]); + break; + case MATHUTILS_SUBTYPE_SPECULAR: + copy_v4_v4(color, self->m->specular()); + color[index] = bmo->data[index]; + self->m->setSpecular(color[0], color[1], color[2], color[3]); + break; + case MATHUTILS_SUBTYPE_AMBIENT: + copy_v4_v4(color, self->m->ambient()); + color[index] = bmo->data[index]; + self->m->setAmbient(color[0], color[1], color[2], color[3]); + break; + case MATHUTILS_SUBTYPE_EMISSION: + copy_v4_v4(color, self->m->emission()); + color[index] = bmo->data[index]; + self->m->setEmission(color[0], color[1], color[2], color[3]); + break; + default: + return -1; } return 0; } diff --git a/source/blender/freestyle/intern/python/BPy_IntegrationType.cpp b/source/blender/freestyle/intern/python/BPy_IntegrationType.cpp index 0db25753caa5..548ab529f34f 100644 --- a/source/blender/freestyle/intern/python/BPy_IntegrationType.cpp +++ b/source/blender/freestyle/intern/python/BPy_IntegrationType.cpp @@ -216,7 +216,7 @@ static PyLongObject _IntegrationType_LAST = { int IntegrationType_Init(PyObject *module) { PyObject *m, *d, *f; - + if (module == NULL) return -1; @@ -230,7 +230,7 @@ int IntegrationType_Init(PyObject *module) PyDict_SetItemString(IntegrationType_Type.tp_dict, "MAX", BPy_IntegrationType_MAX); PyDict_SetItemString(IntegrationType_Type.tp_dict, "FIRST", BPy_IntegrationType_FIRST); PyDict_SetItemString(IntegrationType_Type.tp_dict, "LAST", BPy_IntegrationType_LAST); - + m = PyModule_Create(&module_definition); if (m == NULL) return -1; diff --git a/source/blender/freestyle/intern/python/BPy_Interface0D.cpp b/source/blender/freestyle/intern/python/BPy_Interface0D.cpp index 8f23800fb7aa..d592aed749de 100644 --- a/source/blender/freestyle/intern/python/BPy_Interface0D.cpp +++ b/source/blender/freestyle/intern/python/BPy_Interface0D.cpp @@ -59,7 +59,7 @@ int Interface0D_Init(PyObject *module) if (PyType_Ready(&SVertex_Type) < 0) return -1; Py_INCREF(&SVertex_Type); - PyModule_AddObject(module, "SVertex", (PyObject *)&SVertex_Type); + PyModule_AddObject(module, "SVertex", (PyObject *)&SVertex_Type); if (PyType_Ready(&ViewVertex_Type) < 0) return -1; diff --git a/source/blender/freestyle/intern/python/BPy_MediumType.cpp b/source/blender/freestyle/intern/python/BPy_MediumType.cpp index 240f3f2d6e25..ebd9c6822a94 100644 --- a/source/blender/freestyle/intern/python/BPy_MediumType.cpp +++ b/source/blender/freestyle/intern/python/BPy_MediumType.cpp @@ -103,7 +103,7 @@ PyLongObject _BPy_MediumType_OPAQUE_MEDIUM = { //-------------------MODULE INITIALIZATION-------------------------------- int MediumType_Init(PyObject *module) -{ +{ if (module == NULL) return -1; diff --git a/source/blender/freestyle/intern/python/BPy_SShape.cpp b/source/blender/freestyle/intern/python/BPy_SShape.cpp index 9169adf4d9f6..cf4880ad3f7b 100644 --- a/source/blender/freestyle/intern/python/BPy_SShape.cpp +++ b/source/blender/freestyle/intern/python/BPy_SShape.cpp @@ -232,11 +232,11 @@ static PyObject *SShape_vertices_get(BPy_SShape *self, void *UNUSED(closure)) vector< SVertex * >::iterator it; PyObject *py_vertices = PyList_New(vertices.size()); unsigned int i = 0; - + for (it = vertices.begin(); it != vertices.end(); it++) { PyList_SET_ITEM(py_vertices, i++, BPy_SVertex_from_SVertex(*(*it))); } - + return py_vertices; } @@ -252,11 +252,11 @@ static PyObject *SShape_edges_get(BPy_SShape *self, void *UNUSED(closure)) vector< FEdge * >::iterator it; PyObject *py_edges = PyList_New(edges.size()); unsigned int i = 0; - + for (it = edges.begin(); it != edges.end(); it++) { PyList_SET_ITEM(py_edges, i++, Any_BPy_FEdge_from_FEdge(*(*it))); } - + return py_edges; } diff --git a/source/blender/freestyle/intern/python/BPy_StrokeAttribute.cpp b/source/blender/freestyle/intern/python/BPy_StrokeAttribute.cpp index 43313ef52139..fb7eb49127c9 100644 --- a/source/blender/freestyle/intern/python/BPy_StrokeAttribute.cpp +++ b/source/blender/freestyle/intern/python/BPy_StrokeAttribute.cpp @@ -391,17 +391,17 @@ static int StrokeAttribute_mathutils_get(BaseMathObject *bmo, int subtype) { BPy_StrokeAttribute *self = (BPy_StrokeAttribute *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_COLOR: - bmo->data[0] = self->sa->getColorR(); - bmo->data[1] = self->sa->getColorG(); - bmo->data[2] = self->sa->getColorB(); - break; - case MATHUTILS_SUBTYPE_THICKNESS: - bmo->data[0] = self->sa->getThicknessR(); - bmo->data[1] = self->sa->getThicknessL(); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_COLOR: + bmo->data[0] = self->sa->getColorR(); + bmo->data[1] = self->sa->getColorG(); + bmo->data[2] = self->sa->getColorB(); + break; + case MATHUTILS_SUBTYPE_THICKNESS: + bmo->data[0] = self->sa->getThicknessR(); + bmo->data[1] = self->sa->getThicknessL(); + break; + default: + return -1; } return 0; } @@ -410,14 +410,14 @@ static int StrokeAttribute_mathutils_set(BaseMathObject *bmo, int subtype) { BPy_StrokeAttribute *self = (BPy_StrokeAttribute *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_COLOR: - self->sa->setColor(bmo->data[0], bmo->data[1], bmo->data[2]); - break; - case MATHUTILS_SUBTYPE_THICKNESS: - self->sa->setThickness(bmo->data[0], bmo->data[1]); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_COLOR: + self->sa->setColor(bmo->data[0], bmo->data[1], bmo->data[2]); + break; + case MATHUTILS_SUBTYPE_THICKNESS: + self->sa->setThickness(bmo->data[0], bmo->data[1]); + break; + default: + return -1; } return 0; } @@ -426,25 +426,25 @@ static int StrokeAttribute_mathutils_get_index(BaseMathObject *bmo, int subtype, { BPy_StrokeAttribute *self = (BPy_StrokeAttribute *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_COLOR: - switch (index) { - case 0: bmo->data[0] = self->sa->getColorR(); break; - case 1: bmo->data[1] = self->sa->getColorG(); break; - case 2: bmo->data[2] = self->sa->getColorB(); break; + case MATHUTILS_SUBTYPE_COLOR: + switch (index) { + case 0: bmo->data[0] = self->sa->getColorR(); break; + case 1: bmo->data[1] = self->sa->getColorG(); break; + case 2: bmo->data[2] = self->sa->getColorB(); break; + default: + return -1; + } + break; + case MATHUTILS_SUBTYPE_THICKNESS: + switch (index) { + case 0: bmo->data[0] = self->sa->getThicknessR(); break; + case 1: bmo->data[1] = self->sa->getThicknessL(); break; + default: + return -1; + } + break; default: return -1; - } - break; - case MATHUTILS_SUBTYPE_THICKNESS: - switch (index) { - case 0: bmo->data[0] = self->sa->getThicknessR(); break; - case 1: bmo->data[1] = self->sa->getThicknessL(); break; - default: - return -1; - } - break; - default: - return -1; } return 0; } @@ -453,23 +453,23 @@ static int StrokeAttribute_mathutils_set_index(BaseMathObject *bmo, int subtype, { BPy_StrokeAttribute *self = (BPy_StrokeAttribute *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_COLOR: - { - float r = (index == 0) ? bmo->data[0] : self->sa->getColorR(); - float g = (index == 1) ? bmo->data[1] : self->sa->getColorG(); - float b = (index == 2) ? bmo->data[2] : self->sa->getColorB(); - self->sa->setColor(r, g, b); - } - break; - case MATHUTILS_SUBTYPE_THICKNESS: - { - float tr = (index == 0) ? bmo->data[0] : self->sa->getThicknessR(); - float tl = (index == 1) ? bmo->data[1] : self->sa->getThicknessL(); - self->sa->setThickness(tr, tl); - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_COLOR: + { + float r = (index == 0) ? bmo->data[0] : self->sa->getColorR(); + float g = (index == 1) ? bmo->data[1] : self->sa->getColorG(); + float b = (index == 2) ? bmo->data[2] : self->sa->getColorB(); + self->sa->setColor(r, g, b); + } + break; + case MATHUTILS_SUBTYPE_THICKNESS: + { + float tr = (index == 0) ? bmo->data[0] : self->sa->getThicknessR(); + float tl = (index == 1) ? bmo->data[1] : self->sa->getThicknessL(); + self->sa->setThickness(tr, tl); + } + break; + default: + return -1; } return 0; } diff --git a/source/blender/freestyle/intern/python/BPy_StrokeShader.cpp b/source/blender/freestyle/intern/python/BPy_StrokeShader.cpp index 6b4a1872b617..eee48f19e1bf 100644 --- a/source/blender/freestyle/intern/python/BPy_StrokeShader.cpp +++ b/source/blender/freestyle/intern/python/BPy_StrokeShader.cpp @@ -216,7 +216,7 @@ static PyObject *StrokeShader_shade(BPy_StrokeShader *self, PyObject *args, PyOb if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!", (char **)kwlist, &Stroke_Type, &py_s)) return NULL; - + if (typeid(*(self->ss)) == typeid(StrokeShader)) { PyErr_SetString(PyExc_TypeError, "shade method not properly overridden"); return NULL; diff --git a/source/blender/freestyle/intern/python/BPy_UnaryPredicate1D.cpp b/source/blender/freestyle/intern/python/BPy_UnaryPredicate1D.cpp index fc43accabf0d..87e5e7505ca3 100644 --- a/source/blender/freestyle/intern/python/BPy_UnaryPredicate1D.cpp +++ b/source/blender/freestyle/intern/python/BPy_UnaryPredicate1D.cpp @@ -161,9 +161,9 @@ static PyObject *UnaryPredicate1D___call__(BPy_UnaryPredicate1D *self, PyObject if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!", (char **)kwlist, &Interface1D_Type, &py_if1D)) return NULL; - + Interface1D *if1D = ((BPy_Interface1D *)py_if1D)->if1D; - + if (!if1D) { string class_name(Py_TYPE(self)->tp_name); PyErr_SetString(PyExc_RuntimeError, (class_name + " has no Interface1D").c_str()); diff --git a/source/blender/freestyle/intern/python/BPy_ViewShape.cpp b/source/blender/freestyle/intern/python/BPy_ViewShape.cpp index f2f53159fcfd..33c18c3ce801 100644 --- a/source/blender/freestyle/intern/python/BPy_ViewShape.cpp +++ b/source/blender/freestyle/intern/python/BPy_ViewShape.cpp @@ -222,7 +222,7 @@ static int ViewShape_vertices_set(BPy_ViewShape *self, PyObject *value, void *UN { PyObject *item; vector< ViewVertex *> v; - + if (!PyList_Check(value)) { PyErr_SetString(PyExc_TypeError, "value must be a list of ViewVertex objects"); return -1; diff --git a/source/blender/freestyle/intern/python/BinaryPredicate1D/BPy_ViewMapGradientNormBP1D.cpp b/source/blender/freestyle/intern/python/BinaryPredicate1D/BPy_ViewMapGradientNormBP1D.cpp index 2072faa43efe..8d81e5083407 100644 --- a/source/blender/freestyle/intern/python/BinaryPredicate1D/BPy_ViewMapGradientNormBP1D.cpp +++ b/source/blender/freestyle/intern/python/BinaryPredicate1D/BPy_ViewMapGradientNormBP1D.cpp @@ -35,7 +35,7 @@ extern "C" { //------------------------INSTANCE METHODS ---------------------------------- -//ViewMapGradientNormBP1D(int level, IntegrationType iType=MEAN, float sampling=2.0) +//ViewMapGradientNormBP1D(int level, IntegrationType iType=MEAN, float sampling=2.0) static char ViewMapGradientNormBP1D___doc__[] = "Class hierarchy: :class:`freestyle.types.BinaryPredicate1D` > :class:`ViewMapGradientNormBP1D`\n" diff --git a/source/blender/freestyle/intern/python/Director.cpp b/source/blender/freestyle/intern/python/Director.cpp index 9f85e84e297b..f4f02a7026fd 100644 --- a/source/blender/freestyle/intern/python/Director.cpp +++ b/source/blender/freestyle/intern/python/Director.cpp @@ -325,7 +325,7 @@ int Director_BPy_UnaryFunction1D___call__(void *uf1D, void *py_uf1D, Interface1D vec.push_back(b); } ((UnaryFunction1D< vector > *)uf1D)->result = vec; - } + } Py_DECREF(result); return 0; } diff --git a/source/blender/freestyle/intern/python/Director.h b/source/blender/freestyle/intern/python/Director.h index 40576c0ec2ca..6a0ae7dd7049 100644 --- a/source/blender/freestyle/intern/python/Director.h +++ b/source/blender/freestyle/intern/python/Director.h @@ -53,7 +53,7 @@ int Director_BPy_UnaryFunction1D___call__(void *uf1D, void *py_uf1D, Interface1D // UnaryPredicate0D: __call__ int Director_BPy_UnaryPredicate0D___call__(UnaryPredicate0D *up0D, Interface0DIterator& if0D_it); - + // UnaryPredicate1D: __call__ int Director_BPy_UnaryPredicate1D___call__(UnaryPredicate1D *up1D, Interface1D& if1D); diff --git a/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp b/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp index 39919b414231..d83a5a5174ce 100644 --- a/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp +++ b/source/blender/freestyle/intern/python/Interface0D/BPy_SVertex.cpp @@ -158,18 +158,18 @@ static int SVertex_mathutils_get(BaseMathObject *bmo, int subtype) { BPy_SVertex *self = (BPy_SVertex *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_POINT3D: - bmo->data[0] = self->sv->getX(); - bmo->data[1] = self->sv->getY(); - bmo->data[2] = self->sv->getZ(); - break; - case MATHUTILS_SUBTYPE_POINT2D: - bmo->data[0] = self->sv->getProjectedX(); - bmo->data[1] = self->sv->getProjectedY(); - bmo->data[2] = self->sv->getProjectedZ(); - break; - default: - return -1; + case MATHUTILS_SUBTYPE_POINT3D: + bmo->data[0] = self->sv->getX(); + bmo->data[1] = self->sv->getY(); + bmo->data[2] = self->sv->getZ(); + break; + case MATHUTILS_SUBTYPE_POINT2D: + bmo->data[0] = self->sv->getProjectedX(); + bmo->data[1] = self->sv->getProjectedY(); + bmo->data[2] = self->sv->getProjectedZ(); + break; + default: + return -1; } return 0; } @@ -178,20 +178,20 @@ static int SVertex_mathutils_set(BaseMathObject *bmo, int subtype) { BPy_SVertex *self = (BPy_SVertex *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_POINT3D: - { - Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); - self->sv->setPoint3D(p); - } - break; - case MATHUTILS_SUBTYPE_POINT2D: - { - Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); - self->sv->setPoint2D(p); - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_POINT3D: + { + Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); + self->sv->setPoint3D(p); + } + break; + case MATHUTILS_SUBTYPE_POINT2D: + { + Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); + self->sv->setPoint2D(p); + } + break; + default: + return -1; } return 0; } @@ -200,26 +200,26 @@ static int SVertex_mathutils_get_index(BaseMathObject *bmo, int subtype, int ind { BPy_SVertex *self = (BPy_SVertex *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_POINT3D: - switch (index) { - case 0: bmo->data[0] = self->sv->getX(); break; - case 1: bmo->data[1] = self->sv->getY(); break; - case 2: bmo->data[2] = self->sv->getZ(); break; + case MATHUTILS_SUBTYPE_POINT3D: + switch (index) { + case 0: bmo->data[0] = self->sv->getX(); break; + case 1: bmo->data[1] = self->sv->getY(); break; + case 2: bmo->data[2] = self->sv->getZ(); break; + default: + return -1; + } + break; + case MATHUTILS_SUBTYPE_POINT2D: + switch (index) { + case 0: bmo->data[0] = self->sv->getProjectedX(); break; + case 1: bmo->data[1] = self->sv->getProjectedY(); break; + case 2: bmo->data[2] = self->sv->getProjectedZ(); break; + default: + return -1; + } + break; default: return -1; - } - break; - case MATHUTILS_SUBTYPE_POINT2D: - switch (index) { - case 0: bmo->data[0] = self->sv->getProjectedX(); break; - case 1: bmo->data[1] = self->sv->getProjectedY(); break; - case 2: bmo->data[2] = self->sv->getProjectedZ(); break; - default: - return -1; - } - break; - default: - return -1; } return 0; } @@ -228,22 +228,22 @@ static int SVertex_mathutils_set_index(BaseMathObject *bmo, int subtype, int ind { BPy_SVertex *self = (BPy_SVertex *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_POINT3D: - { - Vec3r p(self->sv->point3D()); - p[index] = bmo->data[index]; - self->sv->setPoint3D(p); - } - break; - case MATHUTILS_SUBTYPE_POINT2D: - { - Vec3r p(self->sv->point2D()); - p[index] = bmo->data[index]; - self->sv->setPoint2D(p); - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_POINT3D: + { + Vec3r p(self->sv->point3D()); + p[index] = bmo->data[index]; + self->sv->setPoint3D(p); + } + break; + case MATHUTILS_SUBTYPE_POINT2D: + { + Vec3r p(self->sv->point2D()); + p[index] = bmo->data[index]; + self->sv->setPoint2D(p); + } + break; + default: + return -1; } return 0; } @@ -341,7 +341,7 @@ PyDoc_STRVAR(SVertex_normals_doc, static PyObject *SVertex_normals_get(BPy_SVertex *self, void *UNUSED(closure)) { - PyObject *py_normals; + PyObject *py_normals; set< Vec3r > normals = self->sv->normals(); set< Vec3r >::iterator it; py_normals = PyList_New(normals.size()); diff --git a/source/blender/freestyle/intern/python/Interface0D/CurvePoint/BPy_StrokeVertex.cpp b/source/blender/freestyle/intern/python/Interface0D/CurvePoint/BPy_StrokeVertex.cpp index ba773d4f4cf8..09e33db529dc 100644 --- a/source/blender/freestyle/intern/python/Interface0D/CurvePoint/BPy_StrokeVertex.cpp +++ b/source/blender/freestyle/intern/python/Interface0D/CurvePoint/BPy_StrokeVertex.cpp @@ -186,10 +186,10 @@ static int StrokeVertex_mathutils_get_index(BaseMathObject *bmo, int /*subtype*/ { BPy_StrokeVertex *self = (BPy_StrokeVertex *)bmo->cb_user; switch (index) { - case 0: bmo->data[0] = (float)self->sv->x(); break; - case 1: bmo->data[1] = (float)self->sv->y(); break; - default: - return -1; + case 0: bmo->data[0] = (float)self->sv->x(); break; + case 1: bmo->data[1] = (float)self->sv->y(); break; + default: + return -1; } return 0; } @@ -198,10 +198,10 @@ static int StrokeVertex_mathutils_set_index(BaseMathObject *bmo, int /*subtype*/ { BPy_StrokeVertex *self = (BPy_StrokeVertex *)bmo->cb_user; switch (index) { - case 0: self->sv->setX((real)bmo->data[0]); break; - case 1: self->sv->setY((real)bmo->data[1]); break; - default: - return -1; + case 0: self->sv->setX((real)bmo->data[0]); break; + case 1: self->sv->setY((real)bmo->data[1]); break; + default: + return -1; } return 0; } diff --git a/source/blender/freestyle/intern/python/Interface1D/BPy_Stroke.cpp b/source/blender/freestyle/intern/python/Interface1D/BPy_Stroke.cpp index 5c816bdfea13..9a39db0ee7e9 100644 --- a/source/blender/freestyle/intern/python/Interface1D/BPy_Stroke.cpp +++ b/source/blender/freestyle/intern/python/Interface1D/BPy_Stroke.cpp @@ -314,7 +314,7 @@ static PyObject *Stroke_stroke_vertices_size(BPy_Stroke *self) return PyLong_FromLong(self->s->strokeVerticesSize()); } -static PyMethodDef BPy_Stroke_methods[] = { +static PyMethodDef BPy_Stroke_methods[] = { {"compute_sampling", (PyCFunction)Stroke_compute_sampling, METH_VARARGS | METH_KEYWORDS, Stroke_compute_sampling_doc}, {"resample", (PyCFunction)Stroke_resample, METH_VARARGS | METH_KEYWORDS, Stroke_resample_doc}, diff --git a/source/blender/freestyle/intern/python/Interface1D/BPy_ViewEdge.cpp b/source/blender/freestyle/intern/python/Interface1D/BPy_ViewEdge.cpp index bcae5a2c2a42..9119d8f999ef 100644 --- a/source/blender/freestyle/intern/python/Interface1D/BPy_ViewEdge.cpp +++ b/source/blender/freestyle/intern/python/Interface1D/BPy_ViewEdge.cpp @@ -182,7 +182,7 @@ PyDoc_STRVAR(ViewEdge_viewshape_doc, ":type: :class:`ViewShape`"); static PyObject *ViewEdge_viewshape_get(BPy_ViewEdge *self, void *UNUSED(closure)) -{ +{ ViewShape *vs = self->ve->viewShape(); if (vs) return BPy_ViewShape_from_ViewShape(*vs); diff --git a/source/blender/freestyle/intern/python/Interface1D/FEdge/BPy_FEdgeSharp.cpp b/source/blender/freestyle/intern/python/Interface1D/FEdge/BPy_FEdgeSharp.cpp index acdd59895117..319eee2945e4 100644 --- a/source/blender/freestyle/intern/python/Interface1D/FEdge/BPy_FEdgeSharp.cpp +++ b/source/blender/freestyle/intern/python/Interface1D/FEdge/BPy_FEdgeSharp.cpp @@ -110,24 +110,24 @@ static int FEdgeSharp_mathutils_get(BaseMathObject *bmo, int subtype) { BPy_FEdgeSharp *self = (BPy_FEdgeSharp *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_NORMAL_A: - { - Vec3r p(self->fes->normalA()); - bmo->data[0] = p[0]; - bmo->data[1] = p[1]; - bmo->data[2] = p[2]; - } - break; - case MATHUTILS_SUBTYPE_NORMAL_B: - { - Vec3r p(self->fes->normalB()); - bmo->data[0] = p[0]; - bmo->data[1] = p[1]; - bmo->data[2] = p[2]; - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_NORMAL_A: + { + Vec3r p(self->fes->normalA()); + bmo->data[0] = p[0]; + bmo->data[1] = p[1]; + bmo->data[2] = p[2]; + } + break; + case MATHUTILS_SUBTYPE_NORMAL_B: + { + Vec3r p(self->fes->normalB()); + bmo->data[0] = p[0]; + bmo->data[1] = p[1]; + bmo->data[2] = p[2]; + } + break; + default: + return -1; } return 0; } @@ -136,20 +136,20 @@ static int FEdgeSharp_mathutils_set(BaseMathObject *bmo, int subtype) { BPy_FEdgeSharp *self = (BPy_FEdgeSharp *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_NORMAL_A: - { - Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); - self->fes->setNormalA(p); - } - break; - case MATHUTILS_SUBTYPE_NORMAL_B: - { - Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); - self->fes->setNormalB(p); - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_NORMAL_A: + { + Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); + self->fes->setNormalA(p); + } + break; + case MATHUTILS_SUBTYPE_NORMAL_B: + { + Vec3r p(bmo->data[0], bmo->data[1], bmo->data[2]); + self->fes->setNormalB(p); + } + break; + default: + return -1; } return 0; } @@ -158,20 +158,20 @@ static int FEdgeSharp_mathutils_get_index(BaseMathObject *bmo, int subtype, int { BPy_FEdgeSharp *self = (BPy_FEdgeSharp *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_NORMAL_A: - { - Vec3r p(self->fes->normalA()); - bmo->data[index] = p[index]; - } - break; - case MATHUTILS_SUBTYPE_NORMAL_B: - { - Vec3r p(self->fes->normalB()); - bmo->data[index] = p[index]; - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_NORMAL_A: + { + Vec3r p(self->fes->normalA()); + bmo->data[index] = p[index]; + } + break; + case MATHUTILS_SUBTYPE_NORMAL_B: + { + Vec3r p(self->fes->normalB()); + bmo->data[index] = p[index]; + } + break; + default: + return -1; } return 0; } @@ -180,22 +180,22 @@ static int FEdgeSharp_mathutils_set_index(BaseMathObject *bmo, int subtype, int { BPy_FEdgeSharp *self = (BPy_FEdgeSharp *)bmo->cb_user; switch (subtype) { - case MATHUTILS_SUBTYPE_NORMAL_A: - { - Vec3r p(self->fes->normalA()); - p[index] = bmo->data[index]; - self->fes->setNormalA(p); - } - break; - case MATHUTILS_SUBTYPE_NORMAL_B: - { - Vec3r p(self->fes->normalB()); - p[index] = bmo->data[index]; - self->fes->setNormalB(p); - } - break; - default: - return -1; + case MATHUTILS_SUBTYPE_NORMAL_A: + { + Vec3r p(self->fes->normalA()); + p[index] = bmo->data[index]; + self->fes->setNormalA(p); + } + break; + case MATHUTILS_SUBTYPE_NORMAL_B: + { + Vec3r p(self->fes->normalB()); + p[index] = bmo->data[index]; + self->fes->setNormalB(p); + } + break; + default: + return -1; } return 0; } diff --git a/source/blender/freestyle/intern/python/Iterator/BPy_ChainSilhouetteIterator.cpp b/source/blender/freestyle/intern/python/Iterator/BPy_ChainSilhouetteIterator.cpp index 08cfffec8601..5a6e838dcc60 100644 --- a/source/blender/freestyle/intern/python/Iterator/BPy_ChainSilhouetteIterator.cpp +++ b/source/blender/freestyle/intern/python/Iterator/BPy_ChainSilhouetteIterator.cpp @@ -98,7 +98,7 @@ static int ChainSilhouetteIterator_init(BPy_ChainSilhouetteIterator *self, PyObj bool restrict_to_selection = (!obj1) ? true : bool_from_PyBool(obj1); ViewEdge *begin = (!obj2 || obj2 == Py_None) ? NULL : ((BPy_ViewEdge *)obj2)->ve; bool orientation = (!obj3) ? true : bool_from_PyBool(obj3); - self->cs_it = new ChainSilhouetteIterator(restrict_to_selection, begin, orientation); + self->cs_it = new ChainSilhouetteIterator(restrict_to_selection, begin, orientation); } else { PyErr_SetString(PyExc_TypeError, "invalid argument(s)"); diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DDouble.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DDouble.cpp index e91c62c7d240..1f5444d7bebe 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DDouble.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DDouble.cpp @@ -161,15 +161,15 @@ static int UnaryFunction1DDouble___init__(BPy_UnaryFunction1DDouble *self, PyObj if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_double = new UnaryFunction1D(); else { self->uf1D_double = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_double->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DEdgeNature.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DEdgeNature.cpp index abef3b2676ff..3f0611dba84e 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DEdgeNature.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DEdgeNature.cpp @@ -83,15 +83,15 @@ static int UnaryFunction1DEdgeNature___init__(BPy_UnaryFunction1DEdgeNature *sel if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_edgenature = new UnaryFunction1D(); else { self->uf1D_edgenature = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_edgenature->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DFloat.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DFloat.cpp index 13a001c585bc..b3b27aabade5 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DFloat.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DFloat.cpp @@ -76,15 +76,15 @@ static int UnaryFunction1DFloat___init__(BPy_UnaryFunction1DFloat *self, PyObjec if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_float = new UnaryFunction1D(); else { self->uf1D_float = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_float->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DUnsigned.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DUnsigned.cpp index 4e88020b5c8d..0814eafb18ea 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DUnsigned.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DUnsigned.cpp @@ -83,15 +83,15 @@ static int UnaryFunction1DUnsigned___init__(BPy_UnaryFunction1DUnsigned *self, P if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_unsigned = new UnaryFunction1D(); else { self->uf1D_unsigned = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_unsigned->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec2f.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec2f.cpp index 9a864a3f5797..f7f4fea02ae7 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec2f.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec2f.cpp @@ -89,15 +89,15 @@ static int UnaryFunction1DVec2f___init__(BPy_UnaryFunction1DVec2f *self, PyObjec if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_vec2f = new UnaryFunction1D(); else { self->uf1D_vec2f = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_vec2f->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec3f.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec3f.cpp index 60c581ac845a..980df2c22680 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec3f.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVec3f.cpp @@ -83,15 +83,15 @@ static int UnaryFunction1DVec3f___init__(BPy_UnaryFunction1DVec3f *self, PyObjec if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_vec3f = new UnaryFunction1D(); else { self->uf1D_vec3f = new UnaryFunction1D(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_vec3f->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVectorViewShape.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVectorViewShape.cpp index c15d974e771b..5eba1573d802 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVectorViewShape.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVectorViewShape.cpp @@ -97,16 +97,16 @@ static int UnaryFunction1DVectorViewShape___init__(BPy_UnaryFunction1DVectorView if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) { self->uf1D_vectorviewshape = new UnaryFunction1D< std::vector >(); } else { self->uf1D_vectorviewshape = new UnaryFunction1D< std::vector >(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_vectorviewshape->py_uf1D = (PyObject *)self; - + return 0; } @@ -149,7 +149,7 @@ static PyObject *UnaryFunction1DVectorViewShape___call__(BPy_UnaryFunction1DVect ViewShape *v = self->uf1D_vectorviewshape->result[i]; PyList_SET_ITEM(list, i, v ? BPy_ViewShape_from_ViewShape(*v) : (Py_INCREF(Py_None), Py_None)); } - + return list; } diff --git a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVoid.cpp b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVoid.cpp index 4db28c0db958..7a83a49b9d24 100644 --- a/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVoid.cpp +++ b/source/blender/freestyle/intern/python/UnaryFunction1D/BPy_UnaryFunction1DVoid.cpp @@ -96,15 +96,15 @@ static int UnaryFunction1DVoid___init__(BPy_UnaryFunction1DVoid *self, PyObject if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) return -1; - + if (!obj) self->uf1D_void = new UnaryFunction1D_void(); else { self->uf1D_void = new UnaryFunction1D_void(IntegrationType_from_BPy_IntegrationType(obj)); } - + self->uf1D_void->py_uf1D = (PyObject *)self; - + return 0; } diff --git a/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h b/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h index 8d7bf986bde4..a8fe3d8bbfae 100644 --- a/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h +++ b/source/blender/freestyle/intern/scene_graph/IndexedFaceSet.h @@ -90,7 +90,7 @@ class IndexedFaceSet : public Rep * - TRIANGLES : the face indices describe single triangles * If iCopy != 0, the array is copied; you must desallocate iFaceStyle. Else you must not. * iVIndices, - * Array of vertices indices. + * Array of vertices indices. * The integers contained in this array must be multiple of 3. * If iCopy != 0, the array is copied; you must desallocate iVIndices. Else you must not. * iVISize diff --git a/source/blender/freestyle/intern/scene_graph/LineRep.cpp b/source/blender/freestyle/intern/scene_graph/LineRep.cpp index e7d811139742..a35920a4f4c3 100644 --- a/source/blender/freestyle/intern/scene_graph/LineRep.cpp +++ b/source/blender/freestyle/intern/scene_graph/LineRep.cpp @@ -39,7 +39,7 @@ void LineRep::ComputeBBox() real YMin = _vertices.front()[1]; real ZMin = _vertices.front()[2]; - // parse all the coordinates to find + // parse all the coordinates to find // the XMax, YMax, ZMax vector::iterator v; for (v = _vertices.begin(); v != _vertices.end(); ++v) { diff --git a/source/blender/freestyle/intern/scene_graph/Node.h b/source/blender/freestyle/intern/scene_graph/Node.h index 546458bad489..4ddcadd35427 100644 --- a/source/blender/freestyle/intern/scene_graph/Node.h +++ b/source/blender/freestyle/intern/scene_graph/Node.h @@ -104,7 +104,7 @@ class Node : public BaseObject protected: -private: +private: BBox _BBox; #ifdef WITH_CXX_GUARDEDALLOC diff --git a/source/blender/freestyle/intern/scene_graph/NodeCamera.h b/source/blender/freestyle/intern/scene_graph/NodeCamera.h index 78c34fdef6d4..c2f70d514a8b 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeCamera.h +++ b/source/blender/freestyle/intern/scene_graph/NodeCamera.h @@ -52,7 +52,7 @@ class NodeCamera : public Node } CameraType; /*! Default matrices: Identity for both projection and modelview. */ - NodeCamera(CameraType camera_type = GENERIC); + NodeCamera(CameraType camera_type = GENERIC); #if 0 /* UNUSED, gives warning in gcc */ NodeCamera(const NodeCamera& iBrother); #endif diff --git a/source/blender/freestyle/intern/scene_graph/NodeGroup.h b/source/blender/freestyle/intern/scene_graph/NodeGroup.h index 69c8a2c8f3b6..e8e58b0915ee 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeGroup.h +++ b/source/blender/freestyle/intern/scene_graph/NodeGroup.h @@ -48,7 +48,7 @@ class NodeGroup : public Node /*! Adds a child. Makes a addRef on the iChild reference counter */ virtual void AddChild(Node *iChild); - /*! destroys all the underlying nodes + /*! destroys all the underlying nodes * Returns the reference counter after having done a release() */ virtual int destroy(); diff --git a/source/blender/freestyle/intern/scene_graph/NodeLight.cpp b/source/blender/freestyle/intern/scene_graph/NodeLight.cpp index 5a54bc09891e..9e15f6c1eeeb 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeLight.cpp +++ b/source/blender/freestyle/intern/scene_graph/NodeLight.cpp @@ -37,7 +37,7 @@ NodeLight::NodeLight() : Node() _number = 7; } else { - _number = numberOfLights; + _number = numberOfLights; numberOfLights++; } @@ -61,7 +61,7 @@ NodeLight::NodeLight(NodeLight& iBrother) : Node(iBrother) _number = 7; } else { - _number = numberOfLights; + _number = numberOfLights; numberOfLights++; } diff --git a/source/blender/freestyle/intern/scene_graph/NodeLight.h b/source/blender/freestyle/intern/scene_graph/NodeLight.h index c633a6bc7b89..10d6f6578722 100644 --- a/source/blender/freestyle/intern/scene_graph/NodeLight.h +++ b/source/blender/freestyle/intern/scene_graph/NodeLight.h @@ -41,7 +41,7 @@ using namespace Geometry; class NodeLight : public Node { public: - NodeLight(); + NodeLight(); NodeLight(NodeLight& iBrother); virtual ~NodeLight() {} diff --git a/source/blender/freestyle/intern/scene_graph/Rep.h b/source/blender/freestyle/intern/scene_graph/Rep.h index 773eb2d32789..4c8017e162d2 100644 --- a/source/blender/freestyle/intern/scene_graph/Rep.h +++ b/source/blender/freestyle/intern/scene_graph/Rep.h @@ -97,7 +97,7 @@ class Rep : public BaseObject return *this; } - virtual ~Rep() + virtual ~Rep() { if (0 != _FrsMaterial) { delete _FrsMaterial; diff --git a/source/blender/freestyle/intern/scene_graph/TriangleRep.h b/source/blender/freestyle/intern/scene_graph/TriangleRep.h index d101cfd79880..353555b28028 100644 --- a/source/blender/freestyle/intern/scene_graph/TriangleRep.h +++ b/source/blender/freestyle/intern/scene_graph/TriangleRep.h @@ -28,7 +28,7 @@ * \date 16/12/2002 */ -//! inherits from class Rep +//! inherits from class Rep #include "Rep.h" namespace Freestyle { diff --git a/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h b/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h index 48d5cd4803e7..87f132b1ff3c 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h +++ b/source/blender/freestyle/intern/stroke/AdvancedFunctions0D.h @@ -109,7 +109,7 @@ class ReadMapPixelF0D : public UnaryFunction0D int _level; public: - /*! Builds the functor from name of the + /*! Builds the functor from name of the * Map that must be read. * \param iMapName * The name of the map. @@ -171,7 +171,7 @@ class ReadCompleteViewMapPixelF0D : public UnaryFunction0D int _level; public: - /*! Builds the functor + /*! Builds the functor * \param level * The level of the pyramid from which the pixel must be read. */ @@ -199,7 +199,7 @@ class GetViewMapGradientNormF0D: public UnaryFunction0D< float> float _step; public: - /*! Builds the functor + /*! Builds the functor * \param level * The level of the pyramid from which the pixel must be read. */ diff --git a/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.cpp b/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.cpp index ed527080f366..247217791a5c 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.cpp +++ b/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.cpp @@ -114,7 +114,7 @@ int GetDirectionalViewMapDensityF1D::operator()(Interface1D& inter) //soc unsigned size; result = integrate(_fun, inter.pointsBegin(_sampling), inter.pointsEnd(_sampling), _integration); return 0; -} +} int GetCompleteViewMapDensityF1D::operator()(Interface1D& inter) { diff --git a/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.h b/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.h index 9df690cf5b04..ec698ca5e685 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.h +++ b/source/blender/freestyle/intern/stroke/AdvancedFunctions1D.h @@ -135,7 +135,7 @@ class GetCompleteViewMapDensityF1D : public UnaryFunction1D public: /*! Builds the functor. * \param level - * The level of the pyramid from which + * The level of the pyramid from which * the pixel must be read. * \param iType * The integration method used to compute diff --git a/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h b/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h index a9ef49aa8027..5ba96f31272c 100644 --- a/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h +++ b/source/blender/freestyle/intern/stroke/AdvancedStrokeShaders.h @@ -61,7 +61,7 @@ class CalligraphicShader : public StrokeShader protected: real _maxThickness; real _minThickness; - Vec2f _orientation; + Vec2f _orientation; bool _clamp; }; diff --git a/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h b/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h index cc935a7e311e..d3d19beba95a 100644 --- a/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h +++ b/source/blender/freestyle/intern/stroke/BasicStrokeShaders.h @@ -405,7 +405,7 @@ class ColorNoiseShader : public StrokeShader class BackboneStretcherShader : public StrokeShader { private: - float _amount; + float _amount; public: /*! Builds the shader. @@ -524,7 +524,7 @@ class PolygonalizationShader : public StrokeShader * The smaller, the closer the new stroke to the orinal one. * This error corresponds to the maximum distance between the new stroke and the old one. */ - PolygonalizationShader(float iError) : StrokeShader() + PolygonalizationShader(float iError) : StrokeShader() { _error = iError; } @@ -594,7 +594,7 @@ class TipRemoverShader : public StrokeShader virtual int shade(Stroke &stroke) const; protected: - real _tipLength; + real _tipLength; }; /*! [ Texture Shader ]. diff --git a/source/blender/freestyle/intern/stroke/Canvas.h b/source/blender/freestyle/intern/stroke/Canvas.h index 5919344b6e01..6d84ff995d2d 100644 --- a/source/blender/freestyle/intern/stroke/Canvas.h +++ b/source/blender/freestyle/intern/stroke/Canvas.h @@ -128,7 +128,7 @@ class Canvas void Clear(); /* Erases the layers */ - virtual void Erase(); + virtual void Erase(); /* Reads a pixel area from the canvas */ virtual void readColorPixels(int x, int y, int w, int h, RGBImage& oImage) const = 0; diff --git a/source/blender/freestyle/intern/stroke/ChainingIterators.h b/source/blender/freestyle/intern/stroke/ChainingIterators.h index 4ece24c5ecf6..310409f160fc 100644 --- a/source/blender/freestyle/intern/stroke/ChainingIterators.h +++ b/source/blender/freestyle/intern/stroke/ChainingIterators.h @@ -80,7 +80,7 @@ class AdjacencyIterator : public Iterator { _internalIterator = iBrother._internalIterator; _restrictToSelection = iBrother._restrictToSelection; - _restrictToUnvisited = iBrother._restrictToUnvisited; + _restrictToUnvisited = iBrother._restrictToUnvisited; return *this; } @@ -289,7 +289,7 @@ class ChainSilhouetteIterator : public ChainingIterator */ virtual int traverse(const AdjacencyIterator& it); - /*! Inits the iterator context */ + /*! Inits the iterator context */ virtual int init() { return 0; diff --git a/source/blender/freestyle/intern/stroke/ContextFunctions.h b/source/blender/freestyle/intern/stroke/ContextFunctions.h index d8b780e77a0f..97710437e47a 100644 --- a/source/blender/freestyle/intern/stroke/ContextFunctions.h +++ b/source/blender/freestyle/intern/stroke/ContextFunctions.h @@ -64,7 +64,7 @@ BBox GetBorderCF(); void LoadMapCF(const char *iFileName, const char *iMapName, unsigned iNbLevels = 4, float iSigma = 1.0f); // ReadMapPixel -/*! Reads a pixel in a user-defined map +/*! Reads a pixel in a user-defined map * \return the floating value stored for that pixel * \param iMapName * The name of the map diff --git a/source/blender/freestyle/intern/stroke/Curve.cpp b/source/blender/freestyle/intern/stroke/Curve.cpp index a8dbce84971e..52fd780ee431 100644 --- a/source/blender/freestyle/intern/stroke/Curve.cpp +++ b/source/blender/freestyle/intern/stroke/Curve.cpp @@ -317,7 +317,7 @@ float CurvePoint::shape_importance() const if (__A == 0) return __B->shape_importance(); return __A->shape_importance(); -} +} const unsigned CurvePoint::qi() const diff --git a/source/blender/freestyle/intern/stroke/Curve.h b/source/blender/freestyle/intern/stroke/Curve.h index 726b238c74be..04cc2fbfd39a 100644 --- a/source/blender/freestyle/intern/stroke/Curve.h +++ b/source/blender/freestyle/intern/stroke/Curve.h @@ -94,7 +94,7 @@ class CurvePoint : public Interface0D return _Point3d.z(); } - /*! Returns the 3D point. */ + /*! Returns the 3D point. */ virtual Vec3r getPoint3D() const { return _Point3d; @@ -118,7 +118,7 @@ class CurvePoint : public Interface0D return _Point2d.z(); } - /*! Returns the 2D point. */ + /*! Returns the 2D point. */ virtual Vec2r getPoint2D() const { return Vec2r(_Point2d.x(), _Point2d.y()); @@ -444,7 +444,7 @@ class Curve : public Interface1D } /*! Adds a single vertex (SVertex) at the end of the Curve */ - inline void push_vertex_back(SVertex *iVertex) + inline void push_vertex_back(SVertex *iVertex) { if (!_Vertices.empty()) { Vec3r vec_tmp(iVertex->point2d() - _Vertices.back()->point2d()); @@ -456,7 +456,7 @@ class Curve : public Interface1D } /*! Adds a single vertex (CurvePoint) at the front of the Curve */ - inline void push_vertex_front(Vertex *iVertex) + inline void push_vertex_front(Vertex *iVertex) { if (!_Vertices.empty()) { Vec3r vec_tmp(iVertex->point2d() - _Vertices.front()->point2d()); @@ -468,7 +468,7 @@ class Curve : public Interface1D } /*! Adds a single vertex (SVertex) at the front of the Curve */ - inline void push_vertex_front(SVertex *iVertex) + inline void push_vertex_front(SVertex *iVertex) { if (!_Vertices.empty()) { Vec3r vec_tmp(iVertex->point2d() - _Vertices.front()->point2d()); diff --git a/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h b/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h index 4142117c361f..726c80d889cb 100644 --- a/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h +++ b/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h @@ -39,7 +39,7 @@ class CurvePoint_const_traits : public Const_traits public: typedef deque vertex_container; typedef vertex_container::const_iterator vertex_container_iterator; - typedef SVertex vertex_type; + typedef SVertex vertex_type; }; class CurvePoint_nonconst_traits : public Nonconst_traits @@ -47,7 +47,7 @@ class CurvePoint_nonconst_traits : public Nonconst_traits public: typedef deque vertex_container; typedef vertex_container::iterator vertex_container_iterator; - typedef SVertex vertex_type; + typedef SVertex vertex_type; }; /**********************************/ @@ -325,7 +325,7 @@ class __point_iterator : public IteratorBase& func, UnaryP if (newId == 0) { newId = new Id(_curve->getId()); _curve->setSplittingId(newId); - } + } Chain *new_curve_a = new Chain(*newId); newId->setSecond(newId->getSecond() + 1); @@ -791,9 +791,9 @@ int Operators::recursiveSplit(UnaryFunction0D& func, UnaryPredicate1D& p if (!splitted_chains.empty()) { for (cit = splitted_chains.begin(), citend = splitted_chains.end(); cit != citend; ++cit) { delete (*cit); - } + } splitted_chains.clear(); - } + } _current_chains_set.clear(); #if 0 @@ -1036,7 +1036,7 @@ static Stroke *createStroke(Interface1D& inter) Vec2r previous = current; SVertex *sv; CurvePoint *cp; - StrokeVertex *stroke_vertex = NULL; + StrokeVertex *stroke_vertex = NULL; bool hasSingularity = false; do { diff --git a/source/blender/freestyle/intern/stroke/Operators.h b/source/blender/freestyle/intern/stroke/Operators.h index c7b0e3f8b81f..4130f9b370e8 100644 --- a/source/blender/freestyle/intern/stroke/Operators.h +++ b/source/blender/freestyle/intern/stroke/Operators.h @@ -94,7 +94,7 @@ class Operators { * \param pred * The predicate on the ViewEdge that expresses the stopping condition. */ - static int chain(ViewEdgeInternal::ViewEdgeIterator& it, UnaryPredicate1D& pred); + static int chain(ViewEdgeInternal::ViewEdgeIterator& it, UnaryPredicate1D& pred); /*! Builds a set of chains from the current set of ViewEdges. * Each ViewEdge of the current list potentially starts a new chain. The chaining operator then iterates over diff --git a/source/blender/freestyle/intern/stroke/Stroke.h b/source/blender/freestyle/intern/stroke/Stroke.h index db96a27e073b..60b8c21067f1 100644 --- a/source/blender/freestyle/intern/stroke/Stroke.h +++ b/source/blender/freestyle/intern/stroke/Stroke.h @@ -565,7 +565,7 @@ class Stroke : public Interface1D * \param iBegin * The iterator pointing to the first vertex. * \param iEnd - * The iterator pointing to the end of the vertex list. + * The iterator pointing to the end of the vertex list. */ template Stroke(InputVertexIterator iBegin, InputVertexIterator iEnd); @@ -601,7 +601,7 @@ class Stroke : public Interface1D * Resamples the curve with a given sampling. * If this sampling is < to the actual sampling value, no resampling is done. * \param iSampling - * The new sampling value. + * The new sampling value. */ int Resample(float iSampling); @@ -609,7 +609,7 @@ class Stroke : public Interface1D */ void RemoveAllVertices(); - /*! Removes the stroke vertex iVertex + /*! Removes the stroke vertex iVertex * from the stroke. * The length and curvilinear abscissa are updated * consequently. diff --git a/source/blender/freestyle/intern/stroke/StrokeRenderer.h b/source/blender/freestyle/intern/stroke/StrokeRenderer.h index 868f61224dea..054182a558a9 100644 --- a/source/blender/freestyle/intern/stroke/StrokeRenderer.h +++ b/source/blender/freestyle/intern/stroke/StrokeRenderer.h @@ -112,7 +112,7 @@ class TextureManager static string _patterns_path; static string _brushes_path; unsigned int _defaultTextureId; - + #ifdef WITH_CXX_GUARDEDALLOC MEM_CXX_CLASS_ALLOC_FUNCS("Freestyle:TextureManager") #endif diff --git a/source/blender/freestyle/intern/stroke/StrokeRep.cpp b/source/blender/freestyle/intern/stroke/StrokeRep.cpp index 028127897ff8..81ef46e5b3b0 100644 --- a/source/blender/freestyle/intern/stroke/StrokeRep.cpp +++ b/source/blender/freestyle/intern/stroke/StrokeRep.cpp @@ -741,7 +741,7 @@ StrokeRep::StrokeRep(Stroke *iStroke) #if 0 _averageTextureAlpha = 0.5; //default value if (_strokeType == OIL_STROKE) - _averageTextureAlpha = 0.75; + _averageTextureAlpha = 0.75; if (_strokeType >= NO_BLEND_STROKE) _averageTextureAlpha = 1.0; #endif diff --git a/source/blender/freestyle/intern/stroke/TextStrokeRenderer.h b/source/blender/freestyle/intern/stroke/TextStrokeRenderer.h index 02f7177b95c6..dd0b945e4d37 100644 --- a/source/blender/freestyle/intern/stroke/TextStrokeRenderer.h +++ b/source/blender/freestyle/intern/stroke/TextStrokeRenderer.h @@ -28,7 +28,7 @@ // Purpose : Class to define the text rendering of a stroke // Format: // x y width height // bbox -// //list of vertices : +// //list of vertices : // t x y z t1 t2 r g b alpha ... // ... // Date of creation : 01/14/2005 diff --git a/source/blender/freestyle/intern/system/Id.h b/source/blender/freestyle/intern/system/Id.h index 8b028cdb3da5..279730f7934b 100644 --- a/source/blender/freestyle/intern/system/Id.h +++ b/source/blender/freestyle/intern/system/Id.h @@ -78,7 +78,7 @@ class Id _first = iBrother._first; _second = iBrother._second; return *this; - } + } /*! Returns the first Id number */ id_type getFirst() const diff --git a/source/blender/freestyle/intern/system/PythonInterpreter.h b/source/blender/freestyle/intern/system/PythonInterpreter.h index 79ba9421cdad..4f5e94ef7a0d 100644 --- a/source/blender/freestyle/intern/system/PythonInterpreter.h +++ b/source/blender/freestyle/intern/system/PythonInterpreter.h @@ -81,7 +81,7 @@ class PythonInterpreter : public Interpreter bool ok = BPY_execute_filepath(_context, fn, reports); #else bool ok; - Text *text = BKE_text_load(&_freestyle_bmain, fn, G.main->name); + Text *text = BKE_text_load(&_freestyle_bmain, fn, G_MAIN->name); if (text) { ok = BPY_execute_text(_context, text, reports, false); BKE_libblock_delete(&_freestyle_bmain, text); diff --git a/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp b/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp index 3243c4d1fb79..79de3ca497db 100644 --- a/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp +++ b/source/blender/freestyle/intern/view_map/ArbitraryGridDensityProvider.cpp @@ -49,7 +49,7 @@ ArbitraryGridDensityProvider::ArbitraryGridDensityProvider(OccluderSource& sourc } ArbitraryGridDensityProvider::ArbitraryGridDensityProvider(OccluderSource& source, unsigned numCells) -: GridDensityProvider(source), numCells(numCells) +: GridDensityProvider(source), numCells(numCells) { real proscenium[4]; calculateOptimalProscenium(source, proscenium); diff --git a/source/blender/freestyle/intern/view_map/CulledOccluderSource.cpp b/source/blender/freestyle/intern/view_map/CulledOccluderSource.cpp index d98a3238a25b..ae0d83a3551a 100644 --- a/source/blender/freestyle/intern/view_map/CulledOccluderSource.cpp +++ b/source/blender/freestyle/intern/view_map/CulledOccluderSource.cpp @@ -199,7 +199,7 @@ void CulledOccluderSource::cullViewEdges(ViewMap& viewMap, bool extensiveFEdgeSe fe = fe->nextEdge(); } - // If bestOccluderTarget was not found inside the occluder proscenium, + // If bestOccluderTarget was not found inside the occluder proscenium, // we need to expand the occluder proscenium to include it. if ((*ve)->isInImage() && bestOccluderTarget != NULL && ! bestOccluderTargetFound) { // Expand occluder proscenium to enclose bestOccluderTarget @@ -249,7 +249,7 @@ void CulledOccluderSource::cullViewEdges(ViewMap& viewMap, bool extensiveFEdgeSe FEdge *festart = (*ve)->fedgeA(); FEdge *fe = festart; do { - // If not (already) visible and center point inside occluder proscenium, + // If not (already) visible and center point inside occluder proscenium, if (!fe->isInImage() && insideProscenium(occluderProscenium, fe->center2d())) { // Use the feature edge for visibility determination fe->setIsInImage(true); diff --git a/source/blender/freestyle/intern/view_map/FEdgeXDetector.cpp b/source/blender/freestyle/intern/view_map/FEdgeXDetector.cpp index a97e60d5f60d..d179e8b7f181 100644 --- a/source/blender/freestyle/intern/view_map/FEdgeXDetector.cpp +++ b/source/blender/freestyle/intern/view_map/FEdgeXDetector.cpp @@ -193,7 +193,7 @@ void FEdgeXDetector::computeCurvatures(WXVertex *vertex) Vec3r e1, n, v; // one vertex curvature info : CurvatureInfo *C; - float radius = _sphereRadius * _meanEdgeSize; + float radius = _sphereRadius * _meanEdgeSize; // view independent stuff if (_computeViewIndependent) { @@ -369,7 +369,7 @@ void FEdgeXDetector::processCreaseShape(WXShape *iWShape) if (!_computeViewIndependent) return; - // Make a pass on the edges to detect the CREASE + // Make a pass on the edges to detect the CREASE vector::iterator we, weend; vector &wedges = iWShape->getEdgeList(); for (we = wedges.begin(), weend = wedges.end(); we != weend; ++we) { @@ -573,7 +573,8 @@ void FEdgeXDetector::ProcessSuggestiveContourFace(WXFace *iFace) real threshold = _meanKr; if (faceLayer->nPosDotP()!=numVertices) { if ((fabs(faceLayer->dotP(0)) < threshold) && (fabs(faceLayer->dotP(1)) < threshold) && - (fabs(faceLayer->dotP(2)) < threshold)) { + (fabs(faceLayer->dotP(2)) < threshold)) + { faceLayer->ReplaceDotP(0, 0); faceLayer->ReplaceDotP(1, 0); faceLayer->ReplaceDotP(2, 0); diff --git a/source/blender/freestyle/intern/view_map/Functions0D.cpp b/source/blender/freestyle/intern/view_map/Functions0D.cpp index f47e5ff16d5d..15319e54f664 100644 --- a/source/blender/freestyle/intern/view_map/Functions0D.cpp +++ b/source/blender/freestyle/intern/view_map/Functions0D.cpp @@ -250,7 +250,7 @@ int Curvature2DAngleF0D::operator()(Interface0DIterator& iter) if ((N1.norm() == 0) && (N2.norm() == 0)) { Exception::raiseException(); result = 0; - return -1; + return -1; } double cosin = N1 * N2; if (cosin > 1) diff --git a/source/blender/freestyle/intern/view_map/Functions1D.h b/source/blender/freestyle/intern/view_map/Functions1D.h index d2a5870f27ab..f3c8957a8044 100644 --- a/source/blender/freestyle/intern/view_map/Functions1D.h +++ b/source/blender/freestyle/intern/view_map/Functions1D.h @@ -101,7 +101,7 @@ class UnaryFunction1D } /*! The operator (). - * \param inter + * \param inter * The Interface1D on which we wish to evaluate the function. * \return the result of the function of type T. */ diff --git a/source/blender/freestyle/intern/view_map/Silhouette.h b/source/blender/freestyle/intern/view_map/Silhouette.h index 9d373107bfa2..44bce375a752 100644 --- a/source/blender/freestyle/intern/view_map/Silhouette.h +++ b/source/blender/freestyle/intern/view_map/Silhouette.h @@ -102,7 +102,7 @@ class SVertex : public Interface0D return _Point3D.z(); } - /*! Returns the 3D point. */ + /*! Returns the 3D point. */ virtual Vec3r getPoint3D() const { return _Point3D; @@ -126,7 +126,7 @@ class SVertex : public Interface0D return _Point2D.z(); } - /*! Returns the 2D point. */ + /*! Returns the 2D point. */ virtual Vec2r getPoint2D() const { return Vec2r(_Point2D.x(), _Point2D.y()); @@ -144,16 +144,16 @@ class SVertex : public Interface0D /*! Returns the nature of the vertex .*/ virtual Nature::VertexNature getNature() const; - /*! Cast the Interface0D in SVertex if it can be. */ + /*! Cast the Interface0D in SVertex if it can be. */ virtual SVertex *castToSVertex(); - /*! Cast the Interface0D in ViewVertex if it can be. */ + /*! Cast the Interface0D in ViewVertex if it can be. */ virtual ViewVertex *castToViewVertex(); - /*! Cast the Interface0D in NonTVertex if it can be. */ + /*! Cast the Interface0D in NonTVertex if it can be. */ virtual NonTVertex *castToNonTVertex(); - /*! Cast the Interface0D in TVertex if it can be. */ + /*! Cast the Interface0D in TVertex if it can be. */ virtual TVertex *castToTVertex(); public: @@ -163,7 +163,7 @@ class SVertex : public Interface0D Id _Id; Vec3r _Point3D; Vec3r _Point2D; - set _Normals; + set _Normals; vector _FEdges; // the edges containing this vertex SShape *_Shape; // the shape to which belongs the vertex ViewVertex *_pViewVertex; // The associated viewvertex, in case there is one. @@ -1291,10 +1291,10 @@ class FEdgeSmooth : public FEdge unsigned _FrsMaterialIndex; #if 0 bool _hasVisibilityPoint; - Vec3r _VisibilityPointA; // The edge on which the visibility will be computed represented + Vec3r _VisibilityPointA; // The edge on which the visibility will be computed represented Vec3r _VisibilityPointB; // using its 2 extremity points A and B #endif - void *_Face; // In case of exact silhouette, Face is the WFace crossed by Fedge + void *_Face; // In case of exact silhouette, Face is the WFace crossed by Fedge // NOT HANDLED BY THE COPY CONSTRUCTEUR bool _FaceMark; @@ -1418,7 +1418,7 @@ class SShape const char *_Name; const char *_LibraryPath; BBox _BBox; - vector _FrsMaterials; + vector _FrsMaterials; float _importance; diff --git a/source/blender/freestyle/intern/view_map/SphericalGrid.h b/source/blender/freestyle/intern/view_map/SphericalGrid.h index 5a94a84705da..2310f5ffe2fc 100644 --- a/source/blender/freestyle/intern/view_map/SphericalGrid.h +++ b/source/blender/freestyle/intern/view_map/SphericalGrid.h @@ -173,7 +173,7 @@ class SphericalGrid // Accessors: bool orthographicProjection() const; const Vec3r& viewpoint() const; - bool enableQI() const; + bool enableQI() const; private: void getCellCoordinates(const Vec3r& point, unsigned& x, unsigned& y); @@ -317,7 +317,7 @@ inline void SphericalGrid::Iterator::reportDepth(Vec3r origin, Vec3r u, real t) // If the current occluder is the best occludee so far, save it. if (! _foundOccludee || _occludeeDepth > depth) { markCurrentOccludeeCandidate(depth); - } + } } else { #if SPHERICAL_GRID_LOGGING diff --git a/source/blender/freestyle/intern/view_map/SteerableViewMap.cpp b/source/blender/freestyle/intern/view_map/SteerableViewMap.cpp index 4f5b4cba7799..34d8ecb3a8d0 100644 --- a/source/blender/freestyle/intern/view_map/SteerableViewMap.cpp +++ b/source/blender/freestyle/intern/view_map/SteerableViewMap.cpp @@ -91,7 +91,7 @@ void SteerableViewMap::Clear() } delete[] _imagesPyramids; _imagesPyramids = 0; - } + } if (!_mapping.empty()) { for (map::iterator m = _mapping.begin(), mend = _mapping.end(); m != mend; ++m) { delete[] (*m).second; @@ -170,7 +170,7 @@ unsigned SteerableViewMap::getSVMNumber(unsigned id) map::iterator o = _mapping.find(id); if (o != _mapping.end()) { double *wvalues = (*o).second; - double maxw = 0.0; + double maxw = 0.0; unsigned winner = _nbOrientations + 1; for (unsigned i = 0; i < _nbOrientations; ++i) { double w = wvalues[i]; diff --git a/source/blender/freestyle/intern/view_map/SteerableViewMap.h b/source/blender/freestyle/intern/view_map/SteerableViewMap.h index 3a6606277766..0327b4a460ec 100644 --- a/source/blender/freestyle/intern/view_map/SteerableViewMap.h +++ b/source/blender/freestyle/intern/view_map/SteerableViewMap.h @@ -48,7 +48,7 @@ class FEdge; class ImagePyramid; class GrayImage; -/*! This class checks for every FEdge in which steerable it belongs and stores the mapping allowing to retrieve +/*! This class checks for every FEdge in which steerable it belongs and stores the mapping allowing to retrieve * this information from the FEdge Id. */ class SteerableViewMap diff --git a/source/blender/freestyle/intern/view_map/ViewMap.cpp b/source/blender/freestyle/intern/view_map/ViewMap.cpp index 52769413e792..01a6edad9736 100644 --- a/source/blender/freestyle/intern/view_map/ViewMap.cpp +++ b/source/blender/freestyle/intern/view_map/ViewMap.cpp @@ -95,7 +95,7 @@ ViewShape *ViewMap::viewShape(unsigned id) void ViewMap::AddViewShape(ViewShape *iVShape) { - _shapeIdToIndex[iVShape->getId().getFirst()] = _VShapes.size(); + _shapeIdToIndex[iVShape->getId().getFirst()] = _VShapes.size(); _VShapes.push_back(iVShape); } @@ -305,13 +305,13 @@ static bool ViewEdgeComp(ViewVertex::directedViewEdge& dve1, ViewVertex::directe if (v1.y() > 0) { if (v2.y() < 0) return true; - else + else return (v1.x() > v2.x()); } else { if (v2.y() > 0) return false; - else + else return (v1.x() < v2.x()); } return false; @@ -387,7 +387,7 @@ void TVertex::setBackEdgeB(ViewEdge *iBackEdgeB, bool incoming) void TVertex::Replace(ViewEdge *iOld, ViewEdge *iNew) { - // theoritically, we only replace edges for which this + // theoritically, we only replace edges for which this // view vertex is the B vertex if ((iOld == _FrontEdgeA.first) && (_FrontEdgeA.first->B() == this)) { _FrontEdgeA.first = iNew; @@ -501,7 +501,7 @@ ViewVertexInternal::orientedViewEdgeIterator TVertex::edgesIterator(ViewEdge *iE /**********************************/ /* */ /* */ -/* NonTVertex */ +/* NonTVertex */ /* */ /* */ /**********************************/ diff --git a/source/blender/freestyle/intern/view_map/ViewMap.h b/source/blender/freestyle/intern/view_map/ViewMap.h index 8b73c8aac3a8..16c9699dcef4 100644 --- a/source/blender/freestyle/intern/view_map/ViewMap.h +++ b/source/blender/freestyle/intern/view_map/ViewMap.h @@ -218,7 +218,7 @@ class ViewMap * iB2D * The x,y,z 2D coordinates of the projection of iB3D * iFEdgeB - * The second FEdge + * The second FEdge * id * The id that must be given to that TVertex */ @@ -650,7 +650,7 @@ class TVertex : public ViewVertex /**********************************/ /* */ /* */ -/* NonTVertex */ +/* NonTVertex */ /* */ /* */ /**********************************/ @@ -1643,7 +1643,7 @@ void ViewShape::SplitEdge(FEdge *fe, const vector& iViewVertices, vect ViewEdge *vEdge = fe->viewedge(); // We first need to sort the view vertices from farther to closer to fe->vertexA - SVertex *sv, *sv2; + SVertex *sv, *sv2; ViewVertex *vva, *vvb; vector::const_iterator vv, vvend; for (vv = iViewVertices.begin(), vvend = iViewVertices.end(); vv != vvend; vv++) { @@ -1660,7 +1660,7 @@ void ViewShape::SplitEdge(FEdge *fe, const vector& iViewVertices, vect sv = sv2; } else { - // if the shape is the same we can safely differ the two vertices using their ids: + // if the shape is the same we can safely differ the two vertices using their ids: if (sv->getId() != fe->vertexA()->getId()) sv = sv2; } @@ -1685,7 +1685,7 @@ void ViewShape::SplitEdge(FEdge *fe, const vector& iViewVertices, vect if ((vva == 0) || (vvb == 0)) { // that means we're dealing with a closed viewedge (loop) // remove the chain that was starting by the fedge A of vEdge (which is different from fe !!!!) shape->RemoveEdgeFromChain(vEdge->fedgeA()); - // we set + // we set vEdge->setA(*vv); vEdge->setB(*vv); vEdge->setFEdgeA(newEdge); diff --git a/source/blender/freestyle/intern/view_map/ViewMapBuilder.cpp b/source/blender/freestyle/intern/view_map/ViewMapBuilder.cpp index 794c782bb732..f5239b970f5a 100644 --- a/source/blender/freestyle/intern/view_map/ViewMapBuilder.cpp +++ b/source/blender/freestyle/intern/view_map/ViewMapBuilder.cpp @@ -1004,7 +1004,7 @@ ViewMap *ViewMapBuilder::BuildViewMap(WingedEdge& we, visibility_algo iAlgo, rea computeInitialViewEdges(we); // Detects cusps - computeCusps(_ViewMap); + computeCusps(_ViewMap); // Compute intersections ComputeIntersections(_ViewMap, sweep_line, epsilon); @@ -1059,7 +1059,7 @@ void ViewMapBuilder::CullViewEdges(ViewMap *ioViewMap, real viewProscenium[4], r cout << "Origin: [" << prosceniumOrigin[0] << ", " << prosceniumOrigin[1] << "]"<< endl; } - // A separate occluder proscenium will also be maintained, starting out the same as the viewport proscenium, and + // A separate occluder proscenium will also be maintained, starting out the same as the viewport proscenium, and // expanding as necessary so that it encompasses the center point of at least one feature edge in each retained view // edge. // The occluder proscenium will be used later to cull occluding triangles before they are inserted into the Grid. @@ -1182,7 +1182,7 @@ void ViewMapBuilder::CullViewEdges(ViewMap *ioViewMap, real viewProscenium[4], r FEdge *festart = (*ve)->fedgeA(); FEdge *fe = festart; do { - // If not (already) visible and center point inside occluder proscenium, + // If not (already) visible and center point inside occluder proscenium, if (!fe->isInImage() && insideProscenium(occluderProscenium, fe->center2d())) { // Use the feature edge for visibility determination fe->setIsInImage(true); @@ -1947,7 +1947,8 @@ int ViewMapBuilder::ComputeRayCastingVisibility(FEdge *fe, Grid *iGrid, real eps int viewport[4]; SilhouetteGeomEngine::retrieveViewport(viewport); if ((A.x() < viewport[0]) || (A.x() > viewport[2]) || (A.y() < viewport[1]) || (A.y() > viewport[3]) || - (B.x() < viewport[0]) || (B.x() > viewport[2]) || (B.y() < viewport[1]) || (B.y() > viewport[3])) { + (B.x() < viewport[0]) || (B.x() > viewport[2]) || (B.y() < viewport[1]) || (B.y() > viewport[3])) + { cerr << "Warning: point is out of the grid for fedge " << fe->getId() << endl; //return 0; } @@ -2286,7 +2287,7 @@ void ViewMapBuilder::ComputeSweepLineIntersections(ViewMap *ioViewMap, real epsi for (fe = ioEdges.begin(), fend = ioEdges.end(); fe != fend; fe++) (*fe)->userdata = NULL; - // list containing the new edges resulting from splitting operations. + // list containing the new edges resulting from splitting operations. vector newEdges; // retrieve the intersected edges: diff --git a/source/blender/freestyle/intern/view_map/ViewMapBuilder.h b/source/blender/freestyle/intern/view_map/ViewMapBuilder.h index 440ae93c7dfa..acde37046255 100644 --- a/source/blender/freestyle/intern/view_map/ViewMapBuilder.h +++ b/source/blender/freestyle/intern/view_map/ViewMapBuilder.h @@ -159,7 +159,7 @@ class ViewMapBuilder /*! Builds the scene view map returns the list the view map * it is up to the caller to delete this ViewMap * iWRoot - * The root group node containing the WEdge structured scene + * The root group node containing the WEdge structured scene */ ViewMap *BuildViewMap(WingedEdge& we, visibility_algo iAlgo, real epsilon, const BBox& bbox, unsigned int sceneNumFaces); @@ -180,7 +180,7 @@ class ViewMapBuilder /*! Computes the 2D scene silhouette edges visibility * iGrid - * For the Ray Casting algorithm. + * For the Ray Casting algorithm. */ void ComputeEdgesVisibility(ViewMap *ioViewMap, WingedEdge& we, const BBox& bbox, unsigned int sceneNumFaces, visibility_algo iAlgo = ray_casting, real epsilon = 1.0e-6); diff --git a/source/blender/freestyle/intern/view_map/ViewMapIO.cpp b/source/blender/freestyle/intern/view_map/ViewMapIO.cpp index 71ae68c06bcb..3e80c004b5f3 100644 --- a/source/blender/freestyle/intern/view_map/ViewMapIO.cpp +++ b/source/blender/freestyle/intern/view_map/ViewMapIO.cpp @@ -284,7 +284,7 @@ static int load(istream& in, FEdge *fe) load(in, v); fesharp->setNormalB(v); - // Materials + // Materials READ(matindex); fesharp->setaFrsMaterialIndex(matindex); READ(matindex); diff --git a/source/blender/freestyle/intern/view_map/ViewMapIterators.h b/source/blender/freestyle/intern/view_map/ViewMapIterators.h index 469c2c3b29c4..b10de13cef72 100644 --- a/source/blender/freestyle/intern/view_map/ViewMapIterators.h +++ b/source/blender/freestyle/intern/view_map/ViewMapIterators.h @@ -30,7 +30,7 @@ #include "ViewMap.h" -#include "../system/Iterator.h" //soc +#include "../system/Iterator.h" //soc namespace Freestyle { diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt index 28c9b1c14fba..9cbb21956df6 100644 --- a/source/blender/gpu/CMakeLists.txt +++ b/source/blender/gpu/CMakeLists.txt @@ -164,4 +164,3 @@ if(WITH_OPENSUBDIV) endif() blender_add_lib(bf_gpu "${SRC}" "${INC}" "${INC_SYS}") - diff --git a/source/blender/gpu/GPU_basic_shader.h b/source/blender/gpu/GPU_basic_shader.h index d9bf3d1ced33..230a5defe7b1 100644 --- a/source/blender/gpu/GPU_basic_shader.h +++ b/source/blender/gpu/GPU_basic_shader.h @@ -140,4 +140,3 @@ void GPU_basic_shader_use_glsl_set(bool enabled); #endif #endif - diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h index 90294b3749d7..7b04587bcd37 100644 --- a/source/blender/gpu/GPU_draw.h +++ b/source/blender/gpu/GPU_draw.h @@ -104,25 +104,25 @@ int GPU_scene_object_lights( /* Mipmap settings * - these will free textures on changes */ -void GPU_set_mipmap(bool mipmap); +void GPU_set_mipmap(struct Main *bmain, bool mipmap); bool GPU_get_mipmap(void); void GPU_set_linear_mipmap(bool linear); bool GPU_get_linear_mipmap(void); -void GPU_paint_set_mipmap(bool mipmap); +void GPU_paint_set_mipmap(struct Main *bmain, bool mipmap); /* Anisotropic filtering settings * - these will free textures on changes */ -void GPU_set_anisotropic(float value); +void GPU_set_anisotropic(struct Main *bmain, float value); float GPU_get_anisotropic(void); /* enable gpu mipmapping */ -void GPU_set_gpu_mipmapping(int gpu_mipmap); +void GPU_set_gpu_mipmapping(struct Main *bmain, int gpu_mipmap); /* Image updates and free * - these deal with images bound as opengl textures */ void GPU_paint_update_image(struct Image *ima, struct ImageUser *iuser, int x, int y, int w, int h); -void GPU_update_images_framechange(void); +void GPU_update_images_framechange(struct Main *bmain); int GPU_update_image_time(struct Image *ima, double time); int GPU_verify_image( struct Image *ima, struct ImageUser *iuser, @@ -135,16 +135,16 @@ void GPU_create_gl_tex_compressed( int textarget, struct Image *ima, struct ImBuf *ibuf); bool GPU_upload_dxt_texture(struct ImBuf *ibuf); void GPU_free_image(struct Image *ima); -void GPU_free_images(void); -void GPU_free_images_anim(void); -void GPU_free_images_old(void); +void GPU_free_images(struct Main *bmain); +void GPU_free_images_anim(struct Main *bmain); +void GPU_free_images_old(struct Main *bmain); /* smoke drawing functions */ void GPU_free_smoke(struct SmokeModifierData *smd); void GPU_create_smoke(struct SmokeModifierData *smd, int highres); /* Delayed free of OpenGL buffers by main thread */ -void GPU_free_unused_buffers(void); +void GPU_free_unused_buffers(struct Main *bmain); #ifdef WITH_OPENSUBDIV struct DerivedMesh; @@ -162,4 +162,3 @@ void GPU_select_to_index_array(unsigned int *col, const unsigned int size); #endif #endif - diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h index 3828a084e6be..d5595baade11 100644 --- a/source/blender/gpu/GPU_material.h +++ b/source/blender/gpu/GPU_material.h @@ -43,6 +43,7 @@ extern "C" { struct Image; struct ImageUser; +struct Main; struct Material; struct Object; struct Image; @@ -267,7 +268,7 @@ GPUMaterial *GPU_material_from_blender(struct Scene *scene, struct Material *ma, GPUMaterial *GPU_material_matcap(struct Scene *scene, struct Material *ma, bool use_opensubdiv); void GPU_material_free(struct ListBase *gpumaterial); -void GPU_materials_free(void); +void GPU_materials_free(struct Main *bmain); bool GPU_lamp_visible(GPULamp *lamp, struct SceneRenderLayer *srl, struct Material *ma); void GPU_material_update_lamps(GPUMaterial *material, float viewmat[4][4], float viewinv[4][4]); diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c index 5db2f2aec24e..cea5fb6981a1 100644 --- a/source/blender/gpu/intern/gpu_codegen.c +++ b/source/blender/gpu/intern/gpu_codegen.c @@ -1830,4 +1830,3 @@ void GPU_pass_free_nodes(ListBase *nodes) { gpu_nodes_free(nodes); } - diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h index 6268e888b3a8..bd10e8c397aa 100644 --- a/source/blender/gpu/intern/gpu_codegen.h +++ b/source/blender/gpu/intern/gpu_codegen.h @@ -198,4 +198,3 @@ void gpu_material_add_node(struct GPUMaterial *material, struct GPUNode *node); int GPU_link_changed(struct GPUNodeLink *link); #endif - diff --git a/source/blender/gpu/intern/gpu_compositing.c b/source/blender/gpu/intern/gpu_compositing.c index 10b9f1928429..1b95396ddabe 100644 --- a/source/blender/gpu/intern/gpu_compositing.c +++ b/source/blender/gpu/intern/gpu_compositing.c @@ -1443,4 +1443,3 @@ void GPU_fx_shader_init_interface(struct GPUShader *shader, GPUFXShaderEffect ef break; } } - diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c index 31d81c0f02ad..726326e9d331 100644 --- a/source/blender/gpu/intern/gpu_draw.c +++ b/source/blender/gpu/intern/gpu_draw.c @@ -152,7 +152,7 @@ static struct GPUTextureState { /* Mipmap settings */ -void GPU_set_gpu_mipmapping(int gpu_mipmap) +void GPU_set_gpu_mipmapping(Main *bmain, int gpu_mipmap) { int old_value = GTS.gpu_mipmap; @@ -160,7 +160,7 @@ void GPU_set_gpu_mipmapping(int gpu_mipmap) GTS.gpu_mipmap = gpu_mipmap && GLEW_EXT_framebuffer_object; if (old_value != GTS.gpu_mipmap) { - GPU_free_images(); + GPU_free_images(bmain); } } @@ -187,10 +187,10 @@ static void gpu_generate_mipmap(GLenum target) glDisable(target); } -void GPU_set_mipmap(bool mipmap) +void GPU_set_mipmap(Main *bmain, bool mipmap) { if (GTS.domipmap != mipmap) { - GPU_free_images(); + GPU_free_images(bmain); GTS.domipmap = mipmap; } } @@ -238,10 +238,10 @@ static GLenum gpu_get_mipmap_filter(bool mag) } /* Anisotropic filtering settings */ -void GPU_set_anisotropic(float value) +void GPU_set_anisotropic(Main *bmain, float value) { if (GTS.anisotropic != value) { - GPU_free_images(); + GPU_free_images(bmain); /* Clamp value to the maximum value the graphics card supports */ const float max = GPU_max_texture_anisotropy(); @@ -1030,7 +1030,7 @@ int GPU_set_tpage(MTexPoly *mtexpoly, int mipmap, int alphablend) * temporary disabling/enabling mipmapping on all images for quick texture * updates with glTexSubImage2D. images that didn't change don't have to be * re-uploaded to OpenGL */ -void GPU_paint_set_mipmap(bool mipmap) +void GPU_paint_set_mipmap(Main *bmain, bool mipmap) { if (!GTS.domipmap) return; @@ -1038,7 +1038,7 @@ void GPU_paint_set_mipmap(bool mipmap) GTS.texpaint = !mipmap; if (mipmap) { - for (Image *ima = G.main->image.first; ima; ima = ima->id.next) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { if (BKE_image_has_bindcode(ima)) { if (ima->tpageflag & IMA_MIPMAP_COMPLETE) { if (ima->bindcode[TEXTARGET_TEXTURE_2D]) { @@ -1061,7 +1061,7 @@ void GPU_paint_set_mipmap(bool mipmap) } else { - for (Image *ima = G.main->image.first; ima; ima = ima->id.next) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { if (BKE_image_has_bindcode(ima)) { if (ima->bindcode[TEXTARGET_TEXTURE_2D]) { glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]); @@ -1233,9 +1233,9 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i BKE_image_release_ibuf(ima, ibuf, NULL); } -void GPU_update_images_framechange(void) +void GPU_update_images_framechange(Main *bmain) { - for (Image *ima = G.main->image.first; ima; ima = ima->id.next) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { if (ima->tpageflag & IMA_TWINANIM) { if (ima->twend >= ima->xrep * ima->yrep) ima->twend = ima->xrep * ima->yrep - 1; @@ -1358,7 +1358,7 @@ static void gpu_queue_image_for_free(Image *ima) BLI_thread_unlock(LOCK_OPENGL); } -void GPU_free_unused_buffers(void) +void GPU_free_unused_buffers(Main *bmain) { if (!BLI_thread_is_main()) return; @@ -1370,7 +1370,7 @@ void GPU_free_unused_buffers(void) Image *ima = node->link; /* check in case it was freed in the meantime */ - if (G.main && BLI_findindex(&G.main->image, ima) != -1) + if (bmain && BLI_findindex(&bmain->image, ima) != -1) GPU_free_image(ima); } @@ -1414,24 +1414,29 @@ void GPU_free_image(Image *ima) ima->tpageflag &= ~(IMA_MIPMAP_COMPLETE | IMA_GLBIND_IS_DATA); } -void GPU_free_images(void) +void GPU_free_images(Main *bmain) { - if (G.main) - for (Image *ima = G.main->image.first; ima; ima = ima->id.next) + if (bmain) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { GPU_free_image(ima); + } + } } /* same as above but only free animated images */ -void GPU_free_images_anim(void) +void GPU_free_images_anim(Main *bmain) { - if (G.main) - for (Image *ima = G.main->image.first; ima; ima = ima->id.next) - if (BKE_image_is_animated(ima)) + if (bmain) { + for (Image *ima = bmain->image.first; ima; ima = ima->id.next) { + if (BKE_image_is_animated(ima)) { GPU_free_image(ima); + } + } + } } -void GPU_free_images_old(void) +void GPU_free_images_old(Main *bmain) { static int lasttime = 0; int ctime = (int)PIL_check_seconds_timer(); @@ -1449,7 +1454,7 @@ void GPU_free_images_old(void) lasttime = ctime; - Image *ima = G.main->image.first; + Image *ima = bmain->image.first; while (ima) { if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) { /* If it's in GL memory, deallocate and set time tag to current time diff --git a/source/blender/gpu/intern/gpu_extensions.c b/source/blender/gpu/intern/gpu_extensions.c index 1b07f933936a..225e608ed038 100644 --- a/source/blender/gpu/intern/gpu_extensions.c +++ b/source/blender/gpu/intern/gpu_extensions.c @@ -358,4 +358,3 @@ void GPU_mem_stats_get(int *totalmem, int *freemem) *freemem = 0; } } - diff --git a/source/blender/gpu/intern/gpu_framebuffer.c b/source/blender/gpu/intern/gpu_framebuffer.c index 3cf396a003e5..b250211b8aa3 100644 --- a/source/blender/gpu/intern/gpu_framebuffer.c +++ b/source/blender/gpu/intern/gpu_framebuffer.c @@ -989,4 +989,3 @@ GPUTexture *GPU_offscreen_depth_texture(const GPUOffScreen *ofs) { return ofs->depth; } - diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c index a72746b0af13..c7491a74d545 100644 --- a/source/blender/gpu/intern/gpu_material.c +++ b/source/blender/gpu/intern/gpu_material.c @@ -2492,25 +2492,25 @@ GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma, bool use_open return mat; } -void GPU_materials_free(void) +void GPU_materials_free(Main *bmain) { Object *ob; Material *ma; World *wo; extern Material defmaterial; - for (ma = G.main->mat.first; ma; ma = ma->id.next) { + for (ma = bmain->mat.first; ma; ma = ma->id.next) { GPU_material_free(&ma->gpumaterial); GPU_material_free(&ma->gpumaterialinstancing); } - for (wo = G.main->world.first; wo; wo = wo->id.next) + for (wo = bmain->world.first; wo; wo = wo->id.next) GPU_material_free(&wo->gpumaterial); GPU_material_free(&defmaterial.gpumaterial); GPU_material_free(&defmaterial.gpumaterialinstancing); - for (ob = G.main->object.first; ob; ob = ob->id.next) + for (ob = bmain->object.first; ob; ob = ob->id.next) GPU_lamp_free(ob); } diff --git a/source/blender/gpu/intern/gpu_shader.c b/source/blender/gpu/intern/gpu_shader.c index 0de75eb39eb0..e63eb4e1bcc7 100644 --- a/source/blender/gpu/intern/gpu_shader.c +++ b/source/blender/gpu/intern/gpu_shader.c @@ -1071,5 +1071,3 @@ void GPU_shader_free_builtin_shaders(void) } } } - - diff --git a/source/blender/gpu/intern/gpu_texture.c b/source/blender/gpu/intern/gpu_texture.c index 4503adf2c58b..373c4e3e915d 100644 --- a/source/blender/gpu/intern/gpu_texture.c +++ b/source/blender/gpu/intern/gpu_texture.c @@ -861,4 +861,3 @@ void GPU_texture_framebuffer_set(GPUTexture *tex, GPUFrameBuffer *fb, int attach tex->fb = fb; tex->fb_attachment = attachment; } - diff --git a/source/blender/gpu/shaders/gpu_shader_basic_frag.glsl b/source/blender/gpu/shaders/gpu_shader_basic_frag.glsl index 01a335af0486..a030756e9921 100644 --- a/source/blender/gpu/shaders/gpu_shader_basic_frag.glsl +++ b/source/blender/gpu/shaders/gpu_shader_basic_frag.glsl @@ -286,4 +286,3 @@ void main() #endif } - diff --git a/source/blender/gpu/shaders/gpu_shader_basic_vert.glsl b/source/blender/gpu/shaders/gpu_shader_basic_vert.glsl index fd7d794b4eff..c29a39b4e34e 100644 --- a/source/blender/gpu/shaders/gpu_shader_basic_vert.glsl +++ b/source/blender/gpu/shaders/gpu_shader_basic_vert.glsl @@ -69,4 +69,3 @@ void main() varying_texture_coord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).st; #endif } - diff --git a/source/blender/gpu/shaders/gpu_shader_fx_dof_vert.glsl b/source/blender/gpu/shaders/gpu_shader_fx_dof_vert.glsl index 63b57d5775cd..221dd7e68dfc 100644 --- a/source/blender/gpu/shaders/gpu_shader_fx_dof_vert.glsl +++ b/source/blender/gpu/shaders/gpu_shader_fx_dof_vert.glsl @@ -69,4 +69,3 @@ void main() vert_generic(); #endif } - diff --git a/source/blender/gpu/shaders/gpu_shader_material.glsl b/source/blender/gpu/shaders/gpu_shader_material.glsl index 201a027dc69f..44bbac84ee2f 100644 --- a/source/blender/gpu/shaders/gpu_shader_material.glsl +++ b/source/blender/gpu/shaders/gpu_shader_material.glsl @@ -418,6 +418,29 @@ void math_atan2(float val1, float val2, out float outval) outval = atan(val1, val2); } +void math_floor(float val, out float outval) +{ + outval = floor(val); +} + +void math_ceil(float val, out float outval) +{ + outval = ceil(val); +} + +void math_fract(float val, out float outval) +{ + outval = val - floor(val); +} + +void math_sqrt(float val, out float outval) +{ + if (val > 0.0) + outval = sqrt(val); + else + outval = 0.0; +} + void squeeze(float val, float width, float center, out float outval) { outval = 1.0 / (1.0 + pow(2.71828183, -((val - center) * width))); @@ -3953,7 +3976,7 @@ void node_tex_sky(vec3 co, out vec4 color) color = vec4(1.0); } -void node_tex_voronoi(vec3 co, float scale, float coloring, out vec4 color, out float fac) +void node_tex_voronoi(vec3 co, float scale, float exponent, float coloring, out vec4 color, out float fac) { #ifdef BIT_OPERATIONS vec3 p = co * scale; diff --git a/source/blender/gpu/shaders/gpu_shader_vertex_world.glsl b/source/blender/gpu/shaders/gpu_shader_vertex_world.glsl index 26c5d20bd118..97388d82cfba 100644 --- a/source/blender/gpu/shaders/gpu_shader_vertex_world.glsl +++ b/source/blender/gpu/shaders/gpu_shader_vertex_world.glsl @@ -79,7 +79,6 @@ void main() varposition = gl_Vertex.xyz; varnormal = normalize(-varposition); - // Always set clip distance to 1 to disable clipping. for (int i = 0; i < 6; ++i) { gl_ClipDistance[i] = 1.0; diff --git a/source/blender/ikplugin/intern/ikplugin_api.c b/source/blender/ikplugin/intern/ikplugin_api.c index ca9dcdf198c9..00fb5768d799 100644 --- a/source/blender/ikplugin/intern/ikplugin_api.c +++ b/source/blender/ikplugin/intern/ikplugin_api.c @@ -144,4 +144,3 @@ void BIK_test_constraint(struct Object *ob, struct bConstraint *cons) if (plugin && plugin->test_constraint) plugin->test_constraint(ob, cons); } - diff --git a/source/blender/ikplugin/intern/iksolver_plugin.c b/source/blender/ikplugin/intern/iksolver_plugin.c index f837789914e0..616e9a723f6f 100644 --- a/source/blender/ikplugin/intern/iksolver_plugin.c +++ b/source/blender/ikplugin/intern/iksolver_plugin.c @@ -582,4 +582,3 @@ void iksolver_execute_tree(struct Scene *scene, Object *ob, bPoseChannel *pchan free_posetree(tree); } } - diff --git a/source/blender/ikplugin/intern/itasc_plugin.cpp b/source/blender/ikplugin/intern/itasc_plugin.cpp index 59385670b9ab..17f9cd5bc7ad 100644 --- a/source/blender/ikplugin/intern/itasc_plugin.cpp +++ b/source/blender/ikplugin/intern/itasc_plugin.cpp @@ -1866,4 +1866,3 @@ void itasc_test_constraint(struct Object *ob, struct bConstraint *cons) break; } } - diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt index e73f227dec8a..8d932c5e79d8 100644 --- a/source/blender/imbuf/CMakeLists.txt +++ b/source/blender/imbuf/CMakeLists.txt @@ -23,7 +23,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . ../blenkernel ../blenlib @@ -83,7 +83,7 @@ set(SRC intern/IMB_filter.h intern/IMB_indexer.h intern/imbuf.h - + # orphan include ../../../intern/ffmpeg/ffmpeg_compat.h ) @@ -139,7 +139,7 @@ if(WITH_CODEC_FFMPEG) ) add_definitions(-DWITH_FFMPEG) - remove_strict_flags_file( + remove_strict_c_flags_file( intern/indexer.c intern/util.c intern/anim_movie.c diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h index 4289f98643d1..75f8df99e635 100644 --- a/source/blender/imbuf/IMB_imbuf.h +++ b/source/blender/imbuf/IMB_imbuf.h @@ -217,7 +217,7 @@ void IMB_blend_color_byte(unsigned char dst[4], unsigned char src1[4], void IMB_blend_color_float(float dst[4], float src1[4], float src2[4], IMB_BlendMode mode); -void IMB_rectclip(struct ImBuf *dbuf, struct ImBuf *sbuf, int *destx, +void IMB_rectclip(struct ImBuf *dbuf, struct ImBuf *sbuf, int *destx, int *desty, int *srcx, int *srcy, int *width, int *height); void IMB_rectcpy(struct ImBuf *drect, struct ImBuf *srect, int destx, int desty, int srcx, int srcy, int width, int height); @@ -322,7 +322,7 @@ int IMB_anim_get_preseek(struct anim *anim); struct ImBuf *IMB_anim_absolute( struct anim *anim, int position, - IMB_Timecode_Type tc /* = 1 = IMB_TC_RECORD_RUN */, + IMB_Timecode_Type tc /* = 1 = IMB_TC_RECORD_RUN */, IMB_Proxy_Size preview_size /* = 0 = IMB_PROXY_NONE */); /** @@ -433,7 +433,7 @@ bool IMB_isfloat(struct ImBuf *ibuf); void IMB_de_interlace(struct ImBuf *ibuf); void IMB_interlace(struct ImBuf *ibuf); -/* create char buffer, color corrected if necessary, for ImBufs that lack one */ +/* create char buffer, color corrected if necessary, for ImBufs that lack one */ void IMB_rect_from_float(struct ImBuf *ibuf); /* Create char buffer for part of the image, color corrected if necessary, * Changed part will be stored in buffer. This is expected to be used for texture painting updates */ diff --git a/source/blender/imbuf/IMB_thumbs.h b/source/blender/imbuf/IMB_thumbs.h index cedd9fb4d9ff..f86bfa23692a 100644 --- a/source/blender/imbuf/IMB_thumbs.h +++ b/source/blender/imbuf/IMB_thumbs.h @@ -102,4 +102,3 @@ void IMB_thumb_path_unlock(const char *path); #endif /* __cplusplus */ #endif /* __IMB_THUMBS_H__ */ - diff --git a/source/blender/imbuf/intern/IMB_allocimbuf.h b/source/blender/imbuf/intern/IMB_allocimbuf.h index a754a4919eb8..75854926d308 100644 --- a/source/blender/imbuf/intern/IMB_allocimbuf.h +++ b/source/blender/imbuf/intern/IMB_allocimbuf.h @@ -54,4 +54,3 @@ bool imb_addencodedbufferImBuf(struct ImBuf *ibuf); bool imb_enlargeencodedbufferImBuf(struct ImBuf *ibuf); #endif - diff --git a/source/blender/imbuf/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h index 6fa31e122cc0..804095a0727c 100644 --- a/source/blender/imbuf/intern/IMB_anim.h +++ b/source/blender/imbuf/intern/IMB_anim.h @@ -103,7 +103,7 @@ struct anim { int frs_sec; double frs_sec_base; int x, y; - + /* for number */ char name[1024]; /* for sequence */ @@ -113,12 +113,12 @@ struct anim { void *movie; void *track; void *params; - int orientation; + int orientation; size_t framesize; int interlacing; int preseek; int streamindex; - + /* avi */ struct _AviMovie *avi; @@ -153,7 +153,7 @@ struct anim { int proxies_tried; int indices_tried; - + struct anim *proxy_anim[IMB_PROXY_MAX_SLOT]; struct anim_index *curr_idx[IMB_TC_MAX_SLOT]; diff --git a/source/blender/imbuf/intern/IMB_filetype.h b/source/blender/imbuf/intern/IMB_filetype.h index 2bd7cbcf6eb3..5351b00d3016 100644 --- a/source/blender/imbuf/intern/IMB_filetype.h +++ b/source/blender/imbuf/intern/IMB_filetype.h @@ -82,8 +82,9 @@ int imb_saveiris(struct ImBuf *ibuf, const char *name, int flags); /* jp2 */ int imb_is_a_jp2(const unsigned char *buf); -struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]); -int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags); +struct ImBuf *imb_load_jp2(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]); +struct ImBuf *imb_load_jp2_filepath(const char *name, int flags, char colorspace[IM_MAX_SPACE]); +int imb_save_jp2(struct ImBuf *ibuf, const char *name, int flags); /* jpeg */ int imb_is_a_jpeg(const unsigned char *mem); @@ -119,4 +120,3 @@ void imb_loadtiletiff(struct ImBuf *ibuf, const unsigned char *mem, size_t size, int imb_savetiff(struct ImBuf *ibuf, const char *name, int flags); #endif /* __IMB_FILETYPE_H__ */ - diff --git a/source/blender/imbuf/intern/IMB_filter.h b/source/blender/imbuf/intern/IMB_filter.h index 65656103435f..36a2dc31021e 100644 --- a/source/blender/imbuf/intern/IMB_filter.h +++ b/source/blender/imbuf/intern/IMB_filter.h @@ -47,4 +47,3 @@ void IMB_unpremultiply_rect_float(float *rect_float, int channels, int w, int h) void imb_onehalf_no_alloc(struct ImBuf *ibuf2, struct ImBuf *ibuf1); #endif - diff --git a/source/blender/imbuf/intern/IMB_indexer.h b/source/blender/imbuf/intern/IMB_indexer.h index bac46740f0f1..024801cb870b 100644 --- a/source/blender/imbuf/intern/IMB_indexer.h +++ b/source/blender/imbuf/intern/IMB_indexer.h @@ -109,7 +109,7 @@ unsigned long long IMB_indexer_get_seek_pos_dts( struct anim_index *idx, int frameno_index); int IMB_indexer_get_frame_index(struct anim_index *idx, int frameno); -unsigned long long IMB_indexer_get_pts(struct anim_index *idx, +unsigned long long IMB_indexer_get_pts(struct anim_index *idx, int frame_index); int IMB_indexer_get_duration(struct anim_index *idx); diff --git a/source/blender/imbuf/intern/allocimbuf.c b/source/blender/imbuf/intern/allocimbuf.c index faa0b5f7b6e6..589955d2ab33 100644 --- a/source/blender/imbuf/intern/allocimbuf.c +++ b/source/blender/imbuf/intern/allocimbuf.c @@ -106,14 +106,14 @@ void imb_freemipmapImBuf(ImBuf *ibuf) void imb_freerectfloatImBuf(ImBuf *ibuf) { if (ibuf == NULL) return; - + if (ibuf->rect_float && (ibuf->mall & IB_rectfloat)) { MEM_freeN(ibuf->rect_float); ibuf->rect_float = NULL; } imb_freemipmapImBuf(ibuf); - + ibuf->rect_float = NULL; ibuf->mall &= ~IB_rectfloat; } @@ -126,7 +126,7 @@ void imb_freerectImBuf(ImBuf *ibuf) if (ibuf->rect && (ibuf->mall & IB_rect)) MEM_freeN(ibuf->rect); ibuf->rect = NULL; - + imb_freemipmapImBuf(ibuf); ibuf->mall &= ~IB_rect; @@ -266,30 +266,30 @@ ImBuf *IMB_makeSingleUser(ImBuf *ibuf) bool addzbufImBuf(ImBuf *ibuf) { if (ibuf == NULL) return false; - + IMB_freezbufImBuf(ibuf); - + if ((ibuf->zbuf = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(unsigned int), __func__))) { ibuf->mall |= IB_zbuf; ibuf->flags |= IB_zbuf; return true; } - + return false; } bool addzbuffloatImBuf(ImBuf *ibuf) { if (ibuf == NULL) return false; - + IMB_freezbuffloatImBuf(ibuf); - + if ((ibuf->zbuf_float = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(float), __func__))) { ibuf->mall |= IB_zbuffloat; ibuf->flags |= IB_zbuffloat; return true; } - + return false; } @@ -372,17 +372,17 @@ void *imb_alloc_pixels(unsigned int x, bool imb_addrectfloatImBuf(ImBuf *ibuf) { if (ibuf == NULL) return false; - + if (ibuf->rect_float) imb_freerectfloatImBuf(ibuf); /* frees mipmap too, hrm */ - + ibuf->channels = 4; if ((ibuf->rect_float = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(float), __func__))) { ibuf->mall |= IB_rectfloat; ibuf->flags |= IB_rectfloat; return true; } - + return false; } @@ -390,12 +390,12 @@ bool imb_addrectfloatImBuf(ImBuf *ibuf) bool imb_addrectImBuf(ImBuf *ibuf) { if (ibuf == NULL) return false; - + /* don't call imb_freerectImBuf, it frees mipmaps, this call is used only too give float buffers display */ if (ibuf->rect && (ibuf->mall & IB_rect)) MEM_freeN(ibuf->rect); ibuf->rect = NULL; - + if ((ibuf->rect = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(unsigned char), __func__))) { ibuf->mall |= IB_rect; ibuf->flags |= IB_rect; @@ -511,7 +511,7 @@ ImBuf *IMB_dupImBuf(const ImBuf *ibuf1) ImBuf *ibuf2, tbuf; int flags = 0; int a, x, y; - + if (ibuf1 == NULL) return NULL; if (ibuf1->rect) flags |= IB_rect; @@ -522,13 +522,13 @@ ImBuf *IMB_dupImBuf(const ImBuf *ibuf1) x = ibuf1->x; y = ibuf1->y; if (ibuf1->flags & IB_fields) y *= 2; - + ibuf2 = IMB_allocImBuf(x, y, ibuf1->planes, flags); if (ibuf2 == NULL) return NULL; if (flags & IB_rect) memcpy(ibuf2->rect, ibuf1->rect, ((size_t)x) * y * sizeof(int)); - + if (flags & IB_rectfloat) memcpy(ibuf2->rect_float, ibuf1->rect_float, ((size_t)ibuf1->channels) * x * y * sizeof(float)); @@ -550,7 +550,7 @@ ImBuf *IMB_dupImBuf(const ImBuf *ibuf1) /* silly trick to copy the entire contents of ibuf1 struct over to ibuf */ tbuf = *ibuf1; - + /* fix pointers */ tbuf.rect = ibuf2->rect; tbuf.rect_float = ibuf2->rect_float; @@ -560,7 +560,7 @@ ImBuf *IMB_dupImBuf(const ImBuf *ibuf1) for (a = 0; a < IMB_MIPMAP_LEVELS; a++) tbuf.mipmap[a] = NULL; tbuf.dds_data.data = NULL; - + /* set malloc flag */ tbuf.mall = ibuf2->mall; tbuf.c_handle = NULL; diff --git a/source/blender/imbuf/intern/anim_movie.c b/source/blender/imbuf/intern/anim_movie.c index f842b69418e2..9ab2ee7dd218 100644 --- a/source/blender/imbuf/intern/anim_movie.c +++ b/source/blender/imbuf/intern/anim_movie.c @@ -243,21 +243,35 @@ void IMB_close_anim_proxies(struct anim *anim) struct IDProperty *IMB_anim_load_metadata(struct anim *anim) { + switch (anim->curtype) { + case ANIM_FFMPEG: + { #ifdef WITH_FFMPEG - AVDictionaryEntry *entry = NULL; + AVDictionaryEntry *entry = NULL; - BLI_assert(anim->pFormatCtx != NULL); - av_log(anim->pFormatCtx, AV_LOG_DEBUG, "METADATA FETCH\n"); + BLI_assert(anim->pFormatCtx != NULL); + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "METADATA FETCH\n"); - while (true) { - entry = av_dict_get(anim->pFormatCtx->metadata, "", entry, AV_DICT_IGNORE_SUFFIX); - if (entry == NULL) break; + while (true) { + entry = av_dict_get(anim->pFormatCtx->metadata, "", entry, AV_DICT_IGNORE_SUFFIX); + if (entry == NULL) break; - /* Delay creation of the property group until there is actual metadata to put in there. */ - IMB_metadata_ensure(&anim->metadata); - IMB_metadata_set_field(anim->metadata, entry->key, entry->value); - } + /* Delay creation of the property group until there is actual metadata to put in there. */ + IMB_metadata_ensure(&anim->metadata); + IMB_metadata_set_field(anim->metadata, entry->key, entry->value); + } #endif + break; + } + case ANIM_SEQUENCE: + case ANIM_AVI: + case ANIM_MOVIE: + /* TODO */ + break; + case ANIM_NONE: + default: + break; + } return anim->metadata; } @@ -325,7 +339,7 @@ static int startavi(struct anim *anim) if (AVIFileGetStream(anim->pfile, &anim->pavi[i], 0L, i) != AVIERR_OK) { break; } - + AVIStreamInfo(anim->pavi[i], &avis, sizeof(avis)); if ((avis.fccType == streamtypeVIDEO) && (firstvideo == -1)) { if (streamcount > 0) { @@ -382,7 +396,7 @@ static int startavi(struct anim *anim) free_anim_avi(anim); return -1; } - + anim->duration = anim->avi->header->TotalFrames; anim->params = NULL; @@ -407,7 +421,7 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position) ImBuf *ibuf = NULL; int *tmp; int y; - + if (anim == NULL) { return NULL; } @@ -431,7 +445,7 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position) tmp = AVI_read_frame(anim->avi, AVI_FORMAT_RGB32, position, AVI_get_stream(anim->avi, AVIST_VIDEO, 0)); - + if (tmp == NULL) { printf("Error reading frame from AVI: '%s'\n", anim->name); IMB_freeImBuf(ibuf); @@ -442,10 +456,10 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position) memcpy(&(ibuf->rect)[((anim->y - y) - 1) * anim->x], &tmp[y * anim->x], anim->x * 4); } - + MEM_freeN(tmp); } - + ibuf->rect_colorspace = colormanage_colorspace_get_named(anim->colorspace); return ibuf; @@ -619,7 +633,7 @@ static int startffmpeg(struct anim *anim) anim->pCodecCtx->width, anim->pCodecCtx->height), "ffmpeg deinterlace"), - anim->pCodecCtx->pix_fmt, + anim->pCodecCtx->pix_fmt, anim->pCodecCtx->width, anim->pCodecCtx->height); } @@ -630,7 +644,7 @@ static int startffmpeg(struct anim *anim) else { anim->preseek = 0; } - + anim->img_convert_ctx = sws_getContext( anim->x, anim->y, @@ -640,7 +654,7 @@ static int startffmpeg(struct anim *anim) AV_PIX_FMT_RGBA, SWS_FAST_BILINEAR | SWS_PRINT_INFO | SWS_FULL_CHR_H_INT, NULL, NULL, NULL); - + if (!anim->img_convert_ctx) { fprintf(stderr, "Can't transform color space??? Bailing out...\n"); @@ -671,7 +685,7 @@ static int startffmpeg(struct anim *anim) fprintf(stderr, "Warning: Could not set libswscale colorspace details.\n"); } #endif - + return (0); } @@ -691,7 +705,7 @@ static void ffmpeg_postprocess(struct anim *anim) return; } - /* This means the data wasnt read properly, + /* This means the data wasnt read properly, * this check stops crashing */ if (input->data[0] == 0 && input->data[1] == 0 && input->data[2] == 0 && input->data[3] == 0) @@ -701,7 +715,7 @@ static void ffmpeg_postprocess(struct anim *anim) return; } - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, " POSTPROC: anim->pFrame planes: %p %p %p %p\n", input->data[0], input->data[1], input->data[2], input->data[3]); @@ -738,7 +752,7 @@ static void ffmpeg_postprocess(struct anim *anim) int x, y, h, w; unsigned char *bottom; unsigned char *top; - + sws_scale(anim->img_convert_ctx, (const uint8_t *const *)input->data, input->linesize, @@ -746,31 +760,31 @@ static void ffmpeg_postprocess(struct anim *anim) anim->y, dst2, dstStride2); - + bottom = (unsigned char *) ibuf->rect; top = bottom + ibuf->x * (ibuf->y - 1) * 4; - + h = (ibuf->y + 1) / 2; w = ibuf->x; - + for (y = 0; y < h; y++) { unsigned char tmp[4]; unsigned int *tmp_l = (unsigned int *) tmp; - + for (x = 0; x < w; x++) { tmp[0] = bottom[0]; tmp[1] = bottom[1]; tmp[2] = bottom[2]; tmp[3] = bottom[3]; - + bottom[0] = top[0]; bottom[1] = top[1]; bottom[2] = top[2]; bottom[3] = top[3]; - + *(unsigned int *) top = *tmp_l; - + bottom += 4; top += 4; } @@ -783,7 +797,7 @@ static void ffmpeg_postprocess(struct anim *anim) int dstStride2[4] = { -dstStride[0], 0, 0, 0 }; uint8_t *dst2[4] = { dst[0] + (anim->y - 1) * dstStride[0], 0, 0, 0 }; - + sws_scale(anim->img_convert_ctx, (const uint8_t *const *)input->data, input->linesize, @@ -820,21 +834,21 @@ static int ffmpeg_decode_video_frame(struct anim *anim) av_free_packet(&anim->next_packet); anim->next_packet.stream_index = -1; } - + while ((rval = av_read_frame(anim->pFormatCtx, &anim->next_packet)) >= 0) { - av_log(anim->pFormatCtx, - AV_LOG_DEBUG, + av_log(anim->pFormatCtx, + AV_LOG_DEBUG, "%sREAD: strID=%d (VID: %d) dts=%lld pts=%lld " "%s\n", (anim->next_packet.stream_index == anim->videoStream) ? "->" : " ", - anim->next_packet.stream_index, + anim->next_packet.stream_index, anim->videoStream, (anim->next_packet.dts == AV_NOPTS_VALUE) ? -1 : (long long int)anim->next_packet.dts, (anim->next_packet.pts == AV_NOPTS_VALUE) ? -1 : (long long int)anim->next_packet.pts, - (anim->next_packet.flags & AV_PKT_FLAG_KEY) ? + (anim->next_packet.flags & AV_PKT_FLAG_KEY) ? " KEY" : ""); if (anim->next_packet.stream_index == anim->videoStream) { anim->pFrameComplete = 0; @@ -863,7 +877,7 @@ static int ffmpeg_decode_video_frame(struct anim *anim) av_free_packet(&anim->next_packet); anim->next_packet.stream_index = -1; } - + if (rval == AVERROR_EOF) { /* this sets size and data fields to zero, * which is necessary to decode the remaining data @@ -918,14 +932,14 @@ static void ffmpeg_decode_video_frame_scan( int count = 1000; av_log(anim->pFormatCtx, - AV_LOG_DEBUG, - "SCAN start: considering pts=%lld in search of %lld\n", + AV_LOG_DEBUG, + "SCAN start: considering pts=%lld in search of %lld\n", (long long int)anim->next_pts, (long long int)pts_to_search); while (count > 0 && anim->next_pts < pts_to_search) { av_log(anim->pFormatCtx, - AV_LOG_DEBUG, - " WHILE: pts=%lld in search of %lld\n", + AV_LOG_DEBUG, + " WHILE: pts=%lld in search of %lld\n", (long long int)anim->next_pts, (long long int)pts_to_search); if (!ffmpeg_decode_video_frame(anim)) { break; @@ -934,9 +948,9 @@ static void ffmpeg_decode_video_frame_scan( } if (count == 0) { av_log(anim->pFormatCtx, - AV_LOG_ERROR, + AV_LOG_ERROR, "SCAN failed: completely lost in stream, " - "bailing out at PTS=%lld, searching for PTS=%lld\n", + "bailing out at PTS=%lld, searching for PTS=%lld\n", (long long int)anim->next_pts, (long long int)pts_to_search); } if (anim->next_pts == pts_to_search) { @@ -995,7 +1009,7 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, int64_t pts_to_search = 0; double frame_rate; double pts_time_base; - long long st_time; + long long st_time; struct anim_index *tc_index = 0; AVStream *v_st; int new_frame_index = 0; /* To quiet gcc barking... */ @@ -1025,7 +1039,7 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, tc_index, new_frame_index); } else { - pts_to_search = (long long) + pts_to_search = (long long) floor(((double) position) / pts_time_base / frame_rate + 0.5); @@ -1034,29 +1048,29 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, } } - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: looking for PTS=%lld " - "(pts_timebase=%g, frame_rate=%g, st_time=%lld)\n", + "(pts_timebase=%g, frame_rate=%g, st_time=%lld)\n", (long long int)pts_to_search, pts_time_base, frame_rate, st_time); - if (anim->last_frame && + if (anim->last_frame && anim->last_pts <= pts_to_search && anim->next_pts > pts_to_search) { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: frame repeat: last: %lld next: %lld\n", - (long long int)anim->last_pts, + (long long int)anim->last_pts, (long long int)anim->next_pts); IMB_refImBuf(anim->last_frame); anim->curposition = position; return anim->last_frame; } - + if (position > anim->curposition + 1 && anim->preseek && !tc_index && position - (anim->curposition + 1) < anim->preseek) { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: within preseek interval (no index)\n"); ffmpeg_decode_video_frame_scan(anim, pts_to_search); @@ -1065,7 +1079,7 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, IMB_indexer_can_scan(tc_index, old_frame_index, new_frame_index)) { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: within preseek interval " "(index tells us)\n"); @@ -1083,24 +1097,24 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, dts = IMB_indexer_get_seek_pos_dts( tc_index, new_frame_index); - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "TC INDEX seek pos = %lld\n", pos); - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "TC INDEX seek dts = %llu\n", dts); if (ffmpeg_seek_by_byte(anim->pFormatCtx)) { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "... using BYTE pos\n"); - ret = av_seek_frame(anim->pFormatCtx, + ret = av_seek_frame(anim->pFormatCtx, -1, pos, AVSEEK_FLAG_BYTE); av_update_cur_dts(anim->pFormatCtx, v_st, dts); } else { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "... using DTS pos\n"); - ret = av_seek_frame(anim->pFormatCtx, + ret = av_seek_frame(anim->pFormatCtx, anim->videoStream, dts, AVSEEK_FLAG_BACKWARD); } @@ -1109,22 +1123,22 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, pos = (long long) (position - anim->preseek) * AV_TIME_BASE / frame_rate; - av_log(anim->pFormatCtx, AV_LOG_DEBUG, - "NO INDEX seek pos = %lld, st_time = %lld\n", + av_log(anim->pFormatCtx, AV_LOG_DEBUG, + "NO INDEX seek pos = %lld, st_time = %lld\n", pos, (st_time != AV_NOPTS_VALUE) ? st_time : 0); if (pos < 0) { pos = 0; } - + if (st_time != AV_NOPTS_VALUE) { pos += st_time; } - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "NO INDEX final seek pos = %lld\n", pos); - ret = av_seek_frame(anim->pFormatCtx, -1, + ret = av_seek_frame(anim->pFormatCtx, -1, pos, AVSEEK_FLAG_BACKWARD); } @@ -1156,7 +1170,7 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, ffmpeg_decode_video_frame(anim); } else { - av_log(anim->pFormatCtx, AV_LOG_DEBUG, + av_log(anim->pFormatCtx, AV_LOG_DEBUG, "FETCH: no seek necessary, just continue...\n"); } @@ -1167,11 +1181,11 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position, ffmpeg_postprocess(anim); anim->last_pts = anim->next_pts; - + ffmpeg_decode_video_frame(anim); - + anim->curposition = position; - + IMB_refImBuf(anim->last_frame); return anim->last_frame; @@ -1275,7 +1289,7 @@ struct ImBuf *IMB_anim_previewframe(struct anim *anim) { struct ImBuf *ibuf = NULL; int position = 0; - + ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE); if (ibuf) { IMB_freeImBuf(ibuf); @@ -1363,7 +1377,7 @@ struct ImBuf *IMB_anim_absolute(struct anim *anim, int position, if (ibuf) { if (filter_y) IMB_filtery(ibuf); BLI_snprintf(ibuf->name, sizeof(ibuf->name), "%s.%04d", anim->name, anim->curposition + 1); - + } return(ibuf); } @@ -1376,7 +1390,7 @@ int IMB_anim_get_duration(struct anim *anim, IMB_Timecode_Type tc) if (tc == IMB_TC_NONE) { return anim->duration; } - + idx = IMB_anim_open_index(anim, tc); if (!idx) { return anim->duration; diff --git a/source/blender/imbuf/intern/bmp.c b/source/blender/imbuf/intern/bmp.c index e63699ea5bae..edaa57eedf20 100644 --- a/source/blender/imbuf/intern/bmp.c +++ b/source/blender/imbuf/intern/bmp.c @@ -130,7 +130,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c unsigned short col; double xppm, yppm; bool top_to_bottom = false; - + (void)size; /* unused */ if (checkbmp(mem) == 0) return(NULL); @@ -248,7 +248,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c rect[0] = bmp[2]; rect[1] = bmp[1]; rect[2] = bmp[0]; - + rect[3] = 255; rect += 4; bmp += 3; } @@ -277,7 +277,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c ibuf->ppm[1] = yppm; ibuf->ftype = IMB_FTYPE_BMP; } - + return(ibuf); } @@ -297,7 +297,7 @@ static int putShortLSB(unsigned short us, FILE *ofile) { putc((us >> 0) & 0xFF, ofile); return putc((us >> 8) & 0xFF, ofile); -} +} /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */ int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags) @@ -306,7 +306,7 @@ int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags) size_t bytesize, extrabytes, ptr; uchar *data; FILE *ofile; - + (void)flags; /* unused */ extrabytes = (4 - ibuf->x * 3 % 4) % 4; diff --git a/source/blender/imbuf/intern/cache.c b/source/blender/imbuf/intern/cache.c index 759f8cc82c26..e8beaa9d68f6 100644 --- a/source/blender/imbuf/intern/cache.c +++ b/source/blender/imbuf/intern/cache.c @@ -280,7 +280,7 @@ static ImGlobalTile *imb_global_cache_get_tile(ImBuf *ibuf, int tx, int ty, ImGl lookuptile.tx = tx; lookuptile.ty = ty; gtile = BLI_ghash_lookup(GLOBAL_CACHE.tilehash, &lookuptile); - + if (gtile) { /* found tile. however it may be in the process of being loaded * by another thread, in that case we do stupid busy loop waiting @@ -450,4 +450,3 @@ void IMB_tiles_to_rect(ImBuf *ibuf) } } } - diff --git a/source/blender/imbuf/intern/cineon/CMakeLists.txt b/source/blender/imbuf/intern/cineon/CMakeLists.txt index c96db4e4a3d6..0a3c440d9a7d 100644 --- a/source/blender/imbuf/intern/cineon/CMakeLists.txt +++ b/source/blender/imbuf/intern/cineon/CMakeLists.txt @@ -23,7 +23,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . .. ../.. diff --git a/source/blender/imbuf/intern/cineon/cineon_dpx.c b/source/blender/imbuf/intern/cineon/cineon_dpx.c index 1d2ebf88a326..c116d32b2f0e 100644 --- a/source/blender/imbuf/intern/cineon/cineon_dpx.c +++ b/source/blender/imbuf/intern/cineon/cineon_dpx.c @@ -106,7 +106,7 @@ static int imb_save_dpx_cineon(ImBuf *ibuf, const char *filename, int use_cineon printf("DPX/Cineon: saving in memory is not supported.\n"); return 0; } - + logImageSetVerbose((G.debug & G_DEBUG) ? 1 : 0); depth = (ibuf->planes + 7) >> 3; diff --git a/source/blender/imbuf/intern/cineon/logImageCore.c b/source/blender/imbuf/intern/cineon/logImageCore.c index bb72f675cb80..614323d0d114 100644 --- a/source/blender/imbuf/intern/cineon/logImageCore.c +++ b/source/blender/imbuf/intern/cineon/logImageCore.c @@ -917,7 +917,7 @@ static float *getLinToLogLut(LogImageFile *logImage, LogImageElement logElement) float gain, negativeFilmGamma, offset, step; unsigned int lutsize = (unsigned int)(logElement.maxValue + 1); unsigned int i; - + lut = MEM_mallocN(sizeof(float) * lutsize, "getLinToLogLut"); negativeFilmGamma = 0.6; @@ -927,7 +927,7 @@ static float *getLinToLogLut(LogImageFile *logImage, LogImageElement logElement) for (i = 0; i < lutsize; i++) lut[i] = (logImage->referenceWhite + log10f(powf((i + offset) / gain, 1.7f / logImage->gamma)) / (step / negativeFilmGamma)) / logElement.maxValue; - + return lut; } @@ -938,7 +938,7 @@ static float *getLogToLinLut(LogImageFile *logImage, LogImageElement logElement) /* float filmGamma; unused */ unsigned int lutsize = (unsigned int)(logElement.maxValue + 1); unsigned int i; - + lut = MEM_mallocN(sizeof(float) * lutsize, "getLogToLinLut"); /* Building the Log -> Lin LUT */ diff --git a/source/blender/imbuf/intern/colormanagement.c b/source/blender/imbuf/intern/colormanagement.c index 7c7c3a7ba45e..86c0dd699303 100644 --- a/source/blender/imbuf/intern/colormanagement.c +++ b/source/blender/imbuf/intern/colormanagement.c @@ -2448,7 +2448,7 @@ const char *IMB_colormanagement_view_get_default_name(const char *display_name) { ColorManagedDisplay *display = colormanage_display_get_named(display_name); ColorManagedView *view = NULL; - + if (display) view = colormanage_view_get_default(display); diff --git a/source/blender/imbuf/intern/dds/BlockDXT.cpp b/source/blender/imbuf/intern/dds/BlockDXT.cpp index 8e571483e086..7273ec1659c9 100644 --- a/source/blender/imbuf/intern/dds/BlockDXT.cpp +++ b/source/blender/imbuf/intern/dds/BlockDXT.cpp @@ -33,7 +33,7 @@ */ // Copyright NVIDIA Corporation 2007 -- Ignacio Castano -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -42,10 +42,10 @@ // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -71,37 +71,37 @@ uint BlockDXT1::evaluatePalette(Color32 color_array[4]) const color_array[0].g = (col0.g << 2) | (col0.g >> 4); color_array[0].r = (col0.r << 3) | (col0.r >> 2); color_array[0].a = 0xFF; - + // @@ Same as above, but faster? // Color32 c; // c.u = ((col0.u << 3) & 0xf8) | ((col0.u << 5) & 0xfc00) | ((col0.u << 8) & 0xf80000); // c.u |= (c.u >> 5) & 0x070007; // c.u |= (c.u >> 6) & 0x000300; // color_array[0].u = c.u; - + color_array[1].r = (col1.r << 3) | (col1.r >> 2); color_array[1].g = (col1.g << 2) | (col1.g >> 4); color_array[1].b = (col1.b << 3) | (col1.b >> 2); color_array[1].a = 0xFF; - + // @@ Same as above, but faster? // c.u = ((col1.u << 3) & 0xf8) | ((col1.u << 5) & 0xfc00) | ((col1.u << 8) & 0xf80000); // c.u |= (c.u >> 5) & 0x070007; // c.u |= (c.u >> 6) & 0x000300; // color_array[1].u = c.u; - + if ( col0.u > col1.u ) { // Four-color block: derive the other two colors. color_array[2].r = (2 * color_array[0].r + color_array[1].r) / 3; color_array[2].g = (2 * color_array[0].g + color_array[1].g) / 3; color_array[2].b = (2 * color_array[0].b + color_array[1].b) / 3; color_array[2].a = 0xFF; - + color_array[3].r = (2 * color_array[1].r + color_array[0].r) / 3; color_array[3].g = (2 * color_array[1].g + color_array[0].g) / 3; color_array[3].b = (2 * color_array[1].b + color_array[0].b) / 3; color_array[3].a = 0xFF; - + return 4; } else { @@ -110,13 +110,13 @@ uint BlockDXT1::evaluatePalette(Color32 color_array[4]) const color_array[2].g = (color_array[0].g + color_array[1].g) / 2; color_array[2].b = (color_array[0].b + color_array[1].b) / 2; color_array[2].a = 0xFF; - + // Set all components to 0 to match DXT specs. color_array[3].r = 0x00; // color_array[2].r; color_array[3].g = 0x00; // color_array[2].g; color_array[3].b = 0x00; // color_array[2].b; color_array[3].a = 0x00; - + return 3; } } @@ -134,7 +134,7 @@ uint BlockDXT1::evaluatePaletteNV5x(Color32 color_array[4]) const color_array[1].g = (col1.g << 2) | (col1.g >> 4); color_array[1].b = (3 * col1.b * 22) / 8; color_array[1].a = 0xFF; - + int gdiff = color_array[1].g - color_array[0].g; if ( col0.u > col1.u ) { @@ -143,7 +143,7 @@ uint BlockDXT1::evaluatePaletteNV5x(Color32 color_array[4]) const color_array[2].g = (256 * color_array[0].g + gdiff / 4 + 128 + gdiff * 80) / 256; color_array[2].b = ((2 * col0.b + col1.b) * 22) / 8; color_array[2].a = 0xFF; - + color_array[3].r = ((2 * col1.r + col0.r) * 22) / 8; color_array[3].g = (256 * color_array[1].g - gdiff / 4 + 128 - gdiff * 80) / 256; color_array[3].b = ((2 * col1.b + col0.b) * 22) / 8; @@ -157,13 +157,13 @@ uint BlockDXT1::evaluatePaletteNV5x(Color32 color_array[4]) const color_array[2].g = (256 * color_array[0].g + gdiff / 4 + 128 + gdiff * 128) / 256; color_array[2].b = ((col0.b + col1.b) * 33) / 8; color_array[2].a = 0xFF; - + // Set all components to 0 to match DXT specs. color_array[3].r = 0x00; // color_array[2].r; color_array[3].g = 0x00; // color_array[2].g; color_array[3].b = 0x00; // color_array[2].b; color_array[3].a = 0x00; - + return 3; } } @@ -175,18 +175,18 @@ void BlockDXT1::evaluatePalette3(Color32 color_array[4]) const color_array[0].g = (col0.g << 2) | (col0.g >> 4); color_array[0].r = (col0.r << 3) | (col0.r >> 2); color_array[0].a = 0xFF; - + color_array[1].r = (col1.r << 3) | (col1.r >> 2); color_array[1].g = (col1.g << 2) | (col1.g >> 4); color_array[1].b = (col1.b << 3) | (col1.b >> 2); color_array[1].a = 0xFF; - + // Three-color block: derive the other color. color_array[2].r = (color_array[0].r + color_array[1].r) / 2; color_array[2].g = (color_array[0].g + color_array[1].g) / 2; color_array[2].b = (color_array[0].b + color_array[1].b) / 2; color_array[2].a = 0xFF; - + // Set all components to 0 to match DXT specs. color_array[3].r = 0x00; // color_array[2].r; color_array[3].g = 0x00; // color_array[2].g; @@ -201,18 +201,18 @@ void BlockDXT1::evaluatePalette4(Color32 color_array[4]) const color_array[0].g = (col0.g << 2) | (col0.g >> 4); color_array[0].r = (col0.r << 3) | (col0.r >> 2); color_array[0].a = 0xFF; - + color_array[1].r = (col1.r << 3) | (col1.r >> 2); color_array[1].g = (col1.g << 2) | (col1.g >> 4); color_array[1].b = (col1.b << 3) | (col1.b >> 2); color_array[1].a = 0xFF; - + // Four-color block: derive the other two colors. color_array[2].r = (2 * color_array[0].r + color_array[1].r) / 3; color_array[2].g = (2 * color_array[0].g + color_array[1].g) / 3; color_array[2].b = (2 * color_array[0].b + color_array[1].b) / 3; color_array[2].a = 0xFF; - + color_array[3].r = (2 * color_array[1].r + color_array[0].r) / 3; color_array[3].g = (2 * color_array[1].g + color_array[0].g) / 3; color_array[3].b = (2 * color_array[1].b + color_array[0].b) / 3; @@ -225,7 +225,7 @@ void BlockDXT1::decodeBlock(ColorBlock *block) const // Decode color block. Color32 color_array[4]; evaluatePalette(color_array); - + // Write color block. for ( uint j = 0; j < 4; j++ ) { for ( uint i = 0; i < 4; i++ ) { @@ -281,7 +281,7 @@ void BlockDXT3::decodeBlock(ColorBlock *block) const { // Decode color. color.decodeBlock(block); - + // Decode alpha. alpha.decodeBlock(block); } @@ -419,10 +419,10 @@ void AlphaBlockDXT5::decodeBlock(ColorBlock *block) const { uint8 alpha_array[8]; evaluatePalette(alpha_array); - + uint8 index_array[16]; indices(index_array); - + for (uint i = 0; i < 16; i++) { block->color(i).a = alpha_array[index_array[i]]; } @@ -431,26 +431,26 @@ void AlphaBlockDXT5::decodeBlock(ColorBlock *block) const void AlphaBlockDXT5::flip4() { uint64 * b = (uint64 *)this; - + // @@ The masks might have to be byte swapped. uint64 tmp = (*b & (uint64)(0x000000000000FFFFLL)); tmp |= (*b & (uint64)(0x000000000FFF0000LL)) << 36; tmp |= (*b & (uint64)(0x000000FFF0000000LL)) << 12; tmp |= (*b & (uint64)(0x000FFF0000000000LL)) >> 12; tmp |= (*b & (uint64)(0xFFF0000000000000LL)) >> 36; - + *b = tmp; } void AlphaBlockDXT5::flip2() { uint * b = (uint *)this; - + // @@ The masks might have to be byte swapped. uint tmp = (*b & 0xFF000000); tmp |= (*b & 0x00000FFF) << 12; tmp |= (*b & 0x00FFF000) >> 12; - + *b = tmp; } @@ -458,7 +458,7 @@ void BlockDXT5::decodeBlock(ColorBlock *block) const { // Decode color. color.decodeBlock(block); - + // Decode alpha. alpha.decodeBlock(block); } @@ -467,7 +467,7 @@ void BlockDXT5::decodeBlockNV5x(ColorBlock *block) const { // Decode color. color.decodeBlockNV5x(block); - + // Decode alpha. alpha.decodeBlock(block); } @@ -492,10 +492,10 @@ void BlockATI1::decodeBlock(ColorBlock *block) const { uint8 alpha_array[8]; alpha.evaluatePalette(alpha_array); - + uint8 index_array[16]; alpha.indices(index_array); - + for (uint i = 0; i < 16; i++) { Color32 & c = block->color(i); c.b = c.g = c.r = alpha_array[index_array[i]]; @@ -521,10 +521,10 @@ void BlockATI2::decodeBlock(ColorBlock *block) const { uint8 alpha_array[8]; uint8 index_array[16]; - + x.evaluatePalette(alpha_array); x.indices(index_array); - + for (uint i = 0; i < 16; i++) { Color32 & c = block->color(i); c.r = alpha_array[index_array[i]]; @@ -532,7 +532,7 @@ void BlockATI2::decodeBlock(ColorBlock *block) const y.evaluatePalette(alpha_array); y.indices(index_array); - + for (uint i = 0; i < 16; i++) { Color32 & c = block->color(i); c.g = alpha_array[index_array[i]]; @@ -563,17 +563,17 @@ void BlockCTX1::evaluatePalette(Color32 color_array[4]) const color_array[0].g = col0[1]; color_array[0].r = col0[0]; color_array[0].a = 0xFF; - + color_array[1].r = 0x00; color_array[1].g = col0[1]; color_array[1].b = col1[0]; color_array[1].a = 0xFF; - + color_array[2].r = 0x00; color_array[2].g = (2 * color_array[0].g + color_array[1].g) / 3; color_array[2].b = (2 * color_array[0].b + color_array[1].b) / 3; color_array[2].a = 0xFF; - + color_array[3].r = 0x00; color_array[3].g = (2 * color_array[1].g + color_array[0].g) / 3; color_array[3].b = (2 * color_array[1].b + color_array[0].b) / 3; @@ -585,7 +585,7 @@ void BlockCTX1::decodeBlock(ColorBlock *block) const // Decode color block. Color32 color_array[4]; evaluatePalette(color_array); - + // Write color block. for ( uint j = 0; j < 4; j++ ) { for ( uint i = 0; i < 4; i++ ) { @@ -665,4 +665,3 @@ void mem_read(Stream & mem, BlockCTX1 & block) mem_read(mem, block.col1[1]); mem_read(mem, block.indices); } - diff --git a/source/blender/imbuf/intern/dds/BlockDXT.h b/source/blender/imbuf/intern/dds/BlockDXT.h index 6aae9c9817c4..7371d72ea4ab 100644 --- a/source/blender/imbuf/intern/dds/BlockDXT.h +++ b/source/blender/imbuf/intern/dds/BlockDXT.h @@ -33,7 +33,7 @@ */ // Copyright NVIDIA Corporation 2007 -- Ignacio Castano -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -42,10 +42,10 @@ // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -79,10 +79,10 @@ struct BlockDXT1 { void evaluatePalette3(Color32 color_array[4]) const; void evaluatePalette4(Color32 color_array[4]) const; - + void decodeBlock(ColorBlock * block) const; void decodeBlockNV5x(ColorBlock * block) const; - + void setIndices(int * idx); void flip4(); @@ -119,9 +119,9 @@ struct AlphaBlockDXT3 { }; uint16 row[4]; }; - + void decodeBlock(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -131,10 +131,10 @@ struct AlphaBlockDXT3 { struct BlockDXT3 { AlphaBlockDXT3 alpha; BlockDXT1 color; - + void decodeBlock(ColorBlock * block) const; void decodeBlockNV5x(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -187,7 +187,7 @@ struct AlphaBlockDXT5 { uint8 bitsD() const { return (u >> 55) & 0x7LL; } uint8 bitsE() const { return (u >> 58) & 0x7LL; } uint8 bitsF() const { return (u >> 61) & 0x7LL; } - + void evaluatePalette(uint8 alpha[8]) const; void evaluatePalette8(uint8 alpha[8]) const; void evaluatePalette6(uint8 alpha[8]) const; @@ -195,9 +195,9 @@ struct AlphaBlockDXT5 { uint index(uint index) const; void setIndex(uint index, uint value); - + void decodeBlock(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -207,10 +207,10 @@ struct AlphaBlockDXT5 { struct BlockDXT5 { AlphaBlockDXT5 alpha; BlockDXT1 color; - + void decodeBlock(ColorBlock * block) const; void decodeBlockNV5x(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -218,9 +218,9 @@ struct BlockDXT5 { /// ATI1 block. struct BlockATI1 { AlphaBlockDXT5 alpha; - + void decodeBlock(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -229,9 +229,9 @@ struct BlockATI1 { struct BlockATI2 { AlphaBlockDXT5 x; AlphaBlockDXT5 y; - + void decodeBlock(ColorBlock * block) const; - + void flip4(); void flip2(); }; @@ -249,7 +249,7 @@ struct BlockCTX1 { void setIndices(int * idx); void decodeBlock(ColorBlock * block) const; - + void flip4(); void flip2(); }; diff --git a/source/blender/imbuf/intern/dds/CMakeLists.txt b/source/blender/imbuf/intern/dds/CMakeLists.txt index 57603725ce16..8c95695f356c 100644 --- a/source/blender/imbuf/intern/dds/CMakeLists.txt +++ b/source/blender/imbuf/intern/dds/CMakeLists.txt @@ -19,11 +19,11 @@ # # The Original Code is: all of this file. # -# Contributor(s): +# Contributor(s): # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . .. ../.. diff --git a/source/blender/imbuf/intern/dds/Color.h b/source/blender/imbuf/intern/dds/Color.h index 6676057d7108..51939a6ea4c4 100644 --- a/source/blender/imbuf/intern/dds/Color.h +++ b/source/blender/imbuf/intern/dds/Color.h @@ -69,7 +69,7 @@ class Color32 operator unsigned int () const { return u; } - + union { struct { unsigned char b, g, r, a; @@ -85,7 +85,7 @@ class Color16 Color16() { } Color16(const Color16 & c) : u(c.u) { } explicit Color16(unsigned short U) : u(U) { } - + union { struct { unsigned short b : 5; diff --git a/source/blender/imbuf/intern/dds/ColorBlock.cpp b/source/blender/imbuf/intern/dds/ColorBlock.cpp index dd4ae3e518ed..d0db912f4dcc 100644 --- a/source/blender/imbuf/intern/dds/ColorBlock.cpp +++ b/source/blender/imbuf/intern/dds/ColorBlock.cpp @@ -44,14 +44,14 @@ { return c.r + c.g + c.b; } - + // Get the euclidean distance between the given colors. inline static uint colorDistance(Color32 c0, Color32 c1) { return (c0.r - c1.r) * (c0.r - c1.r) + (c0.g - c1.g) * (c0.g - c1.g) + (c0.b - c1.b) * (c0.b - c1.b); } #endif - + /// Default constructor. ColorBlock::ColorBlock() @@ -120,11 +120,11 @@ void ColorBlock::init(uint w, uint h, const float *data, uint x, uint y) for (uint i = 0; i < 4; i++) { const uint by = i % bh; - + for (uint e = 0; e < 4; e++) { const uint bx = e % bw; const uint idx = ((y + by) * w + x + bx); - + Color32 & c = color(e, i); c.r = uint8(255 * CLAMP(data[idx + 0 * srcPlane], 0.0f, 1.0f)); // @@ Is this the right way to quantize floats to bytes? c.g = uint8(255 * CLAMP(data[idx + 1 * srcPlane], 0.0f, 1.0f)); @@ -160,13 +160,13 @@ void ColorBlock::swizzle(uint x, uint y, uint z, uint w) bool ColorBlock::isSingleColor(Color32 mask/*= Color32(0xFF, 0xFF, 0xFF, 0x00)*/) const { uint u = m_color[0].u & mask.u; - + for (int i = 1; i < 16; i++) { if (u != (m_color[i].u & mask.u)) { return false; } } - + return true; } @@ -191,7 +191,7 @@ bool ColorBlock::isSingleColorNoAlpha() const return false; } } - + return true; } */ @@ -210,12 +210,12 @@ bool ColorBlock::isSingleColorNoAlpha() const unique = false; } } - + if ( unique ) { count++; } } - + return count; }*/ @@ -231,7 +231,7 @@ Color32 ColorBlock::averageColor() const b += m_color[i].b; a += m_color[i].a; } - + return Color32(uint8(r / 16), uint8(g / 16), uint8(b / 16), uint8(a / 16)); }*/ @@ -251,7 +251,7 @@ void ColorBlock::diameterRange(Color32 *start, Color32 *end) const { Color32 c0, c1; uint best_dist = 0; - + for (int i = 0; i < 16; i++) { for (int j = i+1; j < 16; j++) { uint dist = colorDistance(m_color[i], m_color[j]); @@ -262,7 +262,7 @@ void ColorBlock::diameterRange(Color32 *start, Color32 *end) const } } } - + *start = c0; *end = c1; } @@ -272,13 +272,13 @@ void ColorBlock::luminanceRange(Color32 *start, Color32 *end) const { Color32 minColor, maxColor; uint minLuminance, maxLuminance; - + maxLuminance = minLuminance = colorLuminance(m_color[0]); - + for (uint i = 1; i < 16; i++) { uint luminance = colorLuminance(m_color[i]); - + if (luminance > maxLuminance) { maxLuminance = luminance; maxColor = m_color[i]; @@ -293,7 +293,7 @@ void ColorBlock::luminanceRange(Color32 *start, Color32 *end) const *end = maxColor; } -/// Get color range based on the bounding box. +/// Get color range based on the bounding box. void ColorBlock::boundsRange(Color32 *start, Color32 *end) const { Color32 minColor(255, 255, 255); @@ -327,7 +327,7 @@ void ColorBlock::boundsRange(Color32 *start, Color32 *end) const *end = maxColor; } -/// Get color range based on the bounding box. +/// Get color range based on the bounding box. void ColorBlock::boundsRangeAlpha(Color32 *start, Color32 *end) const { Color32 minColor(255, 255, 255, 255); @@ -361,7 +361,7 @@ void ColorBlock::boundsRangeAlpha(Color32 *start, Color32 *end) const maxColor.g = (maxColor.g >= inset.g) ? maxColor.g - inset.g : 0; maxColor.b = (maxColor.b >= inset.b) ? maxColor.b - inset.b : 0; maxColor.a = (maxColor.a >= inset.a) ? maxColor.a - inset.a : 0; - + *start = minColor; *end = maxColor; } @@ -374,10 +374,10 @@ void ColorBlock::sortColorsByAbsoluteValue() for ( uint a = 0; a < 16; a++ ) { uint max = a; Color16 cmax(m_color[a]); - + for ( uint b = a+1; b < 16; b++ ) { Color16 cb(m_color[b]); - + if ( cb.u > cmax.u ) { max = b; cmax = cb; @@ -391,17 +391,17 @@ void ColorBlock::sortColorsByAbsoluteValue() /*/// Find extreme colors in the given axis. void ColorBlock::computeRange(Vector3::Arg axis, Color32 *start, Color32 *end) const { - + int mini, maxi; mini = maxi = 0; - + float min, max; min = max = dot(Vector3(m_color[0].r, m_color[0].g, m_color[0].b), axis); for (uint i = 1; i < 16; i++) { const Vector3 vec(m_color[i].r, m_color[i].g, m_color[i].b); - + float val = dot(vec, axis); if ( val < min ) { mini = i; @@ -412,7 +412,7 @@ void ColorBlock::computeRange(Vector3::Arg axis, Color32 *start, Color32 *end) c max = val; } } - + *start = m_color[mini]; *end = m_color[maxi]; }*/ @@ -422,12 +422,12 @@ void ColorBlock::computeRange(Vector3::Arg axis, Color32 *start, Color32 *end) c void ColorBlock::sortColors(const Vector3 & axis) { float luma_array[16]; - + for (uint i = 0; i < 16; i++) { const Vector3 vec(m_color[i].r, m_color[i].g, m_color[i].b); luma_array[i] = dot(vec, axis); } - + // Dummy selection sort. for ( uint a = 0; a < 16; a++ ) { uint min = a; @@ -447,13 +447,12 @@ float ColorBlock::volume() const { Box bounds; bounds.clearBounds(); - + for (int i = 0; i < 16; i++) { const Vector3 point(m_color[i].r, m_color[i].g, m_color[i].b); bounds.addPointToBounds(point); } - + return bounds.volume(); } */ - diff --git a/source/blender/imbuf/intern/dds/ColorBlock.h b/source/blender/imbuf/intern/dds/ColorBlock.h index 8d5031aa603f..7b5291cf976c 100644 --- a/source/blender/imbuf/intern/dds/ColorBlock.h +++ b/source/blender/imbuf/intern/dds/ColorBlock.h @@ -46,30 +46,30 @@ struct ColorBlock { ColorBlock(const uint * linearImage); ColorBlock(const ColorBlock & block); ColorBlock(const Image * img, uint x, uint y); - + void init(const Image * img, uint x, uint y); void init(uint w, uint h, const uint * data, uint x, uint y); void init(uint w, uint h, const float * data, uint x, uint y); - + void swizzle(uint x, uint y, uint z, uint w); // 0=r, 1=g, 2=b, 3=a, 4=0xFF, 5=0 - + bool isSingleColor(Color32 mask = Color32(0xFF, 0xFF, 0xFF, 0x00)) const; bool hasAlpha() const; - - + + // Accessors const Color32 * colors() const; Color32 color(uint i) const; Color32 & color(uint i); - + Color32 color(uint x, uint y) const; Color32 & color(uint x, uint y); - + private: - + Color32 m_color[4 * 4]; - + }; diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp index 7c11fca3c342..df9182c2c1e1 100644 --- a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp +++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp @@ -33,7 +33,7 @@ */ // Copyright NVIDIA Corporation 2007 -- Ignacio Castano -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -42,10 +42,10 @@ // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -84,7 +84,7 @@ static const uint FOURCC_ATI1 = DDS_MAKEFOURCC('A', 'T', 'I', '1'); static const uint FOURCC_ATI2 = DDS_MAKEFOURCC('A', 'T', 'I', '2'); //static const uint FOURCC_A2XY = DDS_MAKEFOURCC('A', '2', 'X', 'Y'); - + static const uint FOURCC_DX10 = DDS_MAKEFOURCC('D', 'X', '1', '0'); static const uint FOURCC_UVER = DDS_MAKEFOURCC('U', 'V', 'E', 'R'); @@ -112,7 +112,7 @@ static const uint D3DFMT_A2R10G10B10 = 35; // Palette formats. //static const uint D3DFMT_A8P8 = 40; //static const uint D3DFMT_P8 = 41; - + // Luminance formats. static const uint D3DFMT_L8 = 50; //static const uint D3DFMT_A8L8 = 51; @@ -126,7 +126,7 @@ static const uint D3DFMT_L16 = 81; //static const uint D3DFMT_R32F = 114; //static const uint D3DFMT_G32R32F = 115; //static const uint D3DFMT_A32B32G32R32F = 116; - + static const uint DDSD_CAPS = 0x00000001U; static const uint DDSD_PIXELFORMAT = 0x00001000U; static const uint DDSD_WIDTH = 0x00000004U; @@ -135,7 +135,7 @@ static const uint DDSD_PITCH = 0x00000008U; static const uint DDSD_MIPMAPCOUNT = 0x00020000U; static const uint DDSD_LINEARSIZE = 0x00080000U; static const uint DDSD_DEPTH = 0x00800000U; - + static const uint DDSCAPS_COMPLEX = 0x00000008U; static const uint DDSCAPS_TEXTURE = 0x00001000U; static const uint DDSCAPS_MIPMAP = 0x00400000U; @@ -162,78 +162,78 @@ static const uint DDPF_LUMINANCE = 0x00020000U; static const uint DDPF_ALPHAPREMULT = 0x00008000U; // Custom NVTT flags. -static const uint DDPF_NORMAL = 0x80000000U; +static const uint DDPF_NORMAL = 0x80000000U; static const uint DDPF_SRGB = 0x40000000U; // DX10 formats. enum DXGI_FORMAT { DXGI_FORMAT_UNKNOWN = 0, - + DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R32G32B32A32_UINT = 3, DXGI_FORMAT_R32G32B32A32_SINT = 4, - + DXGI_FORMAT_R32G32B32_TYPELESS = 5, DXGI_FORMAT_R32G32B32_FLOAT = 6, DXGI_FORMAT_R32G32B32_UINT = 7, DXGI_FORMAT_R32G32B32_SINT = 8, - + DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_R16G16B16A16_UNORM = 11, DXGI_FORMAT_R16G16B16A16_UINT = 12, DXGI_FORMAT_R16G16B16A16_SNORM = 13, DXGI_FORMAT_R16G16B16A16_SINT = 14, - + DXGI_FORMAT_R32G32_TYPELESS = 15, DXGI_FORMAT_R32G32_FLOAT = 16, DXGI_FORMAT_R32G32_UINT = 17, DXGI_FORMAT_R32G32_SINT = 18, - + DXGI_FORMAT_R32G8X24_TYPELESS = 19, DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, - + DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DXGI_FORMAT_R10G10B10A2_UNORM = 24, DXGI_FORMAT_R10G10B10A2_UINT = 25, - + DXGI_FORMAT_R11G11B10_FLOAT = 26, - + DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DXGI_FORMAT_R8G8B8A8_UNORM = 28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DXGI_FORMAT_R8G8B8A8_UINT = 30, DXGI_FORMAT_R8G8B8A8_SNORM = 31, DXGI_FORMAT_R8G8B8A8_SINT = 32, - + DXGI_FORMAT_R16G16_TYPELESS = 33, DXGI_FORMAT_R16G16_FLOAT = 34, DXGI_FORMAT_R16G16_UNORM = 35, DXGI_FORMAT_R16G16_UINT = 36, DXGI_FORMAT_R16G16_SNORM = 37, DXGI_FORMAT_R16G16_SINT = 38, - + DXGI_FORMAT_R32_TYPELESS = 39, DXGI_FORMAT_D32_FLOAT = 40, DXGI_FORMAT_R32_FLOAT = 41, DXGI_FORMAT_R32_UINT = 42, DXGI_FORMAT_R32_SINT = 43, - + DXGI_FORMAT_R24G8_TYPELESS = 44, DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, - + DXGI_FORMAT_R8G8_TYPELESS = 48, DXGI_FORMAT_R8G8_UNORM = 49, DXGI_FORMAT_R8G8_UINT = 50, DXGI_FORMAT_R8G8_SNORM = 51, DXGI_FORMAT_R8G8_SINT = 52, - + DXGI_FORMAT_R16_TYPELESS = 53, DXGI_FORMAT_R16_FLOAT = 54, DXGI_FORMAT_D16_UNORM = 55, @@ -241,41 +241,41 @@ static const uint DDPF_SRGB = 0x40000000U; DXGI_FORMAT_R16_UINT = 57, DXGI_FORMAT_R16_SNORM = 58, DXGI_FORMAT_R16_SINT = 59, - + DXGI_FORMAT_R8_TYPELESS = 60, DXGI_FORMAT_R8_UNORM = 61, DXGI_FORMAT_R8_UINT = 62, DXGI_FORMAT_R8_SNORM = 63, DXGI_FORMAT_R8_SINT = 64, DXGI_FORMAT_A8_UNORM = 65, - + DXGI_FORMAT_R1_UNORM = 66, - + DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, - + DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DXGI_FORMAT_G8R8_G8B8_UNORM = 69, - + DXGI_FORMAT_BC1_TYPELESS = 70, DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, - + DXGI_FORMAT_BC2_TYPELESS = 73, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, - + DXGI_FORMAT_BC3_TYPELESS = 76, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, - + DXGI_FORMAT_BC4_TYPELESS = 79, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, - + DXGI_FORMAT_BC5_TYPELESS = 82, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, - + DXGI_FORMAT_B5G6R5_UNORM = 85, DXGI_FORMAT_B5G5R5A1_UNORM = 86, DXGI_FORMAT_B8G8R8A8_UNORM = 87, @@ -312,71 +312,71 @@ static const uint DDPF_SRGB = 0x40000000U; switch (dxgiFormat) { CASE(UNKNOWN); - + CASE(R32G32B32A32_TYPELESS); CASE(R32G32B32A32_FLOAT); CASE(R32G32B32A32_UINT); CASE(R32G32B32A32_SINT); - + CASE(R32G32B32_TYPELESS); CASE(R32G32B32_FLOAT); CASE(R32G32B32_UINT); CASE(R32G32B32_SINT); - + CASE(R16G16B16A16_TYPELESS); CASE(R16G16B16A16_FLOAT); CASE(R16G16B16A16_UNORM); CASE(R16G16B16A16_UINT); CASE(R16G16B16A16_SNORM); CASE(R16G16B16A16_SINT); - + CASE(R32G32_TYPELESS); CASE(R32G32_FLOAT); CASE(R32G32_UINT); CASE(R32G32_SINT); - + CASE(R32G8X24_TYPELESS); CASE(D32_FLOAT_S8X24_UINT); CASE(R32_FLOAT_X8X24_TYPELESS); CASE(X32_TYPELESS_G8X24_UINT); - + CASE(R10G10B10A2_TYPELESS); CASE(R10G10B10A2_UNORM); CASE(R10G10B10A2_UINT); - + CASE(R11G11B10_FLOAT); - + CASE(R8G8B8A8_TYPELESS); CASE(R8G8B8A8_UNORM); CASE(R8G8B8A8_UNORM_SRGB); CASE(R8G8B8A8_UINT); CASE(R8G8B8A8_SNORM); CASE(R8G8B8A8_SINT); - + CASE(R16G16_TYPELESS); CASE(R16G16_FLOAT); CASE(R16G16_UNORM); CASE(R16G16_UINT); CASE(R16G16_SNORM); CASE(R16G16_SINT); - + CASE(R32_TYPELESS); CASE(D32_FLOAT); CASE(R32_FLOAT); CASE(R32_UINT); CASE(R32_SINT); - + CASE(R24G8_TYPELESS); CASE(D24_UNORM_S8_UINT); CASE(R24_UNORM_X8_TYPELESS); CASE(X24_TYPELESS_G8_UINT); - + CASE(R8G8_TYPELESS); CASE(R8G8_UNORM); CASE(R8G8_UINT); CASE(R8G8_SNORM); CASE(R8G8_SINT); - + CASE(R16_TYPELESS); CASE(R16_FLOAT); CASE(D16_UNORM); @@ -384,7 +384,7 @@ static const uint DDPF_SRGB = 0x40000000U; CASE(R16_UINT); CASE(R16_SNORM); CASE(R16_SINT); - + CASE(R8_TYPELESS); CASE(R8_UNORM); CASE(R8_UINT); @@ -393,28 +393,28 @@ static const uint DDPF_SRGB = 0x40000000U; CASE(A8_UNORM); CASE(R1_UNORM); - + CASE(R9G9B9E5_SHAREDEXP); - + CASE(R8G8_B8G8_UNORM); CASE(G8R8_G8B8_UNORM); CASE(BC1_TYPELESS); CASE(BC1_UNORM); CASE(BC1_UNORM_SRGB); - + CASE(BC2_TYPELESS); CASE(BC2_UNORM); CASE(BC2_UNORM_SRGB); - + CASE(BC3_TYPELESS); CASE(BC3_UNORM); CASE(BC3_UNORM_SRGB); - + CASE(BC4_TYPELESS); CASE(BC4_UNORM); CASE(BC4_SNORM); - + CASE(BC5_TYPELESS); CASE(BC5_UNORM); CASE(BC5_SNORM); @@ -424,12 +424,12 @@ static const uint DDPF_SRGB = 0x40000000U; CASE(B8G8R8A8_UNORM); CASE(B8G8R8X8_UNORM); - default: + default: return "UNKNOWN"; } #undef CASE } - + static const char * getD3d10ResourceDimensionString(D3D10_RESOURCE_DIMENSION resourceDimension) { switch (resourceDimension) @@ -686,7 +686,7 @@ void DDSHeader::setFormatCode(uint32 code) // set fourcc pixel format. this->pf.flags = DDPF_FOURCC; this->pf.fourcc = code; - + this->pf.bitcount = 0; this->pf.rmask = 0; this->pf.gmask = 0; @@ -803,7 +803,7 @@ void DDSHeader::swapBytes() this->pitch = POSH_LittleU32(this->pitch); this->depth = POSH_LittleU32(this->depth); this->mipmapcount = POSH_LittleU32(this->mipmapcount); - + for (int i = 0; i < 11; i++) { this->reserved[i] = POSH_LittleU32(this->reserved[i]); } @@ -898,12 +898,12 @@ bool DirectDrawSurface::isValid() const { return false; } - + const uint required = (DDSD_WIDTH|DDSD_HEIGHT/*|DDSD_CAPS|DDSD_PIXELFORMAT*/); if ( (header.flags & required) != required ) { return false; } - + if (header.pf.size != 32) { return false; } @@ -958,20 +958,20 @@ bool DirectDrawSurface::isSupported() const { return false; } - + if (isTextureCube() && (header.caps.caps2 & DDSCAPS2_CUBEMAP_ALL_FACES) != DDSCAPS2_CUBEMAP_ALL_FACES) { // Cubemaps must contain all faces. return false; } - + if (isTexture3D()) { // @@ 3D textures not supported yet. return false; } } - + return true; } @@ -980,14 +980,14 @@ bool DirectDrawSurface::hasAlpha() const if (header.hasDX10Header()) { /* TODO: Update hasAlpha to handle all DX10 formats. */ - return + return header.header10.dxgiFormat == DXGI_FORMAT_BC1_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC2_UNORM || header.header10.dxgiFormat == DXGI_FORMAT_BC3_UNORM; } else { - if (header.pf.flags & DDPF_RGB) + if (header.pf.flags & DDPF_RGB) { return header.pf.amask != 0; } @@ -1096,19 +1096,19 @@ void DirectDrawSurface::setUserVersion(int version) void DirectDrawSurface::mipmap(Image *img, uint face, uint mipmap) { stream.seek(offset(face, mipmap)); - + uint w = width(); uint h = height(); - + // Compute width and height. for (uint m = 0; m < mipmap; m++) { w = MAX(1U, w / 2); h = MAX(1U, h / 2); } - + img->allocate(w, h); - + if (hasAlpha()) { img->setFormat(Image::Format_ARGB); @@ -1125,7 +1125,7 @@ void DirectDrawSurface::mipmap(Image *img, uint face, uint mipmap) } else { - if (header.pf.flags & DDPF_RGB) + if (header.pf.flags & DDPF_RGB) { readLinearImage(img); } @@ -1161,19 +1161,19 @@ void* DirectDrawSurface::readData(uint &rsize) void DirectDrawSurface::readLinearImage(Image *img) { - + const uint w = img->width(); const uint h = img->height(); - + uint rshift, rsize; PixelFormat::maskShiftAndSize(header.pf.rmask, &rshift, &rsize); - + uint gshift, gsize; PixelFormat::maskShiftAndSize(header.pf.gmask, &gshift, &gsize); - + uint bshift, bsize; PixelFormat::maskShiftAndSize(header.pf.bmask, &bshift, &bsize); - + uint ashift, asize; PixelFormat::maskShiftAndSize(header.pf.amask, &ashift, &asize); @@ -1210,19 +1210,19 @@ void DirectDrawSurface::readBlockImage(Image *img) const uint w = img->width(); const uint h = img->height(); - + const uint bw = (w + 3) / 4; const uint bh = (h + 3) / 4; - + for (uint by = 0; by < bh; by++) { for (uint bx = 0; bx < bw; bx++) { ColorBlock block; - + // Read color block. readBlock(&block); - + // Write color block. for (uint y = 0; y < MIN(4U, h-4*by); y++) { @@ -1242,7 +1242,7 @@ static Color32 buildNormal(uint8 x, uint8 y) float nz = 0.0f; if (1 - nx*nx - ny*ny > 0) nz = sqrt(1 - nx*nx - ny*ny); uint8 z = CLAMP(int(255.0f * (nz + 1) / 2.0f), 0, 255); - + return Color32(x, y, z); } @@ -1282,7 +1282,7 @@ void DirectDrawSurface::readBlock(ColorBlock *rgba) BlockDXT5 block; mem_read(stream, block); block.decodeBlock(rgba); - + if (fourcc == FOURCC_RXGB) { // Swap R & A. @@ -1307,7 +1307,7 @@ void DirectDrawSurface::readBlock(ColorBlock *rgba) mem_read(stream, block); block.decodeBlock(rgba); } - + // If normal flag set, convert to normal. if (header.pf.flags & DDPF_NORMAL) { @@ -1377,7 +1377,7 @@ uint DirectDrawSurface::mipmapSize(uint mipmap) const uint w = width(); uint h = height(); uint d = depth(); - + for (uint m = 0; m < mipmap; m++) { w = MAX(1U, w / 2); @@ -1408,19 +1408,19 @@ uint DirectDrawSurface::faceSize() const { const uint count = mipmapCount(); uint size = 0; - + for (uint m = 0; m < count; m++) { size += mipmapSize(m); } - + return size; } uint DirectDrawSurface::offset(const uint face, const uint mipmap) { uint size = 128; // sizeof(DDSHeader); - + if (header.hasDX10Header()) { size += 20; // sizeof(DDSHeader10); @@ -1430,12 +1430,12 @@ uint DirectDrawSurface::offset(const uint face, const uint mipmap) { size += face * faceSize(); } - + for (uint m = 0; m < mipmap; m++) { size += mipmapSize(m); } - + return size; } @@ -1458,7 +1458,7 @@ void DirectDrawSurface::printInfo() const if (header.flags & DDSD_PITCH) printf("Pitch: %u\n", header.pitch); else if (header.flags & DDSD_LINEARSIZE) printf("Linear size: %u\n", header.pitch); printf("Mipmap count: %u\n", header.mipmapcount); - + printf("Pixel Format:\n"); printf("\tFlags: 0x%.8X\n", header.pf.flags); if (header.pf.flags & DDPF_RGB) printf("\t\tDDPF_RGB\n"); @@ -1472,7 +1472,7 @@ void DirectDrawSurface::printInfo() const if (header.pf.flags & DDPF_PALETTEINDEXED8) printf("\t\tDDPF_PALETTEINDEXED8\n"); if (header.pf.flags & DDPF_ALPHAPREMULT) printf("\t\tDDPF_ALPHAPREMULT\n"); if (header.pf.flags & DDPF_NORMAL) printf("\t\tDDPF_NORMAL\n"); - + if (header.pf.fourcc != 0) { // Display fourcc code even when DDPF_FOURCC flag not set. printf("\tFourCC: '%c%c%c%c' (0x%.8X)\n", @@ -1541,7 +1541,7 @@ void DirectDrawSurface::printInfo() const int major = (header.reserved[10] >> 16) & 0xFF; int minor = (header.reserved[10] >> 8) & 0xFF; int revision= header.reserved[10] & 0xFF; - + printf("Version:\n"); printf("\tNVIDIA Texture Tools %d.%d.%d\n", major, minor, revision); } @@ -1551,4 +1551,3 @@ void DirectDrawSurface::printInfo() const printf("User Version: %u\n", header.reserved[8]); } } - diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.h b/source/blender/imbuf/intern/dds/DirectDrawSurface.h index 44c27a98c1d9..b7bcb8303bf8 100644 --- a/source/blender/imbuf/intern/dds/DirectDrawSurface.h +++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.h @@ -33,7 +33,7 @@ */ // Copyright NVIDIA Corporation 2007 -- Ignacio Castano -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -42,10 +42,10 @@ // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -109,7 +109,7 @@ struct DDSHeader { // Helper methods. DDSHeader(); - + void setWidth(uint w); void setHeight(uint h); void setDepth(uint d); @@ -128,9 +128,9 @@ struct DDSHeader { void setSrgbFlag(bool b); void setHasAlphaFlag(bool b); void setUserVersion(int version); - + /*void swapBytes();*/ - + bool hasDX10Header() const; uint signature() const; uint toolVersion() const; @@ -147,12 +147,12 @@ class DirectDrawSurface public: DirectDrawSurface(unsigned char *mem, uint size); ~DirectDrawSurface(); - + bool isValid() const; bool isSupported() const; bool hasAlpha() const; - + uint mipmapCount() const; uint fourCC() const; uint width() const; @@ -166,26 +166,26 @@ class DirectDrawSurface void setNormalFlag(bool b); void setHasAlphaFlag(bool b); void setUserVersion(int version); - + void mipmap(Image *img, uint f, uint m); void *readData(uint &size); // void mipmap(FloatImage *img, uint f, uint m); - + void printInfo() const; private: - + uint blockSize() const; uint faceSize() const; uint mipmapSize(uint m) const; - + uint offset(uint f, uint m); - + void readLinearImage(Image * img); void readBlockImage(Image * img); void readBlock(ColorBlock * rgba); - - + + private: Stream stream; // memory where DDS file resides DDSHeader header; diff --git a/source/blender/imbuf/intern/dds/FlipDXT.cpp b/source/blender/imbuf/intern/dds/FlipDXT.cpp index 604796d17056..336d891fa3a2 100644 --- a/source/blender/imbuf/intern/dds/FlipDXT.cpp +++ b/source/blender/imbuf/intern/dds/FlipDXT.cpp @@ -252,4 +252,3 @@ int FlipDXTCImage(unsigned int width, unsigned int height, unsigned int levels, return 1; } - diff --git a/source/blender/imbuf/intern/dds/FlipDXT.h b/source/blender/imbuf/intern/dds/FlipDXT.h index 892c49bc5d2b..6d4b2390255f 100644 --- a/source/blender/imbuf/intern/dds/FlipDXT.h +++ b/source/blender/imbuf/intern/dds/FlipDXT.h @@ -29,4 +29,3 @@ int FlipDXTCImage(unsigned int width, unsigned int height, unsigned int levels, int fourcc, uint8_t *data); #endif - diff --git a/source/blender/imbuf/intern/dds/Image.cpp b/source/blender/imbuf/intern/dds/Image.cpp index 363af61b9079..fd3ca1c35e64 100644 --- a/source/blender/imbuf/intern/dds/Image.cpp +++ b/source/blender/imbuf/intern/dds/Image.cpp @@ -129,5 +129,3 @@ void Image::setFormat(Image::Format f) { m_format = f; } - - diff --git a/source/blender/imbuf/intern/dds/Image.h b/source/blender/imbuf/intern/dds/Image.h index 658f01deaecf..bb74a9d5d15c 100644 --- a/source/blender/imbuf/intern/dds/Image.h +++ b/source/blender/imbuf/intern/dds/Image.h @@ -44,45 +44,45 @@ class Image { public: - - enum Format + + enum Format { Format_RGB, Format_ARGB, }; - + Image(); ~Image(); - + void allocate(uint w, uint h); #if 0 bool load(const char *name); - + void wrap(void *data, uint w, uint h); void unwrap(); #endif - + uint width() const; uint height() const; - + const Color32 * scanline(uint h) const; Color32 * scanline(uint h); - + const Color32 * pixels() const; Color32 * pixels(); - + const Color32 & pixel(uint idx) const; Color32 & pixel(uint idx); - + const Color32 & pixel(uint x, uint y) const; Color32 & pixel(uint x, uint y); - + Format format() const; void setFormat(Format f); - + private: void free(); - + private: uint m_width; uint m_height; diff --git a/source/blender/imbuf/intern/dds/PixelFormat.h b/source/blender/imbuf/intern/dds/PixelFormat.h index e841e696833f..e37e09dd6611 100644 --- a/source/blender/imbuf/intern/dds/PixelFormat.h +++ b/source/blender/imbuf/intern/dds/PixelFormat.h @@ -33,7 +33,7 @@ */ // Copyright NVIDIA Corporation 2007 -- Ignacio Castano -// +// // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without @@ -42,10 +42,10 @@ // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -93,7 +93,7 @@ ++(*shift); mask >>= 1; } - + *size = 0; while ((mask & 1) == 1) { ++(*size); diff --git a/source/blender/imbuf/intern/dds/Stream.cpp b/source/blender/imbuf/intern/dds/Stream.cpp index d8387b92530e..1af10905e64e 100644 --- a/source/blender/imbuf/intern/dds/Stream.cpp +++ b/source/blender/imbuf/intern/dds/Stream.cpp @@ -99,4 +99,3 @@ unsigned int mem_read(Stream & mem, unsigned char *i, unsigned int cnt) mem.pos += cnt; return(cnt); } - diff --git a/source/blender/imbuf/intern/dds/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp index 67a0b0ffd003..c038407c0a68 100644 --- a/source/blender/imbuf/intern/dds/dds_api.cpp +++ b/source/blender/imbuf/intern/dds/dds_api.cpp @@ -143,7 +143,7 @@ struct ImBuf *imb_load_dds(const unsigned char *mem, size_t size, int flags, cha } } } - ibuf = IMB_allocImBuf(dds.width(), dds.height(), bits_per_pixel, 0); + ibuf = IMB_allocImBuf(dds.width(), dds.height(), bits_per_pixel, 0); if (ibuf == 0) return(0); /* memory allocation failed */ ibuf->ftype = IMB_FTYPE_DDS; diff --git a/source/blender/imbuf/intern/divers.c b/source/blender/imbuf/intern/divers.c index 769d53a44ef3..2b6fa573e632 100644 --- a/source/blender/imbuf/intern/divers.c +++ b/source/blender/imbuf/intern/divers.c @@ -50,24 +50,24 @@ void IMB_de_interlace(ImBuf *ibuf) { ImBuf *tbuf1, *tbuf2; - + if (ibuf == NULL) return; if (ibuf->flags & IB_fields) return; ibuf->flags |= IB_fields; - + if (ibuf->rect) { /* make copies */ tbuf1 = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 32, IB_rect); tbuf2 = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 32, IB_rect); - + ibuf->x *= 2; IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y); IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y); - + ibuf->x /= 2; IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y); IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y); - + IMB_freeImBuf(tbuf1); IMB_freeImBuf(tbuf2); } diff --git a/source/blender/imbuf/intern/filetype.c b/source/blender/imbuf/intern/filetype.c index 7ed5c8ffbcb1..25bbd132a495 100644 --- a/source/blender/imbuf/intern/filetype.c +++ b/source/blender/imbuf/intern/filetype.c @@ -77,7 +77,7 @@ const ImFileType IMB_FILE_TYPES[] = { {imb_initopenexr, NULL, imb_is_a_openexr, NULL, imb_ftype_default, imb_load_openexr, NULL, imb_save_openexr, NULL, IM_FTYPE_FLOAT, IMB_FTYPE_OPENEXR, COLOR_ROLE_DEFAULT_FLOAT}, #endif #ifdef WITH_OPENJPEG - {NULL, NULL, imb_is_a_jp2, NULL, imb_ftype_default, imb_jp2_decode, NULL, imb_savejp2, NULL, IM_FTYPE_FLOAT, IMB_FTYPE_JP2, COLOR_ROLE_DEFAULT_BYTE}, + {NULL, NULL, imb_is_a_jp2, NULL, imb_ftype_default, imb_load_jp2, NULL, imb_save_jp2, NULL, IM_FTYPE_FLOAT, IMB_FTYPE_JP2, COLOR_ROLE_DEFAULT_BYTE}, #endif #ifdef WITH_DDS {NULL, NULL, imb_is_a_dds, NULL, imb_ftype_default, imb_load_dds, NULL, NULL, NULL, 0, IMB_FTYPE_DDS, COLOR_ROLE_DEFAULT_BYTE}, @@ -107,4 +107,3 @@ void imb_filetypes_exit(void) if (type->exit) type->exit(); } - diff --git a/source/blender/imbuf/intern/filter.c b/source/blender/imbuf/intern/filter.c index 902fc6482da6..decbfd6d5b91 100644 --- a/source/blender/imbuf/intern/filter.c +++ b/source/blender/imbuf/intern/filter.c @@ -69,7 +69,7 @@ static void filtrow(unsigned char *point, int x) static void filtrowf(float *point, int x) { float c1, c2, c3; - + if (x > 1) { c1 = c2 = *point; for (x--; x > 0; x--) { @@ -112,7 +112,7 @@ static void filtcolum(unsigned char *point, int y, int skip) static void filtcolumf(float *point, int y, int skip) { float c1, c2, c3, *point2; - + if (y > 1) { c1 = c2 = *point; point2 = point; @@ -211,7 +211,7 @@ static void imb_filterN(ImBuf *out, ImBuf *in) const int channels = in->channels; const int rowlen = in->x; - + if (in->rect && out->rect) { for (int y = 0; y < in->y; y++) { /* setup rows */ @@ -515,13 +515,13 @@ void IMB_remakemipmap(ImBuf *ibuf, int use_filter) { ImBuf *hbuf = ibuf; int curmap = 0; - + ibuf->miptot = 1; - + while (curmap < IMB_MIPMAP_LEVELS) { - + if (ibuf->mipmap[curmap]) { - + if (use_filter) { ImBuf *nbuf = IMB_allocImBuf(hbuf->x, hbuf->y, hbuf->planes, hbuf->flags); imb_filterN(nbuf, hbuf); @@ -531,15 +531,15 @@ void IMB_remakemipmap(ImBuf *ibuf, int use_filter) else imb_onehalf_no_alloc(ibuf->mipmap[curmap], hbuf); } - + ibuf->miptot = curmap + 2; hbuf = ibuf->mipmap[curmap]; if (hbuf) hbuf->miplevel = curmap + 1; - + if (!hbuf || (hbuf->x <= 2 && hbuf->y <= 2)) break; - + curmap++; } } @@ -551,11 +551,11 @@ void IMB_makemipmap(ImBuf *ibuf, int use_filter) int curmap = 0; imb_freemipmapImBuf(ibuf); - + /* no mipmap for non RGBA images */ if (ibuf->rect_float && ibuf->channels < 4) return; - + ibuf->miptot = 1; while (curmap < IMB_MIPMAP_LEVELS) { diff --git a/source/blender/imbuf/intern/imageprocess.c b/source/blender/imbuf/intern/imageprocess.c index 0f5fd6518fb1..2eec5da7bc42 100644 --- a/source/blender/imbuf/intern/imageprocess.c +++ b/source/blender/imbuf/intern/imageprocess.c @@ -87,10 +87,10 @@ static void pixel_from_buffer(struct ImBuf *ibuf, unsigned char **outI, float ** { size_t offset = ((size_t)ibuf->x) * y * 4 + 4 * x; - + if (ibuf->rect) *outI = (unsigned char *)ibuf->rect + offset; - + if (ibuf->rect_float) *outF = ibuf->rect_float + offset; } @@ -112,13 +112,13 @@ void bicubic_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, in { unsigned char *outI = NULL; float *outF = NULL; - + if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) { return; } - + pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */ - + bicubic_interpolation_color(in, outI, outF, u, v); } @@ -145,8 +145,8 @@ void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char outI[4], unsigned char *row1I, *row2I, *row3I, *row4I; float a_b, ma_b, a_mb, ma_mb; int y1, y2, x1, x2; - - + + /* ImBuf in must have a valid rect or rect_float, assume this is already checked */ x1 = (int)floor(u); @@ -194,7 +194,7 @@ void bilinear_interpolation_color_wrap(struct ImBuf *in, unsigned char outI[4], row2I = (unsigned char *)in->rect + ((size_t)in->x) * y2 * 4 + 4 * x1; row3I = (unsigned char *)in->rect + ((size_t)in->x) * y1 * 4 + 4 * x2; row4I = (unsigned char *)in->rect + ((size_t)in->x) * y2 * 4 + 4 * x2; - + /* need to add 0.5 to avoid rounding down (causes darken with the smear brush) * tested with white images and this should not wrap back to zero */ outI[0] = (ma_mb * row1I[0] + a_mb * row3I[0] + ma_b * row2I[0] + a_b * row4I[0]) + 0.5f; @@ -208,13 +208,13 @@ void bilinear_interpolation(ImBuf *in, ImBuf *out, float u, float v, int xout, i { unsigned char *outI = NULL; float *outF = NULL; - + if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) { return; } - + pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */ - + bilinear_interpolation_color(in, outI, outF, u, v); } @@ -227,7 +227,7 @@ void nearest_interpolation_color(struct ImBuf *in, unsigned char outI[4], float int y1, x1; /* ImBuf in must have a valid rect or rect_float, assume this is already checked */ - + x1 = (int)(u); y1 = (int)(v); @@ -316,9 +316,9 @@ void nearest_interpolation(ImBuf *in, ImBuf *out, float x, float y, int xout, in if (in == NULL || (in->rect == NULL && in->rect_float == NULL)) { return; } - + pixel_from_buffer(out, &outI, &outF, xout, yout); /* gcc warns these could be uninitialized, but its ok */ - + nearest_interpolation_color(in, outI, outF, x, y); } diff --git a/source/blender/imbuf/intern/imbuf.h b/source/blender/imbuf/intern/imbuf.h index 90dad70fa61a..051622905380 100644 --- a/source/blender/imbuf/intern/imbuf.h +++ b/source/blender/imbuf/intern/imbuf.h @@ -34,7 +34,7 @@ #include #include -#include +#include #ifndef WIN32 # include @@ -70,4 +70,3 @@ #define IMB_DPI_DEFAULT 72.0f #endif /* __IMBUF_H__ */ - diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c index eaf4dfd84b4c..167f2e4f8e0c 100644 --- a/source/blender/imbuf/intern/indexer.c +++ b/source/blender/imbuf/intern/indexer.c @@ -142,7 +142,7 @@ void IMB_index_builder_finish(anim_index_builder *fp, int rollback) } fclose(fp->fp); - + if (rollback) { unlink(fp->temp_name); } @@ -185,7 +185,7 @@ struct anim_index *IMB_indexer_open(const char *name) idx = MEM_callocN(sizeof(struct anim_index), "anim_index"); BLI_strncpy(idx->name, name, sizeof(idx->name)); - + fseek(fp, 0, SEEK_END); idx->num_entries = (ftell(fp) - 12) / @@ -257,7 +257,7 @@ int IMB_indexer_get_frame_index(struct anim_index *idx, int frameno) int first = 0; /* bsearch (lower bound) the right index */ - + while (len > 0) { half = len >> 1; middle = first; @@ -389,7 +389,7 @@ static void get_proxy_filename(struct anim *anim, IMB_Proxy_Size preview_size, char proxy_name[256]; char stream_suffix[20]; const char *name = (temp) ? "proxy_%d%s_part.avi" : "proxy_%d%s.avi"; - + stream_suffix[0] = 0; if (anim->streamindex > 0) { @@ -418,18 +418,18 @@ static void get_tc_filename(struct anim *anim, IMB_Timecode_Type tc, char stream_suffix[20]; char index_name[256]; - + stream_suffix[0] = 0; if (anim->streamindex > 0) { BLI_snprintf(stream_suffix, 20, "_st%d", anim->streamindex); } - + BLI_snprintf(index_name, 256, index_names[i], stream_suffix, anim->suffix); get_index_dir(anim, index_dir, sizeof(index_dir)); - - BLI_join_dirfile(fname, FILE_MAXFILE + FILE_MAXDIR, + + BLI_join_dirfile(fname, FILE_MAXFILE + FILE_MAXDIR, index_dir, index_name); } @@ -475,7 +475,7 @@ static struct proxy_output_ctx *alloc_proxy_output_ffmpeg( { struct proxy_output_ctx *rv = MEM_callocN( sizeof(struct proxy_output_ctx), "alloc_proxy_output"); - + char fname[FILE_MAX]; int ffmpeg_quality; @@ -491,7 +491,7 @@ static struct proxy_output_ctx *alloc_proxy_output_ffmpeg( rv->of = avformat_alloc_context(); rv->of->oformat = av_guess_format("avi", NULL, NULL); - + BLI_strncpy(rv->of->filename, fname, sizeof(rv->of->filename)); fprintf(stderr, "Starting work on proxy: %s\n", rv->of->filename); @@ -611,7 +611,7 @@ static int add_to_proxy_output_ffmpeg( ret = avcodec_encode_video2(ctx->c, &packet, frame, &got_output); if (ret < 0) { - fprintf(stderr, "Error encoding proxy frame %d for '%s'\n", + fprintf(stderr, "Error encoding proxy frame %d for '%s'\n", ctx->cfra - 1, ctx->of->filename); return 0; } @@ -661,9 +661,9 @@ static void free_proxy_output_ffmpeg(struct proxy_output_ctx *ctx, avcodec_flush_buffers(ctx->c); av_write_trailer(ctx->of); - + avcodec_close(ctx->c); - + if (ctx->of->oformat) { if (!(ctx->of->oformat->flags & AVFMT_NOFILE)) { avio_close(ctx->of->pb); @@ -678,19 +678,19 @@ static void free_proxy_output_ffmpeg(struct proxy_output_ctx *ctx, av_free(ctx->frame); } - get_proxy_filename(ctx->anim, ctx->proxy_size, + get_proxy_filename(ctx->anim, ctx->proxy_size, fname_tmp, true); if (rollback) { unlink(fname_tmp); } else { - get_proxy_filename(ctx->anim, ctx->proxy_size, + get_proxy_filename(ctx->anim, ctx->proxy_size, fname, false); unlink(fname); BLI_rename(fname_tmp, fname); } - + MEM_freeN(ctx); } @@ -883,7 +883,7 @@ static void index_rebuild_ffmpeg_proc_decoded_frame( if (tc_types[i] == IMB_TC_RECORD_RUN_NO_GAPS) tc_frameno = context->frameno_gapless; - + IMB_index_builder_proc_frame( context->indexer[i], curr_packet->data, @@ -892,7 +892,7 @@ static void index_rebuild_ffmpeg_proc_decoded_frame( s_pos, s_dts, pts); } } - + context->frameno_gapless++; } @@ -1006,12 +1006,12 @@ static AviMovie *alloc_proxy_output_avi( float frs_sec_base = 1.0; IMB_anim_get_fps(anim, &frs_sec, &frs_sec_base, false); - + x = width; y = height; framerate = (double) frs_sec / (double) frs_sec_base; - + avi = MEM_mallocN(sizeof(AviMovie), "avimovie"); format = AVI_FORMAT_MJPEG; @@ -1020,7 +1020,7 @@ static AviMovie *alloc_proxy_output_avi( MEM_freeN(avi); return NULL; } - + AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_WIDTH, &x); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_HEIGHT, &y); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_QUALITY, &quality); @@ -1111,7 +1111,7 @@ static void index_rebuild_fallback(FallbackIndexBuilderContext *context, *progress = next_progress; *do_update = true; } - + if (*stop) { break; } @@ -1128,7 +1128,7 @@ static void index_rebuild_fallback(FallbackIndexBuilderContext *context, IMB_scalefastImBuf(s_ibuf, x, y); IMB_convert_rgba_to_abgr(s_ibuf); - + AVI_write_frame(context->proxy_ctx[i], pos, AVI_FORMAT_RGB32, s_ibuf->rect, x * y * 4); @@ -1178,7 +1178,7 @@ IndexBuildContext *IMB_anim_index_rebuild_context(struct anim *anim, IMB_Timecod } } } - + if (!overwrite) { IMB_Proxy_Size built_proxies = IMB_anim_proxy_get_existing(anim); if (built_proxies != 0) { @@ -1194,13 +1194,13 @@ IndexBuildContext *IMB_anim_index_rebuild_context(struct anim *anim, IMB_Timecod } proxy_sizes_to_build &= ~built_proxies; } - + fflush(stdout); if (proxy_sizes_to_build == 0) { return NULL; } - + switch (anim->curtype) { #ifdef WITH_FFMPEG @@ -1313,7 +1313,7 @@ struct anim *IMB_anim_open_proxy( /* proxies are generated in the same color space as animation itself */ anim->proxy_anim[i] = IMB_open_anim(fname, 0, 0, anim->colorspace); - + anim->proxies_tried |= preview_size; return anim->proxy_anim[i]; @@ -1336,7 +1336,7 @@ struct anim_index *IMB_anim_open_index( get_tc_filename(anim, tc, fname); anim->curr_idx[i] = IMB_indexer_open(fname); - + anim->indices_tried |= tc; return anim->curr_idx[i]; diff --git a/source/blender/imbuf/intern/iris.c b/source/blender/imbuf/intern/iris.c index 11b1fd7b1c24..ba48feb01e8f 100644 --- a/source/blender/imbuf/intern/iris.c +++ b/source/blender/imbuf/intern/iris.c @@ -141,7 +141,7 @@ static ushort getshort(MFileOffset *inf) static uint getlong(MFileOffset *mofs) { const uchar *buf; - + buf = MFILE_DATA(mofs); MFILE_STEP(mofs, 4); @@ -220,13 +220,13 @@ static void test_endian_zbuf(struct ImBuf *ibuf) { int len; int *zval; - + if (BIG_LONG(1) == 1) return; if (ibuf->zbuf == NULL) return; - + len = ibuf->x * ibuf->y; zval = ibuf->zbuf; - + while (len--) { zval[0] = BIG_LONG(zval[0]); zval++; @@ -301,7 +301,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors if (ibuf) ibuf->ftype = IMB_FTYPE_IMAGIC; return(ibuf); } - + if (rle) { size_t tablen = (size_t)ysize * (size_t)zsize * sizeof(int); MFILE_SEEK(inf, HEADER_SIZE); @@ -316,7 +316,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors readtab(inf, starttab, tablen); readtab(inf, lengthtab, tablen); - + /* check data order */ cur = 0; badorder = 0; @@ -331,9 +331,9 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors if (badorder) break; } - + if (bpp == 1) { - + ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect); if (!ibuf) { goto fail_rle; @@ -341,7 +341,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors if (ibuf->planes > 32) ibuf->planes = 32; base = ibuf->rect; zbase = (uint *)ibuf->zbuf; - + if (badorder) { for (size_t z = 0; z < zsize; z++) { lptr = base; @@ -382,18 +382,18 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors zptr = zptr_next; } } - + } else { /* bpp == 2 */ - + ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat); if (!ibuf) { goto fail_rle; } fbase = ibuf->rect_float; - + if (badorder) { for (size_t z = 0; z < zsize; z++) { fptr = fbase; @@ -414,7 +414,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors float *fptr_next = fptr + (xsize * 4); for (size_t y = 0; y < ysize; y++) { - + for (size_t z = 0; z < zsize; z++) { MFILE_SEEK(inf, starttab[y + z * ysize]); rledat = MFILE_DATA(inf); @@ -442,7 +442,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors if (UNLIKELY((p) > mem_end)) { dirty_flag |= DIRTY_FLAG_EOF; goto fail_uncompressed; } ((void)0) if (bpp == 1) { - + ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect); if (!ibuf) { goto fail_uncompressed; @@ -451,12 +451,12 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors base = ibuf->rect; zbase = (uint *)ibuf->zbuf; - + MFILE_SEEK(inf, HEADER_SIZE); rledat = MFILE_DATA(inf); - + for (size_t z = 0; z < zsize; z++) { - + if (z < 4) lptr = base; else if (z < 8) lptr = zbase; @@ -469,10 +469,10 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors lptr += xsize; } } - + } else { /* bpp == 2 */ - + ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat); if (!ibuf) { goto fail_uncompressed; @@ -482,9 +482,9 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors MFILE_SEEK(inf, HEADER_SIZE); rledat = MFILE_DATA(inf); - + for (size_t z = 0; z < zsize; z++) { - + fptr = fbase; for (size_t y = 0; y < ysize; y++) { @@ -496,7 +496,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors fptr += xsize * 4; } } - + } #undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL fail_uncompressed: @@ -507,7 +507,7 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors if (bpp == 1) { uchar *rect; - + if (image.zsize == 1) { rect = (uchar *) ibuf->rect; for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) { @@ -533,10 +533,10 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors rect += 4; } } - + } else { /* bpp == 2 */ - + if (image.zsize == 1) { fbase = ibuf->rect_float; for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) { @@ -562,11 +562,11 @@ struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colors fbase += 4; } } - + if (flags & IB_rect) { IMB_rect_from_float(ibuf); } - + } if (dirty_flag) { @@ -816,10 +816,10 @@ static int output_iris(uint *lptr, int xsize, int ysize, int zsize, const char * goodwrite *= writeheader(outf, image); fseek(outf, HEADER_SIZE + (2 * tablen), SEEK_SET); pos = HEADER_SIZE + (2 * tablen); - + for (y = 0; y < ysize; y++) { for (z = 0; z < zsize; z++) { - + if (zsize == 1) { lumrow((uchar *)lptr, (uchar *)lumbuf, xsize); len = compressrow((uchar *)lumbuf, rlebuf, CHANOFFSET(z), xsize); @@ -939,7 +939,7 @@ int imb_saveiris(struct ImBuf *ibuf, const char *name, int flags) zsize = (ibuf->planes + 7) >> 3; if (flags & IB_zbuf && ibuf->zbuf != NULL) zsize = 8; - + IMB_convert_rgba_to_abgr(ibuf); test_endian_zbuf(ibuf); @@ -951,4 +951,3 @@ int imb_saveiris(struct ImBuf *ibuf, const char *name, int flags) return(ret); } - diff --git a/source/blender/imbuf/intern/jp2.c b/source/blender/imbuf/intern/jp2.c index 30a0fdf4e557..cd6bdd643d55 100644 --- a/source/blender/imbuf/intern/jp2.c +++ b/source/blender/imbuf/intern/jp2.c @@ -38,7 +38,1251 @@ #include "openjpeg.h" -// #define JP2_FILEHEADER_SIZE 14 /* UNUSED */ +/* Temporary duplicated implementations for version 1.5 and 2.3, until we + * upgrade all platforms to 2.3. When removing the old code, + * imb_load_jp2_filepath can be added in filetype.c. */ + +#if defined(OPJ_VERSION_MAJOR) && OPJ_VERSION_MAJOR >= 2 + +#define JP2_FILEHEADER_SIZE 12 + +static const char JP2_HEAD[] = {0x0, 0x0, 0x0, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A}; +static const char J2K_HEAD[] = {0xFF, 0x4F, 0xFF, 0x51, 0x00}; + +/* We only need this because of how the presets are set */ +/* this typedef is copied from 'openjpeg-1.5.0/applications/codec/image_to_j2k.c' */ +typedef struct img_folder { + /** The directory path of the folder containing input images*/ + char *imgdirpath; + /** Output format*/ + char *out_format; + /** Enable option*/ + char set_imgdir; + /** Enable Cod Format for output*/ + char set_out_format; + /** User specified rate stored in case of cinema option*/ + float *rates; +} img_fol_t; + +enum { + DCP_CINEMA2K = 3, + DCP_CINEMA4K = 4, +}; + +static bool check_jp2(const unsigned char *mem) /* J2K_CFMT */ +{ + return memcmp(JP2_HEAD, mem, sizeof(JP2_HEAD)) ? 0 : 1; +} + +static bool check_j2k(const unsigned char *mem) /* J2K_CFMT */ +{ + return memcmp(J2K_HEAD, mem, sizeof(J2K_HEAD)) ? 0 : 1; +} + +static OPJ_CODEC_FORMAT format_from_header(const unsigned char mem[JP2_FILEHEADER_SIZE]) +{ + if (check_jp2(mem)) { + return OPJ_CODEC_JP2; + } + else if (check_j2k(mem)) { + return OPJ_CODEC_J2K; + } + else { + return OPJ_CODEC_UNKNOWN; + } +} + +int imb_is_a_jp2(const unsigned char *buf) +{ + return check_jp2(buf); +} + +/** + * sample error callback expecting a FILE* client object + */ +static void error_callback(const char *msg, void *client_data) +{ + FILE *stream = (FILE *)client_data; + fprintf(stream, "[ERROR] %s", msg); +} +/** + * sample warning callback expecting a FILE* client object + */ +static void warning_callback(const char *msg, void *client_data) +{ + FILE *stream = (FILE *)client_data; + fprintf(stream, "[WARNING] %s", msg); +} + +#ifdef DEBUG +/** + * sample debug callback expecting no client object + */ +static void info_callback(const char *msg, void *client_data) +{ + FILE *stream = (FILE *)client_data; + fprintf(stream, "[INFO] %s", msg); +} +#endif + +# define PIXEL_LOOPER_BEGIN(_rect) \ + for (y = h - 1; y != (unsigned int)(-1); y--) { \ + for (i = y * w, i_next = (y + 1) * w; \ + i < i_next; \ + i++, _rect += 4) \ + { \ + +# define PIXEL_LOOPER_BEGIN_CHANNELS(_rect, _channels) \ + for (y = h - 1; y != (unsigned int)(-1); y--) { \ + for (i = y * w, i_next = (y + 1) * w; \ + i < i_next; \ + i++, _rect += _channels) \ + { \ + +# define PIXEL_LOOPER_END \ + } \ +} (void)0 \ + + +/** \name Buffer Stream + * \{ */ + +struct BufInfo { + const unsigned char *buf; + const unsigned char *cur; + off_t len; +}; + +static void opj_read_from_buffer_free(void *UNUSED(p_user_data)) +{ + /* nop */ +} + +static OPJ_SIZE_T opj_read_from_buffer(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) +{ + struct BufInfo *p_file = p_user_data; + OPJ_UINT32 l_nb_read; + + if (p_file->cur + p_nb_bytes < p_file->buf + p_file->len ) { + l_nb_read = p_nb_bytes; + } + else { + l_nb_read = (OPJ_UINT32)(p_file->buf + p_file->len - p_file->cur); + } + memcpy(p_buffer, p_file->cur, l_nb_read); + p_file->cur += l_nb_read; + + return l_nb_read ? l_nb_read : ((OPJ_SIZE_T)-1); +} + +#if 0 +static OPJ_SIZE_T opj_write_from_buffer(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) +{ + struct BufInfo *p_file = p_user_data; + memcpy(p_file->cur, p_buffer, p_nb_bytes); + p_file->cur += p_nb_bytes; + p_file->len += p_nb_bytes; + return p_nb_bytes; +} +#endif + +static OPJ_OFF_T opj_skip_from_buffer(OPJ_OFF_T p_nb_bytes, void *p_user_data) +{ + struct BufInfo *p_file = p_user_data; + if (p_file->cur + p_nb_bytes < p_file->buf + p_file->len) { + p_file->cur += p_nb_bytes; + return p_nb_bytes; + } + p_file->cur = p_file->buf + p_file->len; + return (OPJ_OFF_T)-1; +} + +static OPJ_BOOL opj_seek_from_buffer(OPJ_OFF_T p_nb_bytes, void *p_user_data) +{ + struct BufInfo *p_file = p_user_data; + if (p_nb_bytes < p_file->len) { + p_file->cur = p_file->buf + p_nb_bytes; + return OPJ_TRUE; + } + p_file->cur = p_file->buf + p_file->len; + return OPJ_FALSE; +} + +/** + * Stream wrapper for memory buffer + * (would be nice if this was supported by the API). + */ + +static opj_stream_t *opj_stream_create_from_buffer( + struct BufInfo *p_file, OPJ_UINT32 p_size, + OPJ_BOOL p_is_read_stream) +{ + opj_stream_t *l_stream = opj_stream_create(p_size, p_is_read_stream); + if (l_stream == NULL) { + return NULL; + } + opj_stream_set_user_data(l_stream, p_file, opj_read_from_buffer_free); + opj_stream_set_user_data_length(l_stream, p_file->len); + opj_stream_set_read_function(l_stream, opj_read_from_buffer); +#if 0 /* UNUSED */ + opj_stream_set_write_function(l_stream, opj_write_from_buffer); +#endif + opj_stream_set_skip_function(l_stream, opj_skip_from_buffer); + opj_stream_set_seek_function(l_stream, opj_seek_from_buffer); + + return l_stream; +} + +/** \} */ + + +/** \name File Stream + * \{ */ + +static void opj_free_from_file(void *p_user_data) +{ + FILE *f = p_user_data; + fclose(f); +} + +static OPJ_UINT64 opj_get_data_length_from_file (void *p_user_data) +{ + FILE *p_file = p_user_data; + OPJ_OFF_T file_length = 0; + + fseek(p_file, 0, SEEK_END); + file_length = ftell(p_file); + fseek(p_file, 0, SEEK_SET); + + return (OPJ_UINT64)file_length; +} + +static OPJ_SIZE_T opj_read_from_file(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) +{ + FILE *p_file = p_user_data; + OPJ_SIZE_T l_nb_read = fread(p_buffer, 1, p_nb_bytes, p_file); + return l_nb_read ? l_nb_read : (OPJ_SIZE_T)-1; +} + +static OPJ_SIZE_T opj_write_from_file(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) +{ + FILE *p_file = p_user_data; + return fwrite(p_buffer, 1, p_nb_bytes, p_file); +} + +static OPJ_OFF_T opj_skip_from_file(OPJ_OFF_T p_nb_bytes, void *p_user_data) +{ + FILE *p_file = p_user_data; + if (fseek(p_file, p_nb_bytes, SEEK_CUR)) { + return -1; + } + return p_nb_bytes; +} + +static OPJ_BOOL opj_seek_from_file(OPJ_OFF_T p_nb_bytes, void *p_user_data) +{ + FILE *p_file = p_user_data; + if (fseek(p_file, p_nb_bytes, SEEK_SET)) { + return OPJ_FALSE; + } + return OPJ_TRUE; +} + +/** + * Stream wrapper for memory file + * (would be nice if this was supported by the API). + */ + +static opj_stream_t *opj_stream_create_from_file( + const char *filepath, OPJ_UINT32 p_size, OPJ_BOOL p_is_read_stream, + FILE **r_file) +{ + FILE *p_file = BLI_fopen(filepath, p_is_read_stream ? "rb" : "wb"); + if (p_file == NULL) { + return NULL; + } + + opj_stream_t *l_stream = opj_stream_create(p_size, p_is_read_stream); + if (l_stream == NULL) { + fclose(p_file); + return NULL; + } + + opj_stream_set_user_data(l_stream, p_file, opj_free_from_file); + opj_stream_set_user_data_length(l_stream, opj_get_data_length_from_file(p_file)); + opj_stream_set_write_function(l_stream, opj_write_from_file); + opj_stream_set_read_function(l_stream, opj_read_from_file); + opj_stream_set_skip_function(l_stream, opj_skip_from_file); + opj_stream_set_seek_function(l_stream, opj_seek_from_file); + + if (r_file) { + *r_file = p_file; + } + return l_stream; +} + +/** \} */ + +static ImBuf *imb_load_jp2_stream( + opj_stream_t *stream, OPJ_CODEC_FORMAT p_format, + int flags, char colorspace[IM_MAX_SPACE]); + +ImBuf *imb_load_jp2(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]) +{ + const OPJ_CODEC_FORMAT format = (size > JP2_FILEHEADER_SIZE) ? format_from_header(mem) : OPJ_CODEC_UNKNOWN; + struct BufInfo buf_wrapper = { .buf = mem, .cur = mem, .len = size, }; + opj_stream_t *stream = opj_stream_create_from_buffer(&buf_wrapper, OPJ_J2K_STREAM_CHUNK_SIZE, true); + ImBuf *ibuf = imb_load_jp2_stream(stream, format, flags, colorspace); + opj_stream_destroy(stream); + return ibuf; +} + +ImBuf *imb_load_jp2_filepath(const char *filepath, int flags, char colorspace[IM_MAX_SPACE]) +{ + FILE *p_file = NULL; + unsigned char mem[JP2_FILEHEADER_SIZE]; + opj_stream_t *stream = opj_stream_create_from_file(filepath, OPJ_J2K_STREAM_CHUNK_SIZE, true, &p_file); + if (stream) { + return NULL; + } + else { + if (fread(mem, sizeof(mem), 1, p_file) != sizeof(mem)) { + opj_stream_destroy(stream); + return NULL; + } + else { + fseek(p_file, 0, SEEK_SET); + } + } + + const OPJ_CODEC_FORMAT format = format_from_header(mem); + ImBuf *ibuf = imb_load_jp2_stream(stream, format, flags, colorspace); + opj_stream_destroy(stream); + return ibuf; +} + + +static ImBuf *imb_load_jp2_stream( + opj_stream_t *stream, const OPJ_CODEC_FORMAT format, + int flags, char colorspace[IM_MAX_SPACE]) +{ + if (format == OPJ_CODEC_UNKNOWN) { + return NULL; + } + + struct ImBuf *ibuf = NULL; + bool use_float = false; /* for precision higher then 8 use float */ + bool use_alpha = false; + + long signed_offsets[4] = {0, 0, 0, 0}; + int float_divs[4] = {1, 1, 1, 1}; + + unsigned int i, i_next, w, h, planes; + unsigned int y; + int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */ + + opj_dparameters_t parameters; /* decompression parameters */ + + opj_image_t *image = NULL; + opj_codec_t *codec = NULL; /* handle to a decompressor */ + + /* both 8, 12 and 16 bit JP2Ks are default to standard byte colorspace */ + colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_BYTE); + + /* set decoding parameters to default values */ + opj_set_default_decoder_parameters(¶meters); + + /* JPEG 2000 compressed image data */ + + /* get a decoder handle */ + codec = opj_create_decompress(format); + + /* configure the event callbacks (not required) */ + opj_set_error_handler(codec, error_callback, stderr); + opj_set_warning_handler(codec, warning_callback, stderr); +#ifdef DEBUG /* too noisy */ + opj_set_info_handler(codec, info_callback, stderr); +#endif + + /* setup the decoder decoding parameters using the current image and user parameters */ + if (opj_setup_decoder(codec, ¶meters) == false) { + goto finally; + } + + if (opj_read_header(stream, codec, &image) == false) { + printf("OpenJPEG error: failed to read the header\n"); + goto finally; + } + + /* decode the stream and fill the image structure */ + if (opj_decode(codec, stream, image) == false) { + fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); + goto finally; + } + + if ((image->numcomps * image->x1 * image->y1) == 0) { + fprintf(stderr, "\nError: invalid raw image parameters\n"); + goto finally; + } + + w = image->comps[0].w; + h = image->comps[0].h; + + switch (image->numcomps) { + case 1: /* Grayscale */ + case 3: /* Color */ + planes = 24; + use_alpha = false; + break; + default: /* 2 or 4 - Grayscale or Color + alpha */ + planes = 32; /* grayscale + alpha */ + use_alpha = true; + break; + } + + + i = image->numcomps; + if (i > 4) i = 4; + + while (i) { + i--; + + if (image->comps[i].prec > 8) + use_float = true; + + if (image->comps[i].sgnd) + signed_offsets[i] = 1 << (image->comps[i].prec - 1); + + /* only needed for float images but dosnt hurt to calc this */ + float_divs[i] = (1 << image->comps[i].prec) - 1; + } + + ibuf = IMB_allocImBuf(w, h, planes, use_float ? IB_rectfloat : IB_rect); + + if (ibuf == NULL) { + goto finally; + } + + ibuf->ftype = IMB_FTYPE_JP2; + if (1 /* is_jp2 */ ) { + ibuf->foptions.flag |= JP2_JP2; + } + else { + ibuf->foptions.flag |= JP2_J2K; + } + + if (use_float) { + float *rect_float = ibuf->rect_float; + + if (image->numcomps < 3) { + r = image->comps[0].data; + a = (use_alpha) ? image->comps[1].data : NULL; + + /* grayscale 12bits+ */ + if (use_alpha) { + a = image->comps[1].data; + PIXEL_LOOPER_BEGIN(rect_float) { + rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) / float_divs[0]; + rect_float[3] = (a[i] + signed_offsets[1]) / float_divs[1]; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_float) { + rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) / float_divs[0]; + rect_float[3] = 1.0f; + } + PIXEL_LOOPER_END; + } + } + else { + r = image->comps[0].data; + g = image->comps[1].data; + b = image->comps[2].data; + + /* rgb or rgba 12bits+ */ + if (use_alpha) { + a = image->comps[3].data; + PIXEL_LOOPER_BEGIN(rect_float) { + rect_float[0] = (float)(r[i] + signed_offsets[0]) / float_divs[0]; + rect_float[1] = (float)(g[i] + signed_offsets[1]) / float_divs[1]; + rect_float[2] = (float)(b[i] + signed_offsets[2]) / float_divs[2]; + rect_float[3] = (float)(a[i] + signed_offsets[3]) / float_divs[3]; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_float) { + rect_float[0] = (float)(r[i] + signed_offsets[0]) / float_divs[0]; + rect_float[1] = (float)(g[i] + signed_offsets[1]) / float_divs[1]; + rect_float[2] = (float)(b[i] + signed_offsets[2]) / float_divs[2]; + rect_float[3] = 1.0f; + } + PIXEL_LOOPER_END; + } + } + + } + else { + unsigned char *rect_uchar = (unsigned char *)ibuf->rect; + + if (image->numcomps < 3) { + r = image->comps[0].data; + a = (use_alpha) ? image->comps[1].data : NULL; + + /* grayscale */ + if (use_alpha) { + a = image->comps[3].data; + PIXEL_LOOPER_BEGIN(rect_uchar) { + rect_uchar[0] = rect_uchar[1] = rect_uchar[2] = (r[i] + signed_offsets[0]); + rect_uchar[3] = a[i] + signed_offsets[1]; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_uchar) { + rect_uchar[0] = rect_uchar[1] = rect_uchar[2] = (r[i] + signed_offsets[0]); + rect_uchar[3] = 255; + } + PIXEL_LOOPER_END; + } + } + else { + r = image->comps[0].data; + g = image->comps[1].data; + b = image->comps[2].data; + + /* 8bit rgb or rgba */ + if (use_alpha) { + a = image->comps[3].data; + PIXEL_LOOPER_BEGIN(rect_uchar) { + rect_uchar[0] = r[i] + signed_offsets[0]; + rect_uchar[1] = g[i] + signed_offsets[1]; + rect_uchar[2] = b[i] + signed_offsets[2]; + rect_uchar[3] = a[i] + signed_offsets[3]; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_uchar) { + rect_uchar[0] = r[i] + signed_offsets[0]; + rect_uchar[1] = g[i] + signed_offsets[1]; + rect_uchar[2] = b[i] + signed_offsets[2]; + rect_uchar[3] = 255; + } + PIXEL_LOOPER_END; + } + } + } + + if (flags & IB_rect) { + IMB_rect_from_float(ibuf); + } + +finally: + + /* free remaining structures */ + if (codec) { + opj_destroy_codec(codec); + } + + if (image) { + opj_image_destroy(image); + } + + return ibuf; +} + +//static opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) +/* prec can be 8, 12, 16 */ + +/* use inline because the float passed can be a function call that would end up being called many times */ +#if 0 +#define UPSAMPLE_8_TO_12(_val) ((_val << 4) | (_val & ((1 << 4) - 1))) +#define UPSAMPLE_8_TO_16(_val) ((_val << 8) + _val) + +#define DOWNSAMPLE_FLOAT_TO_8BIT(_val) (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 255 : (int)(255.0f * (_val))) +#define DOWNSAMPLE_FLOAT_TO_12BIT(_val) (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 4095 : (int)(4095.0f * (_val))) +#define DOWNSAMPLE_FLOAT_TO_16BIT(_val) (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 65535 : (int)(65535.0f * (_val))) +#else + +BLI_INLINE int UPSAMPLE_8_TO_12(const unsigned char _val) +{ + return (_val << 4) | (_val & ((1 << 4) - 1)); +} +BLI_INLINE int UPSAMPLE_8_TO_16(const unsigned char _val) +{ + return (_val << 8) + _val; +} + +BLI_INLINE int DOWNSAMPLE_FLOAT_TO_8BIT(const float _val) +{ + return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 255 : (int)(255.0f * (_val))); +} +BLI_INLINE int DOWNSAMPLE_FLOAT_TO_12BIT(const float _val) +{ + return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 4095 : (int)(4095.0f * (_val))); +} +BLI_INLINE int DOWNSAMPLE_FLOAT_TO_16BIT(const float _val) +{ + return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 65535 : (int)(65535.0f * (_val))); +} +#endif + +/* + * 2048x1080 (2K) at 24 fps or 48 fps, or 4096x2160 (4K) at 24 fps; 3x12 bits per pixel, XYZ color space + * + * - In 2K, for Scope (2.39:1) presentation 2048x858 pixels of the image is used + * - In 2K, for Flat (1.85:1) presentation 1998x1080 pixels of the image is used + */ + +/* ****************************** COPIED FROM image_to_j2k.c */ + +/* ----------------------------------------------------------------------- */ +#define CINEMA_24_CS 1302083 /*Codestream length for 24fps*/ +#define CINEMA_48_CS 651041 /*Codestream length for 48fps*/ +#define COMP_24_CS 1041666 /*Maximum size per color component for 2K & 4K @ 24fps*/ +#define COMP_48_CS 520833 /*Maximum size per color component for 2K @ 48fps*/ + + +static int initialise_4K_poc(opj_poc_t *POC, int numres) +{ + POC[0].tile = 1; + POC[0].resno0 = 0; + POC[0].compno0 = 0; + POC[0].layno1 = 1; + POC[0].resno1 = numres - 1; + POC[0].compno1 = 3; + POC[0].prg1 = OPJ_CPRL; + POC[1].tile = 1; + POC[1].resno0 = numres - 1; + POC[1].compno0 = 0; + POC[1].layno1 = 1; + POC[1].resno1 = numres; + POC[1].compno1 = 3; + POC[1].prg1 = OPJ_CPRL; + return 2; +} + +static void cinema_parameters(opj_cparameters_t *parameters) +{ + parameters->tile_size_on = 0; /* false */ + parameters->cp_tdx = 1; + parameters->cp_tdy = 1; + + /*Tile part*/ + parameters->tp_flag = 'C'; + parameters->tp_on = 1; + + /*Tile and Image shall be at (0, 0)*/ + parameters->cp_tx0 = 0; + parameters->cp_ty0 = 0; + parameters->image_offset_x0 = 0; + parameters->image_offset_y0 = 0; + + /*Codeblock size = 32 * 32*/ + parameters->cblockw_init = 32; + parameters->cblockh_init = 32; + parameters->csty |= 0x01; + + /*The progression order shall be CPRL*/ + parameters->prog_order = OPJ_CPRL; + + /* No ROI */ + parameters->roi_compno = -1; + + parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; + + /* 9-7 transform */ + parameters->irreversible = 1; +} + +static void cinema_setup_encoder(opj_cparameters_t *parameters, opj_image_t *image, img_fol_t *img_fol) +{ + int i; + float temp_rate; + + switch (parameters->cp_cinema) { + case OPJ_CINEMA2K_24: + case OPJ_CINEMA2K_48: + if (parameters->numresolution > 6) { + parameters->numresolution = 6; + } + if (!((image->comps[0].w == 2048) || (image->comps[0].h == 1080))) { + fprintf(stdout, "Image coordinates %u x %u is not 2K compliant.\nJPEG Digital Cinema Profile-3 " + "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n", + image->comps[0].w, image->comps[0].h); + parameters->cp_rsiz = OPJ_STD_RSIZ; + } + else { + parameters->cp_rsiz = DCP_CINEMA2K; + } + break; + + case OPJ_CINEMA4K_24: + if (parameters->numresolution < 1) { + parameters->numresolution = 1; + } + else if (parameters->numresolution > 7) { + parameters->numresolution = 7; + } + if (!((image->comps[0].w == 4096) || (image->comps[0].h == 2160))) { + fprintf(stdout, "Image coordinates %u x %u is not 4K compliant.\nJPEG Digital Cinema Profile-4" + "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n", + image->comps[0].w, image->comps[0].h); + parameters->cp_rsiz = OPJ_STD_RSIZ; + } + else { + parameters->cp_rsiz = DCP_CINEMA2K; + } + parameters->numpocs = initialise_4K_poc(parameters->POC, parameters->numresolution); + break; + case OPJ_OFF: + /* do nothing */ + break; + } + + switch (parameters->cp_cinema) { + case OPJ_CINEMA2K_24: + case OPJ_CINEMA4K_24: + for (i = 0; i < parameters->tcp_numlayers; i++) { + temp_rate = 0; + if (img_fol->rates[i] == 0) { + parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy); + } + else { + temp_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy); + if (temp_rate > CINEMA_24_CS) { + parameters->tcp_rates[i] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy); + } + else { + parameters->tcp_rates[i] = img_fol->rates[i]; + } + } + } + parameters->max_comp_size = COMP_24_CS; + break; + + case OPJ_CINEMA2K_48: + for (i = 0; i < parameters->tcp_numlayers; i++) { + temp_rate = 0; + if (img_fol->rates[i] == 0) { + parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy); + } + else { + temp_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy); + if (temp_rate > CINEMA_48_CS) { + parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) / + (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy); + } + else { + parameters->tcp_rates[i] = img_fol->rates[i]; + } + } + } + parameters->max_comp_size = COMP_48_CS; + break; + case OPJ_OFF: + /* do nothing */ + break; + } + parameters->cp_disto_alloc = 1; +} + +static float channel_colormanage_noop(float value) +{ + return value; +} + +static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) +{ + unsigned char *rect_uchar; + float *rect_float, from_straight[4]; + + unsigned int subsampling_dx = parameters->subsampling_dx; + unsigned int subsampling_dy = parameters->subsampling_dy; + + unsigned int i, i_next, numcomps, w, h, prec; + unsigned int y; + int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */ + OPJ_COLOR_SPACE color_space; + opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ + opj_image_t *image = NULL; + + float (*chanel_colormanage_cb)(float); + + img_fol_t img_fol; /* only needed for cinema presets */ + memset(&img_fol, 0, sizeof(img_fol_t)); + + if (ibuf->float_colorspace || (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA)) { + /* float buffer was managed already, no need in color space conversion */ + chanel_colormanage_cb = channel_colormanage_noop; + } + else { + /* standard linear-to-srgb conversion if float buffer wasn't managed */ + chanel_colormanage_cb = linearrgb_to_srgb; + } + + if (ibuf->foptions.flag & JP2_CINE) { + + if (ibuf->x == 4096 || ibuf->y == 2160) + parameters->cp_cinema = OPJ_CINEMA4K_24; + else { + if (ibuf->foptions.flag & JP2_CINE_48FPS) { + parameters->cp_cinema = OPJ_CINEMA2K_48; + } + else { + parameters->cp_cinema = OPJ_CINEMA2K_24; + } + } + if (parameters->cp_cinema) { + img_fol.rates = (float *)MEM_mallocN(parameters->tcp_numlayers * sizeof(float), "jp2_rates"); + for (i = 0; i < parameters->tcp_numlayers; i++) { + img_fol.rates[i] = parameters->tcp_rates[i]; + } + cinema_parameters(parameters); + } + + color_space = (ibuf->foptions.flag & JP2_YCC) ? OPJ_CLRSPC_SYCC : OPJ_CLRSPC_SRGB; + prec = 12; + numcomps = 3; + } + else { + /* Get settings from the imbuf */ + color_space = (ibuf->foptions.flag & JP2_YCC) ? OPJ_CLRSPC_SYCC : OPJ_CLRSPC_SRGB; + + if (ibuf->foptions.flag & JP2_16BIT) prec = 16; + else if (ibuf->foptions.flag & JP2_12BIT) prec = 12; + else prec = 8; + + /* 32bit images == alpha channel */ + /* grayscale not supported yet */ + numcomps = (ibuf->planes == 32) ? 4 : 3; + } + + w = ibuf->x; + h = ibuf->y; + + + /* initialize image components */ + memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t)); + for (i = 0; i < numcomps; i++) { + cmptparm[i].prec = prec; + cmptparm[i].bpp = prec; + cmptparm[i].sgnd = 0; + cmptparm[i].dx = subsampling_dx; + cmptparm[i].dy = subsampling_dy; + cmptparm[i].w = w; + cmptparm[i].h = h; + } + /* create the image */ + image = opj_image_create(numcomps, &cmptparm[0], color_space); + if (!image) { + printf("Error: opj_image_create() failed\n"); + return NULL; + } + + /* set image offset and reference grid */ + image->x0 = parameters->image_offset_x0; + image->y0 = parameters->image_offset_y0; + image->x1 = image->x0 + (w - 1) * subsampling_dx + 1 + image->x0; + image->y1 = image->y0 + (h - 1) * subsampling_dy + 1 + image->y0; + + /* set image data */ + rect_uchar = (unsigned char *) ibuf->rect; + rect_float = ibuf->rect_float; + + /* set the destination channels */ + r = image->comps[0].data; + g = image->comps[1].data; + b = image->comps[2].data; + a = (numcomps == 4) ? image->comps[3].data : NULL; + + if (rect_float && rect_uchar && prec == 8) { + /* No need to use the floating point buffer, just write the 8 bits from the char buffer */ + rect_float = NULL; + } + + if (rect_float) { + int channels_in_float = ibuf->channels ? ibuf->channels : 4; + + switch (prec) { + case 8: /* Convert blenders float color channels to 8, 12 or 16bit ints */ + if (numcomps == 4) { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[2])); + a[i] = DOWNSAMPLE_FLOAT_TO_8BIT(from_straight[3]); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[2])); + a[i] = 255; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + a[i] = 255; + } + PIXEL_LOOPER_END; + } + } + else { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(from_straight[2])); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[2])); + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + } + PIXEL_LOOPER_END; + } + } + break; + + case 12: + if (numcomps == 4) { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[2])); + a[i] = DOWNSAMPLE_FLOAT_TO_12BIT(from_straight[3]); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[2])); + a[i] = 4095; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + a[i] = 4095; + } + PIXEL_LOOPER_END; + } + } + else { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(from_straight[2])); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[2])); + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + } + PIXEL_LOOPER_END; + } + } + break; + + case 16: + if (numcomps == 4) { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[2])); + a[i] = DOWNSAMPLE_FLOAT_TO_16BIT(from_straight[3]); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[2])); + a[i] = 65535; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + a[i] = 65535; + } + PIXEL_LOOPER_END; + } + } + else { + if (channels_in_float == 4) { + PIXEL_LOOPER_BEGIN(rect_float) + { + premul_to_straight_v4_v4(from_straight, rect_float); + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(from_straight[2])); + } + PIXEL_LOOPER_END; + } + else if (channels_in_float == 3) { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 3) + { + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[1])); + b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[2])); + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN_CHANNELS(rect_float, 1) + { + r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(chanel_colormanage_cb(rect_float[0])); + g[i] = b[i] = r[i]; + } + PIXEL_LOOPER_END; + } + } + break; + } + } + else { + /* just use rect*/ + switch (prec) { + case 8: + if (numcomps == 4) { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = rect_uchar[0]; + g[i] = rect_uchar[1]; + b[i] = rect_uchar[2]; + a[i] = rect_uchar[3]; + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = rect_uchar[0]; + g[i] = rect_uchar[1]; + b[i] = rect_uchar[2]; + } + PIXEL_LOOPER_END; + } + break; + + case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */ + if (numcomps == 4) { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]); + g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]); + b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]); + a[i] = UPSAMPLE_8_TO_12(rect_uchar[3]); + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]); + g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]); + b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]); + } + PIXEL_LOOPER_END; + } + break; + + case 16: + if (numcomps == 4) { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]); + g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]); + b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]); + a[i] = UPSAMPLE_8_TO_16(rect_uchar[3]); + } + PIXEL_LOOPER_END; + } + else { + PIXEL_LOOPER_BEGIN(rect_uchar) + { + r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]); + g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]); + b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]); + } + PIXEL_LOOPER_END; + } + break; + } + } + + /* Decide if MCT should be used */ + parameters->tcp_mct = image->numcomps == 3 ? 1 : 0; + + if (parameters->cp_cinema) { + cinema_setup_encoder(parameters, image, &img_fol); + } + + if (img_fol.rates) + MEM_freeN(img_fol.rates); + + return image; +} + +int imb_save_jp2_stream(struct ImBuf *ibuf, opj_stream_t *stream, int flags); + +int imb_save_jp2(struct ImBuf *ibuf, const char *filepath, int flags) +{ + opj_stream_t *stream = opj_stream_create_from_file(filepath, OPJ_J2K_STREAM_CHUNK_SIZE, false, NULL); + if (stream == NULL) { + return 0; + } + int ret = imb_save_jp2_stream(ibuf, stream, flags); + opj_stream_destroy(stream); + return ret; +} + +/* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */ +int imb_save_jp2_stream(struct ImBuf *ibuf, opj_stream_t *stream, int UNUSED(flags)) +{ + int quality = ibuf->foptions.quality; + + opj_cparameters_t parameters; /* compression parameters */ + opj_image_t *image = NULL; + + /* set encoding parameters to default values */ + opj_set_default_encoder_parameters(¶meters); + + /* compression ratio */ + /* invert range, from 10-100, 100-1 + * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/ + parameters.tcp_rates[0] = ((100 - quality) / 90.0f * 99.0f) + 1; + + + parameters.tcp_numlayers = 1; /* only one resolution */ + parameters.cp_disto_alloc = 1; + + image = ibuftoimage(ibuf, ¶meters); + + opj_codec_t *codec = NULL; + int ok = false; + /* JP2 format output */ + { + /* get a JP2 compressor handle */ + OPJ_CODEC_FORMAT format = OPJ_CODEC_JP2; + if (ibuf->foptions.flag & JP2_J2K) { + format = OPJ_CODEC_J2K; + } + else if (ibuf->foptions.flag & JP2_JP2) { + format = OPJ_CODEC_JP2; + } + + codec = opj_create_compress(format); + + /* configure the event callbacks (not required) */ + opj_set_error_handler(codec, error_callback, stderr); + opj_set_warning_handler(codec, warning_callback, stderr); +#ifdef DEBUG /* too noisy */ + opj_set_info_handler(codec, info_callback, stderr); +#endif + + /* setup the encoder parameters using the current image and using user parameters */ + if (opj_setup_encoder(codec, ¶meters, image) == false) { + goto finally; + } + + if (opj_start_compress(codec, image, stream) == false) { + goto finally; + } + if (opj_encode(codec, stream) == false) { + goto finally; + } + if (opj_end_compress(codec, stream) == false) { + goto finally; + } + } + + ok = true; + +finally: + /* free remaining compression structures */ + if (codec) { + opj_destroy_codec(codec); + } + + /* free image data */ + if (image) { + opj_image_destroy(image); + } + + if (ok == false) { + fprintf(stderr, "failed to encode image\n"); + } + + return ok; +} + +#else /* defined(OPJ_VERSION_MAJOR) && OPJ_VERSION_MAJOR >= 2 */ static const char JP2_HEAD[] = {0x0, 0x0, 0x0, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A}; static const char J2K_HEAD[] = {0xFF, 0x4F, 0xFF, 0x51, 0x00}; @@ -94,6 +1338,7 @@ static void warning_callback(const char *msg, void *client_data) FILE *stream = (FILE *)client_data; fprintf(stream, "[WARNING] %s", msg); } + /** * sample debug callback expecting no client object */ @@ -121,12 +1366,12 @@ static void info_callback(const char *msg, void *client_data) } \ } (void)0 \ -struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]) +struct ImBuf *imb_load_jp2(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE]) { struct ImBuf *ibuf = NULL; bool use_float = false; /* for precision higher then 8 use float */ bool use_alpha = false; - + long signed_offsets[4] = {0, 0, 0, 0}; int float_divs[4] = {1, 1, 1, 1}; @@ -134,9 +1379,9 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c unsigned int y; int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */ bool is_jp2, is_j2k; - + opj_dparameters_t parameters; /* decompression parameters */ - + opj_event_mgr_t event_mgr; /* event manager */ opj_image_t *image = NULL; @@ -180,7 +1425,7 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c /* decode the stream and fill the image structure */ image = opj_decode(dinfo, cio); - + if (!image) { fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n"); opj_destroy_decompress(dinfo); @@ -196,10 +1441,10 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c fprintf(stderr, "\nError: invalid raw image parameters\n"); return NULL; } - + w = image->comps[0].w; h = image->comps[0].h; - + switch (image->numcomps) { case 1: /* Grayscale */ case 3: /* Color */ @@ -211,38 +1456,38 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c use_alpha = true; break; } - - + + i = image->numcomps; if (i > 4) i = 4; - + while (i) { i--; - + if (image->comps[i].prec > 8) use_float = true; - + if (image->comps[i].sgnd) signed_offsets[i] = 1 << (image->comps[i].prec - 1); - + /* only needed for float images but dosnt hurt to calc this */ float_divs[i] = (1 << image->comps[i].prec) - 1; } - + ibuf = IMB_allocImBuf(w, h, planes, use_float ? IB_rectfloat : IB_rect); - + if (ibuf == NULL) { if (dinfo) opj_destroy_decompress(dinfo); return NULL; } - + ibuf->ftype = IMB_FTYPE_JP2; if (is_jp2) ibuf->foptions.flag |= JP2_JP2; else ibuf->foptions.flag |= JP2_J2K; - + if (use_float) { float *rect_float = ibuf->rect_float; @@ -293,7 +1538,7 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c PIXEL_LOOPER_END; } } - + } else { unsigned char *rect_uchar = (unsigned char *)ibuf->rect; @@ -346,19 +1591,19 @@ struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, c } } } - + /* free remaining structures */ if (dinfo) { opj_destroy_decompress(dinfo); } - + /* free image data structure */ opj_image_destroy(image); - + if (flags & IB_rect) { IMB_rect_from_float(ibuf); } - + return(ibuf); } @@ -416,8 +1661,8 @@ BLI_INLINE int DOWNSAMPLE_FLOAT_TO_16BIT(const float _val) static int initialise_4K_poc(opj_poc_t *POC, int numres) { - POC[0].tile = 1; - POC[0].resno0 = 0; + POC[0].tile = 1; + POC[0].resno0 = 0; POC[0].compno0 = 0; POC[0].layno1 = 1; POC[0].resno1 = numres - 1; @@ -438,7 +1683,7 @@ static void cinema_parameters(opj_cparameters_t *parameters) parameters->tile_size_on = 0; /* false */ parameters->cp_tdx = 1; parameters->cp_tdy = 1; - + /*Tile part*/ parameters->tp_flag = 'C'; parameters->tp_on = 1; @@ -487,7 +1732,7 @@ static void cinema_setup_encoder(opj_cparameters_t *parameters, opj_image_t *ima parameters->cp_rsiz = DCP_CINEMA2K; } break; - + case CINEMA4K_24: if (parameters->numresolution < 1) { parameters->numresolution = 1; @@ -534,7 +1779,7 @@ static void cinema_setup_encoder(opj_cparameters_t *parameters, opj_image_t *ima } parameters->max_comp_size = COMP_24_CS; break; - + case CINEMA2K_48: for (i = 0; i < parameters->tcp_numlayers; i++) { temp_rate = 0; @@ -572,22 +1817,22 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) { unsigned char *rect_uchar; float *rect_float, from_straight[4]; - + unsigned int subsampling_dx = parameters->subsampling_dx; unsigned int subsampling_dy = parameters->subsampling_dy; - + unsigned int i, i_next, numcomps, w, h, prec; unsigned int y; int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */ OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ opj_image_t *image = NULL; - + float (*chanel_colormanage_cb)(float); - + img_fol_t img_fol; /* only needed for cinema presets */ memset(&img_fol, 0, sizeof(img_fol_t)); - + if (ibuf->float_colorspace || (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA)) { /* float buffer was managed already, no need in color space conversion */ chanel_colormanage_cb = channel_colormanage_noop; @@ -596,9 +1841,9 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) /* standard linear-to-srgb conversion if float buffer wasn't managed */ chanel_colormanage_cb = linearrgb_to_srgb; } - + if (ibuf->foptions.flag & JP2_CINE) { - + if (ibuf->x == 4096 || ibuf->y == 2160) parameters->cp_cinema = CINEMA4K_24; else { @@ -616,7 +1861,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) } cinema_parameters(parameters); } - + color_space = (ibuf->foptions.flag & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB; prec = 12; numcomps = 3; @@ -624,20 +1869,20 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) else { /* Get settings from the imbuf */ color_space = (ibuf->foptions.flag & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB; - + if (ibuf->foptions.flag & JP2_16BIT) prec = 16; else if (ibuf->foptions.flag & JP2_12BIT) prec = 12; else prec = 8; - + /* 32bit images == alpha channel */ /* grayscale not supported yet */ numcomps = (ibuf->planes == 32) ? 4 : 3; } - + w = ibuf->x; h = ibuf->y; - - + + /* initialize image components */ memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t)); for (i = 0; i < numcomps; i++) { @@ -665,7 +1910,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) /* set image data */ rect_uchar = (unsigned char *) ibuf->rect; rect_float = ibuf->rect_float; - + /* set the destination channels */ r = image->comps[0].data; g = image->comps[1].data; @@ -676,7 +1921,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) /* No need to use the floating point buffer, just write the 8 bits from the char buffer */ rect_float = NULL; } - + if (rect_float) { int channels_in_float = ibuf->channels ? ibuf->channels : 4; @@ -744,7 +1989,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) } } break; - + case 12: if (numcomps == 4) { if (channels_in_float == 4) { @@ -898,7 +2143,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) PIXEL_LOOPER_END; } break; - + case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */ if (numcomps == 4) { PIXEL_LOOPER_BEGIN(rect_uchar) @@ -944,33 +2189,33 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters) break; } } - + /* Decide if MCT should be used */ parameters->tcp_mct = image->numcomps == 3 ? 1 : 0; - + if (parameters->cp_cinema) { cinema_setup_encoder(parameters, image, &img_fol); } - + if (img_fol.rates) MEM_freeN(img_fol.rates); - + return image; } /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */ -int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) +int imb_save_jp2(struct ImBuf *ibuf, const char *name, int flags) { int quality = ibuf->foptions.quality; - + int bSuccess; opj_cparameters_t parameters; /* compression parameters */ opj_event_mgr_t event_mgr; /* event manager */ opj_image_t *image = NULL; - + (void)flags; /* unused */ - + /* * configure the event callbacks (not required) * setting of each callback is optional @@ -979,22 +2224,22 @@ int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) event_mgr.error_handler = error_callback; event_mgr.warning_handler = warning_callback; event_mgr.info_handler = info_callback; - + /* set encoding parameters to default values */ opj_set_default_encoder_parameters(¶meters); - + /* compression ratio */ /* invert range, from 10-100, 100-1 * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/ parameters.tcp_rates[0] = ((100 - quality) / 90.0f * 99.0f) + 1; - + parameters.tcp_numlayers = 1; /* only one resolution */ parameters.cp_disto_alloc = 1; image = ibuftoimage(ibuf, ¶meters); - - + + { /* JP2 format output */ int codestream_length; opj_cio_t *cio = NULL; @@ -1021,7 +2266,7 @@ int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) /* encode the image */ bSuccess = opj_encode(cinfo, cio, image, NULL); /* last arg used to be parameters.index but this deprecated */ - + if (!bSuccess) { opj_cio_close(cio); fprintf(stderr, "failed to encode image\n"); @@ -1031,7 +2276,7 @@ int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) /* write the buffer to disk */ f = BLI_fopen(name, "wb"); - + if (!f) { fprintf(stderr, "failed to open %s for writing\n", name); return 1; @@ -1041,13 +2286,15 @@ int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) fprintf(stderr, "Generated outfile %s\n", name); /* close and free the byte stream */ opj_cio_close(cio); - + /* free remaining compression structures */ opj_destroy_compress(cinfo); } /* free image data */ opj_image_destroy(image); - + return 1; } + +#endif /* defined(OPJ_VERSION_MAJOR) && OPJ_VERSION_MAJOR >= 2 */ diff --git a/source/blender/imbuf/intern/jpeg.c b/source/blender/imbuf/intern/jpeg.c index ef9217fbc8ca..2febbb1f8610 100644 --- a/source/blender/imbuf/intern/jpeg.c +++ b/source/blender/imbuf/intern/jpeg.c @@ -48,7 +48,7 @@ #include "IMB_imbuf.h" #include "IMB_metadata.h" #include "IMB_filetype.h" -#include "jpeglib.h" +#include "jpeglib.h" #include "jerror.h" #include "IMB_colormanagement.h" @@ -247,12 +247,12 @@ static boolean handle_app1(j_decompress_ptr cinfo) INT32 length; /* initialized by the macro */ INT32 i; char neogeo[128]; - + INPUT_VARS(cinfo); INPUT_2BYTES(cinfo, length, return false); length -= 2; - + if (length < 16) { for (i = 0; i < length; i++) { INPUT_BYTE(cinfo, neogeo[i], return false); @@ -308,12 +308,12 @@ static ImBuf *ibJpegImageFromCinfo(struct jpeg_decompress_struct *cinfo, int fla row_stride = cinfo->output_width * depth; row_pointer = (*cinfo->mem->alloc_sarray)((j_common_ptr) cinfo, JPOOL_IMAGE, row_stride, 1); - + for (y = ibuf->y - 1; y >= 0; y--) { jpeg_read_scanlines(cinfo, row_pointer, 1); rect = (uchar *) (ibuf->rect + y * ibuf->x); buffer = row_pointer[0]; - + switch (depth) { case 1: for (x = ibuf->x; x > 0; x--) { @@ -419,7 +419,7 @@ static ImBuf *ibJpegImageFromCinfo(struct jpeg_decompress_struct *cinfo, int fla jpeg_finish_decompress(cinfo); } - + jpeg_destroy((j_common_ptr) cinfo); if (ibuf) { ibuf->ftype = IMB_FTYPE_JPG; @@ -456,7 +456,7 @@ ImBuf *imb_load_jpeg(const unsigned char *buffer, size_t size, int flags, char c memory_source(cinfo, buffer, size); ibuf = ibJpegImageFromCinfo(cinfo, flags); - + return(ibuf); } @@ -584,7 +584,7 @@ static int init_jpeg(FILE *outfile, struct jpeg_compress_struct *cinfo, struct I break; } jpeg_set_defaults(cinfo); - + /* own settings */ cinfo->dct_method = JDCT_FLOAT; @@ -629,7 +629,7 @@ static int save_stdjpeg(const char *name, struct ImBuf *ibuf) int imb_savejpeg(struct ImBuf *ibuf, const char *name, int flags) { - + ibuf->flags = flags; return save_stdjpeg(name, ibuf); } diff --git a/source/blender/imbuf/intern/module.c b/source/blender/imbuf/intern/module.c index 777fe77f032a..3f2e9e042120 100644 --- a/source/blender/imbuf/intern/module.c +++ b/source/blender/imbuf/intern/module.c @@ -51,4 +51,3 @@ void IMB_exit(void) imb_mmap_lock_exit(); imb_refcounter_lock_exit(); } - diff --git a/source/blender/imbuf/intern/oiio/openimageio_api.cpp b/source/blender/imbuf/intern/oiio/openimageio_api.cpp index b123d508f99f..f018bfc09d7d 100644 --- a/source/blender/imbuf/intern/oiio/openimageio_api.cpp +++ b/source/blender/imbuf/intern/oiio/openimageio_api.cpp @@ -179,7 +179,7 @@ int imb_is_a_photoshop(const char *filename) NULL }; - return BLI_testextensie_array(filename, photoshop_extension); + return BLI_path_extension_check_array(filename, photoshop_extension); } int imb_save_photoshop(struct ImBuf *ibuf, const char * /*name*/, int flags) @@ -291,5 +291,3 @@ int OIIO_getVersionHex(void) } } // export "C" - - diff --git a/source/blender/imbuf/intern/openexr/CMakeLists.txt b/source/blender/imbuf/intern/openexr/CMakeLists.txt index d5cb8e8a3b6c..d4e6e9dc6701 100644 --- a/source/blender/imbuf/intern/openexr/CMakeLists.txt +++ b/source/blender/imbuf/intern/openexr/CMakeLists.txt @@ -23,7 +23,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . .. ../.. diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp index ad04f1fb78d6..a52ae75e87b4 100644 --- a/source/blender/imbuf/intern/openexr/openexr_api.cpp +++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp @@ -912,7 +912,7 @@ int IMB_exr_begin_read(void *handle, const char *filename, int *width, int *heig for (size_t i = 0; i < channels.size(); i++) { IMB_exr_add_channel(data, NULL, channels[i].name.c_str(), channels[i].view.c_str(), 0, 0, NULL, false); - + echan = (ExrChannel *)data->channels.last; echan->m->name = channels[i].name; echan->m->view = channels[i].view; @@ -1274,7 +1274,7 @@ static int imb_exr_split_channel_name(ExrChannel *echan, char *layname, char *pa const char *token; char tokenbuf[EXR_TOT_MAXNAME]; int len; - + /* some multilayers have the combined buffer with names A B G R saved */ if (name[1] == 0) { echan->chan_id = name[0]; diff --git a/source/blender/imbuf/intern/openexr/openexr_api.h b/source/blender/imbuf/intern/openexr/openexr_api.h index 165cc9687014..92bbeecfd5db 100644 --- a/source/blender/imbuf/intern/openexr/openexr_api.h +++ b/source/blender/imbuf/intern/openexr/openexr_api.h @@ -42,7 +42,7 @@ extern "C" { void imb_initopenexr (void); int imb_is_a_openexr (const unsigned char *mem); - + int imb_save_openexr (struct ImBuf *ibuf, const char *name, int flags); struct ImBuf *imb_load_openexr (const unsigned char *mem, size_t size, int flags, char *colorspace); diff --git a/source/blender/imbuf/intern/png.c b/source/blender/imbuf/intern/png.c index 8ac206a97ea4..47a2a8d40fbe 100644 --- a/source/blender/imbuf/intern/png.c +++ b/source/blender/imbuf/intern/png.c @@ -82,7 +82,7 @@ int imb_is_a_png(const unsigned char *mem) return(ret_val); } -static void Flush(png_structp png_ptr) +static void Flush(png_structp png_ptr) { (void)png_ptr; } @@ -415,7 +415,7 @@ int imb_savepng(struct ImBuf *ibuf, const char *name, int flags) num_text++; } } - + metadata = MEM_callocN(num_text * sizeof(png_text), "png_metadata"); num_text = 0; for (prop = ibuf->metadata->data.group.first; prop; prop = prop->next) { @@ -426,7 +426,7 @@ int imb_savepng(struct ImBuf *ibuf, const char *name, int flags) num_text++; } } - + png_set_text(png_ptr, info_ptr, metadata, num_text); MEM_freeN(metadata); @@ -544,7 +544,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { - png_destroy_read_struct(&png_ptr, (png_infopp)NULL, + png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); printf("Cannot png_create_info_struct\n"); return NULL; @@ -568,7 +568,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors // png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); - png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, + png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); channels = png_get_channels(png_ptr, info_ptr); @@ -601,7 +601,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors printf("PNG format not supported\n"); longjmp(png_jmpbuf(png_ptr), 1); } - + ibuf = IMB_allocImBuf(width, height, 8 * channels, 0); if (ibuf) { @@ -780,4 +780,3 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors return(ibuf); } - diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c index 8d822a314f54..be33c16c8ae7 100644 --- a/source/blender/imbuf/intern/radiance_hdr.c +++ b/source/blender/imbuf/intern/radiance_hdr.c @@ -256,7 +256,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char /* read in and decode the actual data */ sline = (RGBE *)MEM_mallocN(sizeof(*sline) * width, __func__); rect_float = ibuf->rect_float; - + for (size_t y = 0; y < height; y++) { ptr = freadcolrs(sline, ptr, width, mem_eof); if (ptr == NULL) { @@ -274,11 +274,11 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char } MEM_freeN(sline); if (oriY[0] == '-') IMB_flipy(ibuf); - + if (flags & IB_rect) { IMB_rect_from_float(ibuf); } - + return ibuf; } //else printf("Data not found!\n"); @@ -385,9 +385,9 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags) float *fp = NULL; size_t width = ibuf->x, height = ibuf->y; unsigned char *cp = NULL; - + (void)flags; /* unused */ - + if (file == NULL) { return 0; } @@ -398,7 +398,7 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags) cp = (unsigned char *)ibuf->rect + ibuf->channels * (height - 1) * width; if (ibuf->rect_float) fp = ibuf->rect_float + ibuf->channels * (height - 1) * width; - + for (size_t y = 0; y < height; y++) { if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) { fclose(file); diff --git a/source/blender/imbuf/intern/readimage.c b/source/blender/imbuf/intern/readimage.c index afa3ffb31f38..0b4490a3beb8 100644 --- a/source/blender/imbuf/intern/readimage.c +++ b/source/blender/imbuf/intern/readimage.c @@ -159,7 +159,7 @@ static ImBuf *IMB_ibImageFromFile(const char *filepath, int flags, char colorspa static bool imb_is_filepath_format(const char *filepath) { /* return true if this is one of the formats that can't be loaded from memory */ - return BLI_testextensie_array(filepath, imb_ext_image_filepath_only); + return BLI_path_extension_check_array(filepath, imb_ext_image_filepath_only); } ImBuf *IMB_loadifffile(int file, const char *filepath, int flags, char colorspace[IM_MAX_SPACE], const char *descr) @@ -199,7 +199,7 @@ static void imb_cache_filename(char *filename, const char *name, int flags) /* read .tx instead if it exists and is not older */ if (flags & IB_tilecache) { BLI_strncpy(filename, name, IMB_FILENAME_SIZE); - if (!BLI_replace_extension(filename, IMB_FILENAME_SIZE, ".tx")) + if (!BLI_path_extension_replace(filename, IMB_FILENAME_SIZE, ".tx")) return; if (BLI_file_older(name, filename)) diff --git a/source/blender/imbuf/intern/rectop.c b/source/blender/imbuf/intern/rectop.c index 2fe17ee56c61..a762e3780dc9 100644 --- a/source/blender/imbuf/intern/rectop.c +++ b/source/blender/imbuf/intern/rectop.c @@ -167,13 +167,13 @@ void IMB_blend_color_float(float dst[4], float src1[4], float src2[4], IMB_Blend /* clipping */ -void IMB_rectclip(ImBuf *dbuf, ImBuf *sbuf, int *destx, +void IMB_rectclip(ImBuf *dbuf, ImBuf *sbuf, int *destx, int *desty, int *srcx, int *srcy, int *width, int *height) { int tmp; if (dbuf == NULL) return; - + if (*destx < 0) { *srcx -= *destx; *width += *destx; @@ -213,14 +213,14 @@ void IMB_rectclip(ImBuf *dbuf, ImBuf *sbuf, int *destx, } } -static void imb_rectclip3(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, int *destx, +static void imb_rectclip3(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, int *destx, int *desty, int *origx, int *origy, int *srcx, int *srcy, int *width, int *height) { int tmp; if (dbuf == NULL) return; - + if (*destx < 0) { *srcx -= *destx; *origx -= *destx; @@ -286,7 +286,7 @@ static void imb_rectclip3(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, int *destx, /* copy and blend */ -void IMB_rectcpy(ImBuf *dbuf, ImBuf *sbuf, int destx, +void IMB_rectcpy(ImBuf *dbuf, ImBuf *sbuf, int destx, int desty, int srcx, int srcy, int width, int height) { IMB_rectblend(dbuf, dbuf, sbuf, NULL, NULL, NULL, 0, destx, desty, destx, desty, srcx, srcy, width, height, IMB_BLEND_COPY, false); @@ -786,20 +786,20 @@ void IMB_rectfill(ImBuf *drect, const float col[4]) if (drect->rect) { unsigned int *rrect = drect->rect; char ccol[4]; - + ccol[0] = (int)(col[0] * 255); ccol[1] = (int)(col[1] * 255); ccol[2] = (int)(col[2] * 255); ccol[3] = (int)(col[3] * 255); - + num = drect->x * drect->y; for (; num > 0; num--) *rrect++ = *((unsigned int *)ccol); } - + if (drect->rect_float) { float *rrectf = drect->rect_float; - + num = drect->x * drect->y; for (; num > 0; num--) { *rrectf++ = col[0]; @@ -821,7 +821,7 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, float aich; /* alpha, inverted, ai/255.0 - Convert char to float at the same time */ if ((!rect && !rectf) || (!col) || col[3] == 0.0f) return; - + /* sanity checks for coords */ CLAMP(x1, 0, width); CLAMP(x2, 0, width); @@ -831,18 +831,18 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, if (x1 > x2) SWAP(int, x1, x2); if (y1 > y2) SWAP(int, y1, y2); if (x1 == x2 || y1 == y2) return; - + a = col[3]; ai = 1 - a; aich = ai / 255.0f; if (rect) { - unsigned char *pixel; + unsigned char *pixel; unsigned char chr = 0, chg = 0, chb = 0; float fr = 0, fg = 0, fb = 0; const int alphaint = unit_float_to_uchar_clamp(a); - + if (a == 1.0f) { chr = unit_float_to_uchar_clamp(col[0]); chg = unit_float_to_uchar_clamp(col[1]); @@ -874,7 +874,7 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height, } } } - + if (rectf) { float col_conv[4]; float *pixel; diff --git a/source/blender/imbuf/intern/rotate.c b/source/blender/imbuf/intern/rotate.c index 886944f61901..f00745f0052a 100644 --- a/source/blender/imbuf/intern/rotate.c +++ b/source/blender/imbuf/intern/rotate.c @@ -54,7 +54,7 @@ void IMB_flipy(struct ImBuf *ibuf) top = ibuf->rect; bottom = top + ((y - 1) * x); line = MEM_mallocN(x * sizeof(int), "linebuf"); - + y >>= 1; for (; y > 0; y--) { @@ -96,7 +96,7 @@ void IMB_flipx(struct ImBuf *ibuf) { int x, y, xr, xl, yi; float px_f[4]; - + if (ibuf == NULL) return; x = ibuf->x; @@ -109,7 +109,7 @@ void IMB_flipx(struct ImBuf *ibuf) } } } - + if (ibuf->rect_float) { for (yi = y - 1; yi >= 0; yi--) { for (xr = x - 1, xl = 0; xr >= xl; xr--, xl++) { diff --git a/source/blender/imbuf/intern/scaling.c b/source/blender/imbuf/intern/scaling.c index 4b528160fb77..43c5a9d3597f 100644 --- a/source/blender/imbuf/intern/scaling.c +++ b/source/blender/imbuf/intern/scaling.c @@ -60,7 +60,7 @@ static void imb_half_x_no_alloc(struct ImBuf *ibuf2, struct ImBuf *ibuf1) do_rect = (ibuf1->rect != NULL); do_float = (ibuf1->rect_float != NULL && ibuf2->rect_float != NULL); - + _p1 = (uchar *) ibuf1->rect; dest = (uchar *) ibuf2->rect; @@ -113,12 +113,12 @@ struct ImBuf *IMB_half_x(struct ImBuf *ibuf1) if (ibuf1->rect == NULL && ibuf1->rect_float == NULL) return (NULL); if (ibuf1->x <= 1) return(IMB_dupImBuf(ibuf1)); - + ibuf2 = IMB_allocImBuf((ibuf1->x) / 2, ibuf1->y, ibuf1->planes, ibuf1->flags); if (ibuf2 == NULL) return (NULL); imb_half_x_no_alloc(ibuf2, ibuf1); - + return (ibuf2); } @@ -133,7 +133,7 @@ struct ImBuf *IMB_double_fast_x(struct ImBuf *ibuf1) do_rect = (ibuf1->rect != NULL); do_float = (ibuf1->rect_float != NULL); - + ibuf2 = IMB_allocImBuf(2 * ibuf1->x, ibuf1->y, ibuf1->planes, ibuf1->flags); if (ibuf2 == NULL) return (NULL); @@ -245,14 +245,14 @@ struct ImBuf *IMB_half_y(struct ImBuf *ibuf1) if (ibuf1 == NULL) return (NULL); if (ibuf1->rect == NULL && ibuf1->rect_float == NULL) return (NULL); - + if (ibuf1->y <= 1) return(IMB_dupImBuf(ibuf1)); ibuf2 = IMB_allocImBuf(ibuf1->x, (ibuf1->y) / 2, ibuf1->planes, ibuf1->flags); if (ibuf2 == NULL) return (NULL); imb_half_y_no_alloc(ibuf2, ibuf1); - + return (ibuf2); } @@ -303,7 +303,7 @@ struct ImBuf *IMB_double_y(struct ImBuf *ibuf1) if (ibuf1->rect == NULL) return (NULL); ibuf2 = IMB_double_fast_y(ibuf1); - + IMB_filtery(ibuf2); return (ibuf2); } @@ -358,30 +358,30 @@ void imb_onehalf_no_alloc(struct ImBuf *ibuf2, struct ImBuf *ibuf1) imb_half_x_no_alloc(ibuf2, ibuf1); return; } - + if (do_rect) { unsigned char *cp1, *cp2, *dest; - + cp1 = (unsigned char *) ibuf1->rect; dest = (unsigned char *) ibuf2->rect; - + for (y = ibuf2->y; y > 0; y--) { cp2 = cp1 + (ibuf1->x << 2); for (x = ibuf2->x; x > 0; x--) { unsigned short p1i[8], p2i[8], desti[4]; - + straight_uchar_to_premul_ushort(p1i, cp1); straight_uchar_to_premul_ushort(p2i, cp2); straight_uchar_to_premul_ushort(p1i + 4, cp1 + 4); straight_uchar_to_premul_ushort(p2i + 4, cp2 + 4); - + desti[0] = ((unsigned int) p1i[0] + p2i[0] + p1i[4] + p2i[4]) >> 2; desti[1] = ((unsigned int) p1i[1] + p2i[1] + p1i[5] + p2i[5]) >> 2; desti[2] = ((unsigned int) p1i[2] + p2i[2] + p1i[6] + p2i[6]) >> 2; desti[3] = ((unsigned int) p1i[3] + p2i[3] + p1i[7] + p2i[7]) >> 2; - + premul_ushort_to_straight_uchar(dest, desti); - + cp1 += 8; cp2 += 8; dest += 4; @@ -390,10 +390,10 @@ void imb_onehalf_no_alloc(struct ImBuf *ibuf2, struct ImBuf *ibuf1) if (ibuf1->x & 1) cp1 += 4; } } - + if (do_float) { float *p1f, *p2f, *destf; - + p1f = ibuf1->rect_float; destf = ibuf2->rect_float; for (y = ibuf2->y; y > 0; y--) { @@ -419,15 +419,15 @@ ImBuf *IMB_onehalf(struct ImBuf *ibuf1) if (ibuf1 == NULL) return (NULL); if (ibuf1->rect == NULL && ibuf1->rect_float == NULL) return (NULL); - + if (ibuf1->x <= 1) return(IMB_half_y(ibuf1)); if (ibuf1->y <= 1) return(IMB_half_x(ibuf1)); - + ibuf2 = IMB_allocImBuf((ibuf1->x) / 2, (ibuf1->y) / 2, ibuf1->planes, ibuf1->flags); if (ibuf2 == NULL) return (NULL); - + imb_onehalf_no_alloc(ibuf2, ibuf1); - + return (ibuf2); } @@ -582,7 +582,7 @@ static void shrink_picture_byte( struct scale_outpix_byte *temp; y_counter += 65536; - + for (x = 0; x < dst_width; x++) { uintptr_t f = 0x80000000UL / dst_line1[x].weight; *dst++ = (val = (dst_line1[x].r * f) >> 15) > 255 ? 255 : val; @@ -782,7 +782,7 @@ static void shrink_picture_float( struct scale_outpix_float *temp; y_counter += 1.0f; - + for (x = 0; x < dst_width; x++) { float f = 1.0f / dst_line1[x].weight; *dst++ = dst_line1[x].r * f; @@ -921,7 +921,7 @@ static ImBuf *scaledownx(struct ImBuf *ibuf, int newx) rectf = ibuf->rect_float; newrectf = _newrectf; } - + for (y = ibuf->y; y > 0; y--) { sample = 0.0f; val[0] = val[1] = val[2] = val[3] = 0.0f; @@ -940,12 +940,12 @@ static ImBuf *scaledownx(struct ImBuf *ibuf, int newx) nvalf[2] = -valf[2] * sample; nvalf[3] = -valf[3] * sample; } - + sample += add; while (sample >= 1.0f) { sample -= 1.0f; - + if (do_rect) { nval[0] += rect[0]; nval[1] += rect[1]; @@ -961,31 +961,31 @@ static ImBuf *scaledownx(struct ImBuf *ibuf, int newx) rectf += 4; } } - + if (do_rect) { val[0] = rect[0]; val[1] = rect[1]; val[2] = rect[2]; val[3] = rect[3]; rect += 4; - + newrect[0] = ((nval[0] + sample * val[0]) / add + 0.5f); newrect[1] = ((nval[1] + sample * val[1]) / add + 0.5f); newrect[2] = ((nval[2] + sample * val[2]) / add + 0.5f); newrect[3] = ((nval[3] + sample * val[3]) / add + 0.5f); - + newrect += 4; } if (do_float) { - + valf[0] = rectf[0]; valf[1] = rectf[1]; valf[2] = rectf[2]; valf[3] = rectf[3]; rectf += 4; - + newrectf[0] = ((nvalf[0] + sample * valf[0]) / add); newrectf[1] = ((nvalf[1] + sample * valf[1]) / add); newrectf[2] = ((nvalf[2] + sample * valf[2]) / add); newrectf[3] = ((nvalf[3] + sample * valf[3]) / add); - + newrectf += 4; } - + sample -= 1.0f; } } @@ -1005,7 +1005,7 @@ static ImBuf *scaledownx(struct ImBuf *ibuf, int newx) ibuf->rect_float = _newrectf; } (void)rect_size; /* UNUSED in release builds */ - + ibuf->x = newx; return(ibuf); } @@ -1053,7 +1053,7 @@ static ImBuf *scaledowny(struct ImBuf *ibuf, int newy) rectf = ibuf->rect_float + x; newrectf = _newrectf + x; } - + sample = 0.0f; val[0] = val[1] = val[2] = val[3] = 0.0f; valf[0] = valf[1] = valf[2] = valf[3] = 0.0f; @@ -1071,12 +1071,12 @@ static ImBuf *scaledowny(struct ImBuf *ibuf, int newy) nvalf[2] = -valf[2] * sample; nvalf[3] = -valf[3] * sample; } - + sample += add; while (sample >= 1.0f) { sample -= 1.0f; - + if (do_rect) { nval[0] += rect[0]; nval[1] += rect[1]; @@ -1096,27 +1096,27 @@ static ImBuf *scaledowny(struct ImBuf *ibuf, int newy) if (do_rect) { val[0] = rect[0]; val[1] = rect[1]; val[2] = rect[2]; val[3] = rect[3]; rect += skipx; - + newrect[0] = ((nval[0] + sample * val[0]) / add + 0.5f); newrect[1] = ((nval[1] + sample * val[1]) / add + 0.5f); newrect[2] = ((nval[2] + sample * val[2]) / add + 0.5f); newrect[3] = ((nval[3] + sample * val[3]) / add + 0.5f); - + newrect += skipx; } if (do_float) { - + valf[0] = rectf[0]; valf[1] = rectf[1]; valf[2] = rectf[2]; valf[3] = rectf[3]; rectf += skipx; - + newrectf[0] = ((nvalf[0] + sample * valf[0]) / add); newrectf[1] = ((nvalf[1] + sample * valf[1]) / add); newrectf[2] = ((nvalf[2] + sample * valf[2]) / add); newrectf[3] = ((nvalf[3] + sample * valf[3]) / add); - + newrectf += skipx; } - + sample -= 1.0f; } } @@ -1136,7 +1136,7 @@ static ImBuf *scaledowny(struct ImBuf *ibuf, int newy) ibuf->rect_float = (float *) _newrectf; } (void)rect_size; /* UNUSED in release builds */ - + ibuf->y = newy; return(ibuf); } @@ -1189,7 +1189,7 @@ static ImBuf *scaleupx(struct ImBuf *ibuf, int newx) for (y = ibuf->y; y > 0; y--) { sample = 0; - + if (do_rect) { val_a = rect[0]; nval_a = rect[4]; @@ -1217,7 +1217,7 @@ static ImBuf *scaleupx(struct ImBuf *ibuf, int newx) val_af = rectf[0]; nval_af = rectf[4]; diff_af = nval_af - val_af; - + val_bf = rectf[1]; nval_bf = rectf[5]; diff_bf = nval_bf - val_bf; @@ -1262,7 +1262,7 @@ static ImBuf *scaleupx(struct ImBuf *ibuf, int newx) val_af = nval_af; nval_af = rectf[0]; diff_af = nval_af - val_af; - + val_bf = nval_bf; nval_bf = rectf[1]; diff_bf = nval_bf - val_bf; @@ -1305,7 +1305,7 @@ static ImBuf *scaleupx(struct ImBuf *ibuf, int newx) ibuf->mall |= IB_rectfloat; ibuf->rect_float = (float *) _newrectf; } - + ibuf->x = newx; return(ibuf); } @@ -1391,7 +1391,7 @@ static ImBuf *scaleupy(struct ImBuf *ibuf, int newy) val_af = rectf[0]; nval_af = rectf[skipx]; diff_af = nval_af - val_af; - + val_bf = rectf[1]; nval_bf = rectf[skipx + 1]; diff_bf = nval_bf - val_bf; @@ -1406,7 +1406,7 @@ static ImBuf *scaleupy(struct ImBuf *ibuf, int newy) rectf += 2 * skipx; } - + for (y = newy; y > 0; y--) { if (sample >= 1.0f) { sample -= 1.0f; @@ -1437,7 +1437,7 @@ static ImBuf *scaleupy(struct ImBuf *ibuf, int newy) val_af = nval_af; nval_af = rectf[0]; diff_af = nval_af - val_af; - + val_bf = nval_bf; nval_bf = rectf[1]; diff_bf = nval_bf - val_bf; @@ -1480,7 +1480,7 @@ static ImBuf *scaleupy(struct ImBuf *ibuf, int newy) ibuf->mall |= IB_rectfloat; ibuf->rect_float = (float *) _newrectf; } - + ibuf->y = newy; return(ibuf); } @@ -1557,7 +1557,7 @@ bool IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy) { if (ibuf == NULL) return false; if (ibuf->rect == NULL && ibuf->rect_float == NULL) return false; - + if (newx == ibuf->x && newy == ibuf->y) { return false; } @@ -1576,7 +1576,7 @@ bool IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy) if (newy && (newy < ibuf->y)) scaledowny(ibuf, newy); if (newx && (newx > ibuf->x)) scaleupx(ibuf, newx); if (newy && (newy > ibuf->y)) scaleupy(ibuf, newy); - + return true; } @@ -1602,15 +1602,15 @@ bool IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy if (ibuf->rect) do_rect = true; if (ibuf->rect_float) do_float = true; if (do_rect == false && do_float == false) return false; - + if (newx == ibuf->x && newy == ibuf->y) return false; - + if (do_rect) { _newrect = MEM_mallocN(newx * newy * sizeof(int), "scalefastimbuf"); if (_newrect == NULL) return false; newrect = _newrect; } - + if (do_float) { _newrectf = MEM_mallocN(newx * newy * sizeof(float) * 4, "scalefastimbuf f"); if (_newrectf == NULL) { diff --git a/source/blender/imbuf/intern/targa.c b/source/blender/imbuf/intern/targa.c index 0949a4312932..9d92d146f500 100644 --- a/source/blender/imbuf/intern/targa.c +++ b/source/blender/imbuf/intern/targa.c @@ -122,7 +122,7 @@ static bool makebody_tga(ImBuf *ibuf, FILE *file, int (*out)(unsigned int, FILE register int copy, bytes; register unsigned int *rect, *rectstart, *temp; int y; - + for (y = 0; y < ibuf->y; y++) { bytes = ibuf->x - 1; rectstart = rect = ibuf->rect + (y * ibuf->x); @@ -253,7 +253,7 @@ int imb_savetarga(struct ImBuf *ibuf, const char *name, int flags) char buf[20] = {0}; FILE *fildes; bool ok = false; - + (void)flags; /* unused */ buf[16] = (ibuf->planes + 0x7) & ~0x7; @@ -265,7 +265,7 @@ int imb_savetarga(struct ImBuf *ibuf, const char *name, int flags) } if (ibuf->foptions.flag & RAWTGA) buf[2] &= ~8; - + buf[8] = 0; buf[9] = 0; buf[10] = 0; @@ -308,7 +308,7 @@ int imb_savetarga(struct ImBuf *ibuf, const char *name, int flags) break; } } - + fclose(fildes); return ok; } @@ -353,7 +353,7 @@ static int checktarga(TARGA *tga, const unsigned char *mem) int imb_is_a_targa(const unsigned char *buf) { TARGA tga; - + return checktarga(&tga, buf); } @@ -378,13 +378,13 @@ static void decodetarga(struct ImBuf *ibuf, const unsigned char *mem, size_t mem int count, col, size; unsigned int *rect; uchar *cp = (uchar *) &col; - + if (ibuf == NULL) return; if (ibuf->rect == NULL) return; size = ibuf->x * ibuf->y; rect = ibuf->rect; - + /* set alpha */ cp[0] = 0xff; cp[1] = cp[2] = 0; @@ -573,10 +573,10 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char if (tga.imgtyp < 4) ibuf->foptions.flag |= RAWTGA; mem = mem + 18 + tga.numid; - + cp[0] = 0xff; cp[1] = cp[2] = 0; - + if (tga.mapsize) { /* load color map */ /*mincol = tga.maporig;*/ /*UNUSED*/ @@ -609,7 +609,7 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char } cmap[count] = cp_data; } - + size = 0; for (int cmap_index = cmap_max - 1; cmap_index > 0; cmap_index >>= 1) { size++; @@ -620,7 +620,7 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char cmap[0] &= BIG_LONG(0x00ffffffl); } } - + if (flags & IB_test) { if (cmap) { MEM_freeN(cmap); @@ -630,7 +630,7 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char if (tga.imgtyp != 1 && tga.imgtyp != 9) { /* happens sometimes (beuh) */ if (cmap) { - MEM_freeN(cmap); + MEM_freeN(cmap); cmap = NULL; } } @@ -653,7 +653,7 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char else if (tga.pixsize <= 32) decodetarga(ibuf, mem, mem_size, 3); break; } - + if (cmap) { /* apply color map */ rect = ibuf->rect; @@ -666,7 +666,7 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char MEM_freeN(cmap); } - + if (tga.pixsize == 16) { unsigned int col; rect = ibuf->rect; @@ -685,29 +685,29 @@ ImBuf *imb_loadtarga(const unsigned char *mem, size_t mem_size, int flags, char } ibuf->planes = 24; } - + if (tga.imgtyp == 3 || tga.imgtyp == 11) { uchar *crect; unsigned int *lrect, col; - + crect = (uchar *) ibuf->rect; lrect = (unsigned int *) ibuf->rect; - + for (size = ibuf->x * ibuf->y; size > 0; size--) { col = *lrect++; - + crect[0] = 255; crect[1] = crect[2] = crect[3] = col; crect += 4; } } - + if (tga.imgdes & 0x20) { IMB_flipy(ibuf); } if (ibuf->rect) IMB_convert_rgba_to_abgr(ibuf); - + return ibuf; } diff --git a/source/blender/imbuf/intern/thumbs.c b/source/blender/imbuf/intern/thumbs.c index d6179136d1f8..ed7bbae6935b 100644 --- a/source/blender/imbuf/intern/thumbs.c +++ b/source/blender/imbuf/intern/thumbs.c @@ -223,7 +223,7 @@ static bool uri_from_filename(const char *path, char *uri) { char orig_uri[URI_MAX]; const char *dirstart = path; - + #ifdef WIN32 { char vol[3]; diff --git a/source/blender/imbuf/intern/thumbs_blend.c b/source/blender/imbuf/intern/thumbs_blend.c index a589c285ef28..a2363f96bfa5 100644 --- a/source/blender/imbuf/intern/thumbs_blend.c +++ b/source/blender/imbuf/intern/thumbs_blend.c @@ -144,7 +144,7 @@ void IMB_thumb_overlay_blend(unsigned int *thumb, int width, int height, float a { int x, y; int stride_x = (margin_r - margin_l) - 2; - + for (y = 0; y < height; y++) { for (x = 0; x < width; x++, px += 4) { int hline = 0, vline = 0; diff --git a/source/blender/imbuf/intern/tiff.c b/source/blender/imbuf/intern/tiff.c index 914fcc4e847d..0d650daa1c99 100644 --- a/source/blender/imbuf/intern/tiff.c +++ b/source/blender/imbuf/intern/tiff.c @@ -47,7 +47,7 @@ #include "BLI_math.h" #include "BLI_utildefines.h" - + #include "BKE_global.h" #include "IMB_imbuf_types.h" @@ -137,10 +137,10 @@ static tsize_t imb_tiff_ReadProc(thandle_t handle, tdata_t data, tsize_t n) nRemaining = 0; else nRemaining = mfile->size - mfile->offset; - + if (nCopy > nRemaining) nCopy = nRemaining; - + /* on EOF, return immediately and read (copy) nothing */ if (nCopy <= 0) return (0); @@ -165,7 +165,7 @@ static tsize_t imb_tiff_WriteProc(thandle_t handle, tdata_t data, tsize_t n) (void)handle; (void)data; (void)n; - + printf("imb_tiff_WriteProc: this function should not be called.\n"); return (-1); } @@ -208,7 +208,7 @@ static toff_t imb_tiff_SeekProc(thandle_t handle, toff_t ofs, int whence) break; default: /* no other types are supported - return an error */ - fprintf(stderr, + fprintf(stderr, "imb_tiff_SeekProc: " "Unsupported TIFF SEEK type.\n"); return (-1); @@ -243,12 +243,12 @@ static int imb_tiff_CloseProc(thandle_t handle) fprintf(stderr, "imb_tiff_CloseProc: !mfile || !mfile->mem!\n"); return (0); } - + /* virtually close the file */ mfile->mem = NULL; mfile->offset = 0; mfile->size = 0; - + return (0); } @@ -281,7 +281,7 @@ static TIFF *imb_tiff_client_open(ImbTIFFMemFile *memFile, const unsigned char * memFile->offset = 0; memFile->size = size; - return TIFFClientOpen("(Blender TIFF Interface Layer)", + return TIFFClientOpen("(Blender TIFF Interface Layer)", "r", (thandle_t)(memFile), imb_tiff_ReadProc, imb_tiff_WriteProc, imb_tiff_SeekProc, imb_tiff_CloseProc, @@ -369,7 +369,7 @@ static void imb_read_tiff_resolution(ImBuf *ibuf, TIFF *image) } } -/* +/* * Use the libTIFF scanline API to read a TIFF image. * This method is most flexible and can handle multiple different bit depths * and RGB channel orderings. @@ -408,7 +408,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) imb_read_tiff_resolution(ibuf, image); scanline = TIFFScanlineSize(image); - + if (bitspersample == 32) { ib_flag = IB_rectfloat; fbuf = (float *)_TIFFmalloc(scanline); @@ -426,12 +426,12 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) else { ib_flag = IB_rect; } - + tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ib_flag); if (!tmpibuf) { goto cleanup; } - + /* simple RGBA image */ if (!(bitspersample == 32 || bitspersample == 16)) { success |= TIFFReadRGBAImage(image, ibuf->x, ibuf->y, tmpibuf->rect, 0); @@ -440,11 +440,11 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) else if (config == PLANARCONFIG_CONTIG) { for (row = 0; row < ibuf->y; row++) { size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1)); - + if (bitspersample == 32) { success |= TIFFReadScanline(image, fbuf, row, 0); scanline_contig_32bit(tmpibuf->rect_float + ib_offset, fbuf, ibuf->x, spp); - + } else if (bitspersample == 16) { success |= TIFFReadScanline(image, sbuf, row, 0); @@ -454,13 +454,13 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) /* separate channels: RRRGGGBBB */ } else if (config == PLANARCONFIG_SEPARATE) { - + /* imbufs always have 4 channels of data, so we iterate over all of them * but only fill in from the TIFF scanline where necessary. */ for (chan = 0; chan < 4; chan++) { for (row = 0; row < ibuf->y; row++) { size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1)); - + if (bitspersample == 32) { if (chan == 3 && spp == 3) /* fill alpha if only RGB TIFF */ copy_vn_fl(fbuf, ibuf->x, 1.0f); @@ -469,7 +469,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) else success |= TIFFReadScanline(image, fbuf, row, chan); scanline_separate_32bit(tmpibuf->rect_float + ib_offset, fbuf, ibuf->x, chan); - + } else if (bitspersample == 16) { if (chan == 3 && spp == 3) /* fill alpha if only RGB TIFF */ @@ -479,7 +479,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) else success |= TIFFReadScanline(image, sbuf, row, chan); scanline_separate_16bit(tmpibuf->rect_float + ib_offset, sbuf, ibuf->x, chan); - + } } } @@ -490,7 +490,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) if (bitspersample < 16) if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(tmpibuf); - + /* assign rect last */ if (tmpibuf->rect_float) ibuf->rect_float = tmpibuf->rect_float; @@ -498,7 +498,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) ibuf->rect = tmpibuf->rect; ibuf->mall |= ib_flag; ibuf->flags |= ib_flag; - + tmpibuf->mall &= ~ib_flag; } @@ -509,7 +509,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image) _TIFFfree(sbuf); IMB_freeImBuf(tmpibuf); - + return success; } @@ -564,15 +564,15 @@ ImBuf *imb_loadtiff(const unsigned char *mem, size_t size, int flags, char color TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height); TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &spp); - + ib_depth = (spp == 3) ? 24 : 32; - + ibuf = IMB_allocImBuf(width, height, ib_depth, 0); if (ibuf) { ibuf->ftype = IMB_FTYPE_TIF; } else { - fprintf(stderr, + fprintf(stderr, "imb_loadtiff: could not allocate memory for TIFF " "image.\n"); TIFFClose(image); @@ -808,7 +808,7 @@ int imb_savetiff(ImBuf *ibuf, const char *name, int flags) /* RGBA images */ TIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1, extraSampleTypes); - TIFFSetField(image, TIFFTAG_PHOTOMETRIC, + TIFFSetField(image, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else if (samplesperpixel == 3) { diff --git a/source/blender/imbuf/intern/util.c b/source/blender/imbuf/intern/util.c index 9dfe926ddffa..6a095b2da1fa 100644 --- a/source/blender/imbuf/intern/util.c +++ b/source/blender/imbuf/intern/util.c @@ -166,7 +166,7 @@ int IMB_ispic_type(const char *name) BLI_assert(!BLI_path_is_rel(name)); if (UTIL_DEBUG) printf("%s: loading %s\n", __func__, name); - + if (BLI_stat(name, &st) == -1) return false; if (((st.st_mode) & S_IFMT) != S_IFREG) @@ -281,7 +281,7 @@ static int isffmpeg(const char *filename) AVCodec *pCodec; AVCodecContext *pCodecCtx; - if (BLI_testextensie_n( + if (BLI_path_extension_check_n( filename, ".swf", ".jpg", ".png", ".dds", ".tga", ".bmp", ".tif", ".exr", ".cin", ".wav", NULL)) { @@ -378,13 +378,13 @@ int imb_get_anim_type(const char *name) return ANIM_NONE; } - + bool IMB_isanim(const char *filename) { int type; type = imb_get_anim_type(filename); - + return (type && type != ANIM_SEQUENCE); } diff --git a/source/blender/imbuf/readme.txt b/source/blender/imbuf/readme.txt index d50cb8c781dc..855f62294206 100644 --- a/source/blender/imbuf/readme.txt +++ b/source/blender/imbuf/readme.txt @@ -15,11 +15,11 @@ short imb_saveopenexr(struct ImBuf *ibuf, char *myfile, int flags); /* Used to test if its the correct format int IMB_is_openexr(void *buf); -Step 2: +Step 2: Add your hooks to read and write the image format these go in writeimage.c and readimage.c just look at how the others are done -Step 3: +Step 3: Add in IS_openexr to blender/source/blender/imbuf/IMB_imbuf_types.h Add in R_openexr to source/blender/makesdna/DNA_scene_types.h @@ -36,11 +36,11 @@ blender/source/blender/src/filesel.c blender/source/blender/src/screendump.c and add your extension so that your format gets recognized in the thumbnails. -Step 6: +Step 6: Alter the build process: For cmake you need to edit blender/source/blender/imbuf/CMakeLists.txt and add in your additional files to source_files. -If you have any external library info you will also need to add that +If you have any external library info you will also need to add that to the various build processes. Step 7: diff --git a/source/blender/makesdna/DNA_ID.h b/source/blender/makesdna/DNA_ID.h index c632b87752ba..0c7341b0fae9 100644 --- a/source/blender/makesdna/DNA_ID.h +++ b/source/blender/makesdna/DNA_ID.h @@ -153,7 +153,7 @@ typedef struct Library { char filepath[1024]; struct Library *parent; /* set for indirectly linked libs, used in the outliner and while reading */ - + struct PackedFile *packedfile; /* Temp data needed by read/write code. */ diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h index 0e13aff4d442..e255b85ebe37 100644 --- a/source/blender/makesdna/DNA_action_types.h +++ b/source/blender/makesdna/DNA_action_types.h @@ -72,10 +72,10 @@ typedef enum eMotionPathVert_Flag { typedef struct bMotionPath { bMotionPathVert *points; /* path samples */ int length; /* the number of cached verts */ - + int start_frame; /* for drawing paths, the start frame number */ int end_frame; /* for drawing paths, the end frame number */ - + float color[3]; /* optional custom color */ int line_thickness; /* line thickness */ int flag; /* baking settings - eMotionPath_Flag */ @@ -90,7 +90,7 @@ typedef enum eMotionPath_Flag { /* Custom colors */ MOTIONPATH_FLAG_CUSTOM = (1 << 2), /* Draw lines or only points */ - MOTIONPATH_FLAG_LINES = (1 << 3) + MOTIONPATH_FLAG_LINES = (1 << 3) } eMotionPath_Flag; /* Visualization General --------------------------- */ @@ -101,22 +101,22 @@ typedef struct bAnimVizSettings { /* Onion-Skinning Settings ----------------- */ int ghost_sf, ghost_ef; /* start and end frames of ghost-drawing range (only used for GHOST_TYPE_RANGE) */ int ghost_bc, ghost_ac; /* number of frames before/after current frame to show */ - + short ghost_type; /* eOnionSkin_Types */ short ghost_step; /* number of frames between each ghost shown (not for GHOST_TYPE_KEYS) */ - + short ghost_flag; /* eOnionSkin_Flag */ - + /* General Settings ------------------------ */ short recalc; /* eAnimViz_RecalcFlags */ - + /* Motion Path Settings ------------------- */ short path_type; /* eMotionPath_Types */ short path_step; /* number of frames between points indicated on the paths */ - + short path_viewflag; /* eMotionPaths_ViewFlag */ short path_bakeflag; /* eMotionPaths_BakeFlag */ - + int path_sf, path_ef; /* start and end frames of path-calculation range */ int path_bc, path_ac; /* number of frames before/after current frame to show */ } bAnimVizSettings; @@ -185,19 +185,19 @@ typedef enum eMotionPaths_BakeFlag { /* PoseChannel ------------------------------------ */ -/* PoseChannel +/* PoseChannel * * A PoseChannel stores the results of Actions and transform information * with respect to the restposition of Armature bones */ typedef struct bPoseChannel { struct bPoseChannel *next, *prev; - + IDProperty *prop; /* User-Defined Properties on this PoseChannel */ - + ListBase constraints; /* Constraints that act on this PoseChannel */ char name[64]; /* need to match bone name length: MAXBONENAME */ - + short flag; /* dynamic, for detecting transform changes */ short ikflag; /* settings for IK bones */ short protectflag; /* protect channels from being transformed */ @@ -234,32 +234,32 @@ typedef struct bPoseChannel { float rotAxis[3], rotAngle; /* axis-angle rotation */ short rotmode; /* eRotationModes - rotation representation to use */ short pad; - + float chan_mat[4][4]; /* matrix result of loc/quat/size, and where we put deform in, see next line */ float pose_mat[4][4]; /* constraints accumulate here. in the end, pose_mat = bone->arm_mat * chan_mat * this matrix is object space */ float constinv[4][4]; /* inverse result of constraints. * doesn't include effect of restposition, parent, and local transform*/ - + float pose_head[3]; /* actually pose_mat[3] */ float pose_tail[3]; /* also used for drawing help lines... */ - + float limitmin[3], limitmax[3]; /* DOF constraint, note! - these are stored in degrees, not radians */ float stiffness[3]; /* DOF stiffness */ float ikstretch; float ikrotweight; /* weight of joint rotation constraint */ float iklinweight; /* weight of joint stretch constraint */ - + /* curved bones settings - these are for animating, and are applied on top of the copies in pchan->bone */ float roll1, roll2; float curveInX, curveInY; float curveOutX, curveOutY; float ease1, ease2; float scaleIn, scaleOut; - + struct bPoseChannel *bbone_prev; /* next/prev bones to use as handle references when calculating bbones (optional) */ struct bPoseChannel *bbone_next; - + void *temp; /* use for outliner */ } bPoseChannel; @@ -270,16 +270,16 @@ typedef enum ePchan_Flag { POSE_LOC = (1 << 0), POSE_ROT = (1 << 1), POSE_SIZE = (1 << 2), - + /* old IK/cache stuff - * - used to be here from (1 << 3) to (1 << 8) + * - used to be here from (1 << 3) to (1 << 8) * but has been repurposed since 2.77.2 * as they haven't been used in over 10 years */ - + /* has BBone deforms */ POSE_BBONE_SHAPE = (1 << 3), - + /* IK/Pose solving */ POSE_CHAIN = (1 << 9), POSE_DONE = (1 << 10), @@ -357,8 +357,8 @@ typedef enum eRotationModes { ROT_MODE_YZX = 4, ROT_MODE_ZXY = 5, ROT_MODE_ZYX = 6, - /* NOTE: space is reserved here for 18 other possible - * euler rotation orders not implemented + /* NOTE: space is reserved here for 18 other possible + * euler rotation orders not implemented */ /* axis angle rotations */ ROT_MODE_AXISANGLE = -1, @@ -369,7 +369,7 @@ typedef enum eRotationModes { /* Pose ------------------------------------ */ -/* Pose-Object. +/* Pose-Object. * * It is only found under ob->pose. It is not library data, even * though there is a define for it (hack for the outliner). @@ -386,19 +386,19 @@ typedef struct bPose { short flag, pad; unsigned int proxy_layer; /* proxy layer: copy from armature, gets synced */ int pad1; - + float ctime; /* local action time of this pose */ float stride_offset[3]; /* applied to object */ float cyclic_offset[3]; /* result of match and cycles, applied in BKE_pose_where_is() */ - - + + ListBase agroups; /* list of bActionGroups */ - + int active_group; /* index of active group (starts from 1) */ int iksolver; /* ik solver to use, see ePose_IKSolverType */ void *ikdata; /* temporary IK data, depends on the IK solver. Not saved in file */ void *ikparam; /* IK solver parameters, structure depends on iksolver */ - + bAnimVizSettings avs; /* settings for visualization of bone animation */ char proxy_act_bone[64]; /* proxy active bone name, MAXBONENAME */ } bPose; @@ -489,13 +489,13 @@ typedef enum eItasc_Solver { */ typedef struct bActionGroup { struct bActionGroup *next, *prev; - + ListBase channels; /* Note: this must not be touched by standard listbase functions which would clear links to other channels */ - + int flag; /* settings for this action-group */ int customCol; /* index of custom color set to use when used for bones (0=default - used for all old files, -1=custom set) */ char name[64]; /* name of the group */ - + ThemeWireColor cs; /* color set to use when customCol == -1 */ } bActionGroup; @@ -518,7 +518,7 @@ typedef enum eActionGroup_Flag { /* sub channel modifiers off */ AGRP_MODIFIERS_OFF = (1 << 7), - + AGRP_TEMP = (1 << 30), AGRP_MOVED = (1u << 31) } eActionGroup_Flag; @@ -526,7 +526,7 @@ typedef enum eActionGroup_Flag { /* Actions -------------------------------------- */ -/* Action - reusable F-Curve 'bag' (act) +/* Action - reusable F-Curve 'bag' (act) * * This contains F-Curves that may affect settings from more than one ID blocktype and/or * datablock (i.e. sub-data linked/used directly to the ID block that the animation data is linked to), @@ -538,15 +538,15 @@ typedef enum eActionGroup_Flag { */ typedef struct bAction { ID id; /* ID-serialisation for relinking */ - + ListBase curves; /* function-curves (FCurve) */ ListBase chanbase DNA_DEPRECATED; /* legacy data - Action Channels (bActionChannel) in pre-2.5 animation system */ ListBase groups; /* groups of function-curves (bActionGroup) */ ListBase markers; /* markers local to the Action (used to provide Pose-Libraries) */ - + int flag; /* settings for this action */ int active_marker; /* index of the active marker */ - + int idroot; /* type of ID-blocks that action can be assigned to (if 0, will be set to whatever ID first evaluates it) */ int pad; } bAction; @@ -572,13 +572,13 @@ typedef enum eAction_Flags { typedef struct bDopeSheet { ID *source; /* currently ID_SCE (for Dopesheet), and ID_SC (for Grease Pencil) */ ListBase chanbase; /* cache for channels (only initialized when pinned) */ // XXX not used! - + struct Group *filter_grp; /* object group for ADS_FILTER_ONLYOBGROUP filtering option */ char searchstr[64]; /* string to search for in displayed names of F-Curves for ADS_FILTER_BY_FCU_NAME filtering option */ - + int filterflag; /* flags to use for filtering data */ int flag; /* standard flags */ - + int renameIndex; /* index+1 of channel to rename - only gets set by renaming operator */ int pad; } bDopeSheet; @@ -588,7 +588,7 @@ typedef struct bDopeSheet { typedef enum eDopeSheet_FilterFlag { /* general filtering */ ADS_FILTER_ONLYSEL = (1 << 0), /* only include channels relating to selected data */ - + /* temporary filters */ ADS_FILTER_ONLYDRIVERS = (1 << 1), /* for 'Drivers' editor - only include Driver data from AnimData */ ADS_FILTER_ONLYNLA = (1 << 2), /* for 'NLA' editor - only include NLA data from AnimData */ @@ -627,22 +627,22 @@ typedef enum eDopeSheet_FilterFlag { ADS_FILTER_INCL_HIDDEN = (1 << 26), /* include 'hidden' channels too (i.e. those from hidden Objects/Bones) */ ADS_FILTER_BY_FCU_NAME = (1 << 27), /* for F-Curves, filter by the displayed name (i.e. to isolate all Location curves only) */ ADS_FILTER_ONLY_ERRORS = (1 << 28), /* show only F-Curves which are disabled/have errors - for debugging drivers */ - + /* GPencil Mode */ ADS_FILTER_GP_3DONLY = (1 << 29), /* GP Mode - Only show datablocks used in the scene */ - + /* combination filters (some only used at runtime) */ ADS_FILTER_NOOBDATA = (ADS_FILTER_NOCAM | ADS_FILTER_NOMAT | ADS_FILTER_NOLAM | ADS_FILTER_NOCUR | ADS_FILTER_NOPART | ADS_FILTER_NOARM | ADS_FILTER_NOSPK | ADS_FILTER_NOMODIFIERS) -} eDopeSheet_FilterFlag; +} eDopeSheet_FilterFlag; /* DopeSheet general flags */ typedef enum eDopeSheet_Flag { ADS_FLAG_SUMMARY_COLLAPSED = (1 << 0), /* when summary is shown, it is collapsed, so all other channels get hidden */ ADS_FLAG_SHOW_DBFILTERS = (1 << 1), /* show filters for datablocks */ - + ADS_FLAG_FUZZY_NAMES = (1 << 2), /* use fuzzy/partial string matches when ADS_FILTER_BY_FCU_NAME is enabled (WARNING: expensive operation) */ ADS_FLAG_NO_DB_SORT = (1 << 3), /* do not sort datablocks (mostly objects) by name (NOTE: potentially expensive operation) */ - + /* NOTE: datablock filter flags continued (1 << 10) onwards... */ } eDopeSheet_Flag; @@ -658,10 +658,10 @@ typedef struct SpaceAction { /* End 'SpaceLink' header. */ View2D v2d DNA_DEPRECATED; /* copied to region */ - + bAction *action; /* the currently active action */ bDopeSheet ads; /* the currently active context (when not showing action) */ - + char mode, autosnap; /* mode: editing context; autosnap: automatic keyframe snapping mode */ short flag; /* flag: bitmapped settings; */ float timeslide; /* for Time-Slide transform mode drawing - current frame? */ @@ -693,7 +693,7 @@ typedef enum eSAction_Flag { SACTION_NOREALTIMEUPDATES = (1 << 10), /* move markers as well as keyframes */ SACTION_MARKERS_MOVE = (1 << 11) -} eSAction_Flag; +} eSAction_Flag; /* SpaceAction Mode Settings */ typedef enum eAnimEdit_Context { @@ -745,10 +745,10 @@ typedef enum eAnimEdit_AutoSnap { typedef struct bActionChannel { struct bActionChannel *next, *prev; bActionGroup *grp; /* Action Group this Action Channel belongs to */ - + struct Ipo *ipo; /* IPO block this action channel references */ ListBase constraintChannels; /* Constraint Channels (when Action Channel represents an Object or Bone) */ - + int flag; /* settings accessed via bitmapping */ char name[64]; /* channel name, MAX_NAME */ int temp; /* temporary setting - may be used to indicate group that channel belongs to during syncing */ diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h index b9683649163f..70fe722719d3 100644 --- a/source/blender/makesdna/DNA_actuator_types.h +++ b/source/blender/makesdna/DNA_actuator_types.h @@ -132,9 +132,9 @@ typedef struct bIpoActuator { float sta, end; char name[64]; /* MAX_NAME */ char frameProp[64]; /* Set this property to the actions current frame, MAX_NAME */ - + short pad1, pad2, pad3, pad4; - + } bIpoActuator; typedef struct bCameraActuator { @@ -159,10 +159,10 @@ typedef struct bGroupActuator { short flag, type; int sta, end; char name[64]; /* property or groupkey, MAX_NAME */ - + short pad[3], cur, butsta, butend;/* not referenced, can remove? */ /* struct Group *group; not used, remove */ - + } bGroupActuator; /* I added a few extra fields here, to facilitate conversions */ @@ -200,8 +200,8 @@ typedef struct bVibrationActuator { } bVibrationActuator; typedef struct bVisibilityActuator { - /** bit 0: Is this object visible? - ** bit 1: Apply recursively + /** bit 0: Is this object visible? + ** bit 1: Apply recursively ** bit 2: Is this object an occluder? */ int flag; } bVisibilityActuator; @@ -272,7 +272,7 @@ typedef struct bActuator { struct bActuator *next, *prev, *mynew; short type; /** - * Tells what type of actuator data \ref data holds. + * Tells what type of actuator data \ref data holds. */ short flag; short otype, go; @@ -348,8 +348,8 @@ typedef struct bActuator { #define ACT_SHOW 1 #define ACT_DEL 2 #define ACT_NEW 4 -#define ACT_LINKED 8 -#define ACT_VISIBLE 16 +#define ACT_LINKED 8 +#define ACT_VISIBLE 16 #define ACT_PIN 32 #define ACT_DEACTIVATE 64 diff --git a/source/blender/makesdna/DNA_anim_types.h b/source/blender/makesdna/DNA_anim_types.h index f5260319eff3..d0a21b50d455 100644 --- a/source/blender/makesdna/DNA_anim_types.h +++ b/source/blender/makesdna/DNA_anim_types.h @@ -44,30 +44,30 @@ extern "C" { /* Modifiers -------------------------------------- */ -/* F-Curve Modifiers (fcm) +/* F-Curve Modifiers (fcm) * * These alter the way F-Curves behave, by altering the value that is returned * when evaluating the curve's data at some time (t). */ typedef struct FModifier { struct FModifier *next, *prev; - + struct FCurve *curve; /* containing curve, only used for updates to CYCLES */ void *data; /* pointer to modifier data */ - + char name[64]; /* user-defined description for the modifier - MAX_ID_NAME-2 */ short type; /* type of f-curve modifier */ short flag; /* settings for the modifier */ - + float influence; /* the amount that the modifier should influence the value */ - + float sfra; /* start frame of restricted frame-range */ float efra; /* end frame of restricted frame-range */ float blendin; /* number of frames from sfra before modifier takes full influence */ float blendout; /* number of frames from efra before modifier fades out */ } FModifier; -/* Types of F-Curve modifier +/* Types of F-Curve modifier * WARNING: order here is important! */ typedef enum eFModifier_Types { @@ -81,7 +81,7 @@ typedef enum eFModifier_Types { FMODIFIER_TYPE_PYTHON = 7, FMODIFIER_TYPE_LIMITS = 8, FMODIFIER_TYPE_STEPPED = 9, - + /* NOTE: all new modifiers must be added above this line */ FMODIFIER_NUM_TYPES } eFModifier_Types; @@ -100,7 +100,7 @@ typedef enum eFModifier_Flags { FMODIFIER_FLAG_RANGERESTRICT = (1<<4), /* use influence control */ FMODIFIER_FLAG_USEINFLUENCE = (1<<5) -} eFModifier_Flags; +} eFModifier_Flags; /* --- */ @@ -109,10 +109,10 @@ typedef struct FMod_Generator { /* general generator information */ float *coefficients; /* coefficients array */ unsigned int arraysize; /* size of the coefficients array */ - + int poly_order; /* order of polynomial generated (i.e. 1 for linear, 2 for quadratic) */ int mode; /* which 'generator' to use eFMod_Generator_Modes */ - + /* settings */ int flag; /* settings */ } FMod_Generator; @@ -124,7 +124,7 @@ typedef enum eFMod_Generator_Modes { } eFMod_Generator_Modes; -/* generator flags +/* generator flags * - shared by Generator and Function Generator */ typedef enum eFMod_Generator_Flags { @@ -147,7 +147,7 @@ typedef struct FMod_FunctionGenerator { float phase_multiplier; float phase_offset; float value_offset; - + /* flags */ int type; /* eFMod_Generator_Functions */ int flag; /* eFMod_Generator_flags */ @@ -168,7 +168,7 @@ typedef enum eFMod_Generator_Functions { typedef struct FCM_EnvelopeData { float min, max; /* min/max values for envelope at this point (absolute values) */ float time; /* time for that this sample-point occurs */ - + short f1; /* settings for 'min' control point */ short f2; /* settings for 'max' control point */ } FCM_EnvelopeData; @@ -177,7 +177,7 @@ typedef struct FCM_EnvelopeData { typedef struct FMod_Envelope { FCM_EnvelopeData *data; /* data-points defining envelope to apply (array) */ int totvert; /* number of envelope points */ - + float midval; /* value that envelope's influence is centered around / based on */ float min, max; /* distances from 'middle-value' for 1:1 envelope influence */ } FMod_Envelope; @@ -230,11 +230,11 @@ typedef struct FMod_Noise { float strength; float phase; float offset; - + short depth; short modification; } FMod_Noise; - + /* modification modes */ typedef enum eFMod_Noise_Modifications { FCM_NOISE_MODIF_REPLACE = 0, /* Modify existing curve, matching it's shape */ @@ -269,31 +269,31 @@ typedef enum eFMod_Stepped_Flags { */ typedef struct DriverTarget { ID *id; /* ID-block which owns the target, no user count */ - + char *rna_path; /* RNA path defining the setting to use (for DVAR_TYPE_SINGLE_PROP) */ - + char pchan_name[64]; /* name of the posebone to use (for vars where DTAR_FLAG_STRUCT_REF is used) - MAX_ID_NAME-2 */ short transChan; /* transform channel index (for DVAR_TYPE_TRANSFORM_CHAN)*/ - + short flag; /* flags for the validity of the target (NOTE: these get reset every time the types change) */ int idtype; /* type of ID-block that this target can use */ } DriverTarget; /* Driver Target flags */ typedef enum eDriverTarget_Flag { - /* used for targets that use the pchan_name instead of RNA path - * (i.e. rotation difference) + /* used for targets that use the pchan_name instead of RNA path + * (i.e. rotation difference) */ DTAR_FLAG_STRUCT_REF = (1 << 0), /* idtype can only be 'Object' */ DTAR_FLAG_ID_OB_ONLY = (1 << 1), - + /* "localspace" flags */ /* base flag - basically "pre parent+constraints" */ DTAR_FLAG_LOCALSPACE = (1 << 2), /* include constraints transformed to space including parents */ DTAR_FLAG_LOCAL_CONSTS = (1 << 3), - + /* error flags */ DTAR_FLAG_INVALID = (1 << 4), } eDriverTarget_Flag; @@ -309,7 +309,7 @@ typedef enum eDriverTarget_TransformChannels { DTAR_TRANSCHAN_SCALEX, DTAR_TRANSCHAN_SCALEY, DTAR_TRANSCHAN_SCALEZ, - + MAX_DTAR_TRANSCHAN_TYPES } eDriverTarget_TransformChannels; @@ -328,14 +328,14 @@ typedef enum eDriverTarget_TransformChannels { */ typedef struct DriverVar { struct DriverVar *next, *prev; - + char name[64]; /* name of the variable to use in py-expression (must be valid python identifier) - MAX_ID_NAME-2 */ - + DriverTarget targets[8]; /* MAX_DRIVER_TARGETS, target slots */ - + char num_targets; /* number of targets actually used by this variable */ char type; /* type of driver variable (eDriverVar_Types) */ - + short flag; /* validation tags, etc. (eDriverVar_Flags) */ float curval; /* result of previous evaluation */ } DriverVar; @@ -350,8 +350,8 @@ typedef enum eDriverVar_Types { DVAR_TYPE_LOC_DIFF, /* 'final' transform for object/bones */ DVAR_TYPE_TRANSFORM_CHAN, - - /* maximum number of variable types + + /* maximum number of variable types * NOTE: this must always be th last item in this list, * so add new types above this line */ @@ -362,7 +362,7 @@ typedef enum eDriverVar_Types { typedef enum eDriverVar_Flags { /* variable is not set up correctly */ DVAR_FLAG_ERROR = (1 << 0), - + /* variable name doesn't pass the validation tests */ DVAR_FLAG_INVALID_NAME = (1 << 1), /* name starts with a number */ @@ -408,16 +408,16 @@ typedef enum eDriverVar_Flags { */ typedef struct ChannelDriver { ListBase variables; /* targets for this driver (i.e. list of DriverVar) */ - - /* python expression to execute (may call functions defined in an accessory file) + + /* python expression to execute (may call functions defined in an accessory file) * which relates the target 'variables' in some way to yield a single usable value */ char expression[256]; /* expression to compile for evaluation */ void *expr_comp; /* PyObject - compiled expression, don't save this */ - + float curval; /* result of previous evaluation */ float influence; /* influence of driver on result */ // XXX to be implemented... this is like the constraint influence setting - + /* general settings */ int type; /* type of driver */ int flag; /* settings of driver */ @@ -472,32 +472,32 @@ typedef struct FPoint { /* 'Function-Curve' - defines values over time for a given setting (fcu) */ typedef struct FCurve { struct FCurve *next, *prev; - + /* group */ bActionGroup *grp; /* group that F-Curve belongs to */ - + /* driver settings */ ChannelDriver *driver; /* only valid for drivers (i.e. stored in AnimData not Actions) */ /* evaluation settings */ ListBase modifiers; /* FCurve Modifiers */ - + /* motion data */ BezTriple *bezt; /* user-editable keyframes (array) */ FPoint *fpt; /* 'baked/imported' motion samples (array) */ unsigned int totvert; /* total number of points which define the curve (i.e. size of arrays in FPoints) */ - + /* value cache + settings */ float curval; /* value stored from last time curve was evaluated (not threadsafe, debug display only!) */ short flag; /* user-editable settings for this curve */ short extend; /* value-extending mode for this curve (does not cover */ char auto_smoothing; /* auto-handle smoothing mode */ - + char pad[7]; /* RNA - data link */ int array_index; /* if applicable, the index of the RNA-array item to get */ char *rna_path; /* RNA-path to resolve data-access */ - + /* curve coloring (for editor) */ int color_mode; /* coloring method to use (eFCurve_Coloring) */ float color[3]; /* the last-color this curve took */ @@ -518,7 +518,7 @@ typedef enum eFCurve_Flags { FCURVE_PROTECTED = (1<<3), /* fcurve will not be evaluated for the next round */ FCURVE_MUTED = (1<<4), - + /* fcurve uses 'auto-handles', which stay horizontal... */ // DEPRECATED FCURVE_AUTO_HANDLES = (1<<5), @@ -529,7 +529,7 @@ typedef enum eFCurve_Flags { FCURVE_INT_VALUES = (1<<11), /* curve can only have certain discrete-number values (no interpolation at all, for enums/booleans) */ FCURVE_DISCRETE_VALUES = (1<<12), - + /* temporary tag for editing */ FCURVE_TAGGED = (1<<15) } eFCurve_Flags; @@ -561,7 +561,7 @@ typedef enum eFCurve_Smoothing { * they are not stored here... see DNA_action_types.h instead */ - + /* ************************************************ */ /* Animation Reuse - i.e. users of Actions */ @@ -580,7 +580,7 @@ typedef struct AnimMapPair { char to[128]; /* part of path to replace with */ } AnimMapPair; -/* Retargetting Information for Actions +/* Retargetting Information for Actions * * This should only be used if it is strictly necessary (i.e. user will need to explicitly * add this when they find that some channels do not match, or motion is not going to right @@ -593,7 +593,7 @@ typedef struct AnimMapPair { // such consequences... typedef struct AnimMapper { struct AnimMapper *next, *prev; - + bAction *target; /* target action */ ListBase mappings; /* remapping table (bAnimMapPair) */ } AnimMapper; @@ -699,14 +699,14 @@ typedef enum eNlaStrip_Flag { } eNlaStrip_Flag; /* NLA Strip Type */ -typedef enum eNlaStrip_Type { +typedef enum eNlaStrip_Type { /* 'clip' - references an Action */ NLASTRIP_TYPE_CLIP = 0, /* 'transition' - blends between the adjacent strips */ NLASTRIP_TYPE_TRANSITION, /* 'meta' - a strip which acts as a container for a few others */ NLASTRIP_TYPE_META, - + /* 'emit sound' - a strip which is used for timing when speaker emits sounds */ NLASTRIP_TYPE_SOUND } eNlaStrip_Type; @@ -722,12 +722,12 @@ typedef enum eNlaStrip_Type { */ typedef struct NlaTrack { struct NlaTrack *next, *prev; - + ListBase strips; /* bActionStrips in this track */ - + int flag; /* settings for this track */ int index; /* index of the track in the stack (NOTE: not really useful, but we need a pad var anyways!) */ - + char name[64]; /* short user-description of this track - MAX_ID_NAME-2 */ } NlaTrack; @@ -743,7 +743,7 @@ typedef enum eNlaTrack_Flag { NLATRACK_SOLO = (1<<3), /* track's settings (and strips) cannot be edited (to guard against unwanted changes) */ NLATRACK_PROTECTED = (1<<4), - + /* track is not allowed to execute, usually as result of tweaking being enabled (internal flag) */ NLATRACK_DISABLED = (1<<10) } eNlaTrack_Flag; @@ -752,7 +752,7 @@ typedef enum eNlaTrack_Flag { /* ************************************ */ /* KeyingSet Datatypes */ -/* Path for use in KeyingSet definitions (ksp) +/* Path for use in KeyingSet definitions (ksp) * * Paths may be either specific (specifying the exact sub-ID * dynamic data-block - such as PoseChannels - to act upon, ala @@ -762,18 +762,18 @@ typedef enum eNlaTrack_Flag { */ typedef struct KS_Path { struct KS_Path *next, *prev; - + ID *id; /* ID block that keyframes are for */ char group[64]; /* name of the group to add to - MAX_ID_NAME-2 */ - + int idtype; /* ID-type that path can be used on */ - + short groupmode; /* group naming (eKSP_Grouping) */ short flag; /* various settings, etc. */ - + char *rna_path; /* dynamically (or statically in the case of predefined sets) path */ int array_index; /* index that path affects */ - + short keyingflag; /* (eInsertKeyFlags) settings to supply insertkey() with */ short keyingoverride; /* (eInsertKeyFlags) for each flag set, the relevant keyingflag bit overrides the default */ } KS_Path; @@ -792,14 +792,14 @@ typedef enum eKSP_Grouping { KSP_GROUP_NONE, /* path should be grouped using KeyingSet's name */ KSP_GROUP_KSNAME, - /* path should be grouped using name of inner-most context item from templates + /* path should be grouped using name of inner-most context item from templates * - this is most useful for relative KeyingSets only */ KSP_GROUP_TEMPLATE_ITEM } eKSP_Grouping; /* ---------------- */ - + /* KeyingSet definition (ks) * * A KeyingSet defines a group of properties that should @@ -812,21 +812,21 @@ typedef enum eKSP_Grouping { */ typedef struct KeyingSet { struct KeyingSet *next, *prev; - + ListBase paths; /* (KS_Path) paths to keyframe to */ - + char idname[64]; /* unique name (for search, etc.) - MAX_ID_NAME-2 */ char name[64]; /* user-viewable name for KeyingSet (for menus, etc.) - MAX_ID_NAME-2 */ char description[240]; /* (RNA_DYN_DESCR_MAX) short help text. */ char typeinfo[64]; /* name of the typeinfo data used for the relative paths - MAX_ID_NAME-2 */ - + int active_path; /* index of the active path */ - + short flag; /* settings for KeyingSet */ - + short keyingflag; /* (eInsertKeyFlags) settings to supply insertkey() with */ short keyingoverride; /* (eInsertKeyFlags) for each flag set, the relevant keyingflag bit overrides the default */ - + char pad[6]; } KeyingSet; @@ -859,7 +859,7 @@ typedef enum eInsertKeyFlags { /* AnimOverride ------------------------------------- */ -/* Animation Override (aor) +/* Animation Override (aor) * * This is used to as temporary storage of values which have been changed by the user, but not * yet keyframed (thus, would get overwritten by the animation system before the user had a chance @@ -870,10 +870,10 @@ typedef enum eInsertKeyFlags { */ typedef struct AnimOverride { struct AnimOverride *next, *prev; - + char *rna_path; /* RNA-path to use to resolve data-access */ int array_index; /* if applicable, the index of the RNA-array item to get */ - + float value; /* value to override setting with */ } AnimOverride; @@ -965,7 +965,7 @@ typedef enum eAnimData_Recalc { /* Base Struct for Anim ------------------------------------- */ -/* Used for BKE_animdata_from_id() +/* Used for BKE_animdata_from_id() * All ID-datablocks which have their own 'local' AnimData * should have the same arrangement in their structs. */ diff --git a/source/blender/makesdna/DNA_armature_types.h b/source/blender/makesdna/DNA_armature_types.h index 757c0eb8394d..f1fe370788d3 100644 --- a/source/blender/makesdna/DNA_armature_types.h +++ b/source/blender/makesdna/DNA_armature_types.h @@ -67,17 +67,17 @@ typedef struct Bone { float dist, weight; /* dist, weight: for non-deformgroup deforms */ float xwidth, length, zwidth; /* width: for block bones. keep in this order, transform! */ float rad_head, rad_tail; /* radius for head/tail sphere, defining deform as well, parent->rad_tip overrides rad_head */ - + float roll1, roll2; /* curved bones settings - these define the "restpose" for a curved bone */ float curveInX, curveInY; float curveOutX, curveOutY; float ease1, ease2; /* length of bezier handles */ float scaleIn, scaleOut; - + float size[3]; /* patch for upward compat, UNUSED! */ int layer; /* layers that bone appears on */ short segments; /* for B-bones */ - + short pad1; } Bone; @@ -213,7 +213,7 @@ typedef enum eBone_Flag { BONE_NO_LOCAL_LOCATION = (1 << 22), /* bone location is in armature space */ BONE_RELATIVE_PARENTING = (1 << 23), /* object child will use relative transform (like deform) */ BONE_ADD_PARENT_END_ROLL = (1 << 24) /* it will add the parent end roll to the inroll */ - + } eBone_Flag; #define MAXBONENAME 64 diff --git a/source/blender/makesdna/DNA_boid_types.h b/source/blender/makesdna/DNA_boid_types.h index 44764eb012eb..a161fde119e0 100644 --- a/source/blender/makesdna/DNA_boid_types.h +++ b/source/blender/makesdna/DNA_boid_types.h @@ -154,7 +154,7 @@ typedef struct BoidState { ListBase actions; char name[32]; int id, flag; - + /* rules */ int ruleset_type; float rule_fuzziness; diff --git a/source/blender/makesdna/DNA_camera_types.h b/source/blender/makesdna/DNA_camera_types.h index ddf6af62291a..e011ef123476 100644 --- a/source/blender/makesdna/DNA_camera_types.h +++ b/source/blender/makesdna/DNA_camera_types.h @@ -68,8 +68,8 @@ typedef struct GameCameraViewportSettings { typedef struct Camera { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + char type; /* CAM_PERSP, CAM_ORTHO or CAM_PANO */ char dtx; /* draw type extra */ short flag; @@ -90,7 +90,7 @@ typedef struct Camera { int pad3; struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ - + struct Object *dof_ob; struct GPUDOFSettings gpu_dof; diff --git a/source/blender/makesdna/DNA_cloth_types.h b/source/blender/makesdna/DNA_cloth_types.h index ee147da8dae1..992cfedbc476 100644 --- a/source/blender/makesdna/DNA_cloth_types.h +++ b/source/blender/makesdna/DNA_cloth_types.h @@ -78,7 +78,7 @@ typedef struct ClothSimSettings { float vel_damping; /* damp the velocity to speed up getting to the resting position */ float shrink_min; /* min amount to shrink cloth by 0.0f (no shrink) - 1.0f (shrink to nothing) */ float shrink_max; /* max amount to shrink cloth by 0.0f (no shrink) - 1.0f (shrink to nothing) */ - + /* XXX various hair stuff * should really be separate, this struct is a horrible mess already */ diff --git a/source/blender/makesdna/DNA_color_types.h b/source/blender/makesdna/DNA_color_types.h index 6f9c407c6c60..8ed38b0b05dd 100644 --- a/source/blender/makesdna/DNA_color_types.h +++ b/source/blender/makesdna/DNA_color_types.h @@ -55,7 +55,7 @@ enum { typedef struct CurveMap { short totpoint, flag; - + float range; /* quick multiply value for reading table */ float mintable, maxtable; /* the x-axis range for the table */ float ext_in[2], ext_out[2]; /* for extrapolated curves, the direction vector */ @@ -74,13 +74,13 @@ typedef struct CurveMapping { int flag, cur; /* cur; for buttons, to show active curve */ int preset; int changed_timestamp; - + rctf curr, clipr; /* current rect, clip rect (is default rect too) */ - + CurveMap cm[4]; /* max 4 builtin curves per mapping struct now */ float black[3], white[3]; /* black/white point (black[0] abused for current frame) */ float bwmul[3]; /* black/white point multiply value, for speed */ - + float sample[3]; /* sample values, if flag set it draws line and intersection */ } CurveMapping; diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h index 11cb9d3f708a..4d9b85b38ad9 100644 --- a/source/blender/makesdna/DNA_constraint_types.h +++ b/source/blender/makesdna/DNA_constraint_types.h @@ -53,23 +53,23 @@ typedef struct bConstraintChannel { /* A Constraint */ typedef struct bConstraint { struct bConstraint *next, *prev; - + void *data; /* Constraint data (a valid constraint type) */ short type; /* Constraint type */ short flag; /* Flag - General Settings */ - + char ownspace; /* Space that owner should be evaluated in */ char tarspace; /* Space that target should be evaluated in (only used if 1 target) */ - + char name[64]; /* Constraint name, MAX_NAME */ - + short pad; - + float enforce; /* Amount of influence exherted by constraint (0.0-1.0) */ float headtail; /* Point along subtarget bone where the actual target is. 0=head (default for all), 1=tail*/ - + struct Ipo *ipo DNA_DEPRECATED; /* local influence ipo or driver */ /* old animation system, deprecated for 2.5 */ - + /* below are readonly fields that are set at runtime by the solver for use in the GE (only IK atm) */ float lin_error; /* residual error on constraint expressed in blender unit*/ float rot_error; /* residual error on constraint expressed in radiant */ @@ -87,9 +87,9 @@ typedef struct bConstraintTarget { struct Object *tar; /* object to use as target */ char subtarget[64]; /* subtarget - pchan or vgroup name, MAX_ID_NAME-2 */ - + float matrix[4][4]; /* matrix used during constraint solving - should be cleared before each use */ - + short space; /* space that target should be evaluated in (overrides bConstraint->tarspace) */ short flag; /* runtime settings (for editor, etc.) */ short type; /* type of target (eConstraintObType) */ @@ -111,15 +111,15 @@ typedef enum eConstraintObType { /* Python Script Constraint */ -typedef struct bPythonConstraint { +typedef struct bPythonConstraint { struct Text *text; /* text-buffer (containing script) to execute */ IDProperty *prop; /* 'id-properties' used to store custom properties for constraint */ - + int flag; /* general settings/state indicators accessed by bitmapping */ int tarnum; /* number of targets - usually only 1-3 are needed */ - + ListBase targets; /* a list of targets that this constraint has (bConstraintTarget-s) */ - + struct Object *tar; /* target from previous implementation (version-patch sets this to NULL on file-load) */ char subtarget[64]; /* subtarger from previous implentation (version-patch sets this to "" on file-load), MAX_ID_NAME-2 */ } bPythonConstraint; @@ -155,7 +155,7 @@ typedef enum eConstraint_IK_Type { } eConstraint_IK_Type; -/* Spline IK Constraint +/* Spline IK Constraint * Aligns 'n' bones to the curvature defined by the curve, * with the chain ending on the bone that owns this constraint, * and starting on the nth parent. @@ -163,16 +163,16 @@ typedef enum eConstraint_IK_Type { typedef struct bSplineIKConstraint { /* target(s) */ struct Object *tar; /* curve object (with follow path enabled) which drives the bone chain */ - + /* binding details */ float *points; /* array of numpoints items, denoting parametric positions along curve that joints should follow */ short numpoints; /* number of points to bound in points array */ short chainlen; /* number of bones ('n') that are in the chain */ - + /* settings */ short flag; /* general settings for constraint */ short xzScaleMode; /* method used for determining the x & z scaling of the bones */ - + /* volume preservation settings */ float bulge; float bulge_min; @@ -276,12 +276,12 @@ typedef struct bDampTrackConstraint { /* Follow Path constraints */ typedef struct bFollowPathConstraint { struct Object *tar; /* Must be path object */ - + float offset; /* Offset in time on the path (in frames), when NOT using 'fixed position' */ float offset_fac; /* Parametric offset factor defining position along path, when using 'fixed position' */ - + int followflag; - + short trackflag; short upflag; } bFollowPathConstraint; @@ -290,7 +290,7 @@ typedef struct bFollowPathConstraint { typedef struct bStretchToConstraint { struct Object *tar; int flag; - int volmode; + int volmode; int plane; float orglength; float bulge; @@ -339,11 +339,11 @@ typedef struct bChildOfConstraint { typedef struct bTransformConstraint { struct Object *tar; /* target (i.e. 'driver' object/bone) */ char subtarget[64]; /* MAX_ID_NAME-2 */ - + short from, to; /* can be loc(0), rot(1) or size(2) */ char map[3]; /* defines which target-axis deform is copied by each owner-axis */ char expo; /* extrapolate motion? if 0, confine to ranges */ - + float from_min[3]; /* from_min/max defines range of target transform */ float from_max[3]; /* to map on to to_min/max range. */ float to_min[3]; /* range of motion on owner caused by target */ @@ -368,12 +368,12 @@ typedef struct bPivotConstraint { struct Object *tar; /* target object (optional) */ char subtarget[64]; /* subtarget name (optional), MAX_ID_NAME-2 */ float offset[3]; /* offset from the target to use, regardless of whether it exists */ - + /* Rotation-driven activation: * This option provides easier one-stop setups for footrolls */ short rotAxis; /* rotation axes to consider for this (ePivotConstraint_Axis) */ - + /* General flags */ short flag; /* ePivotConstraint_Flag */ } bPivotConstraint; @@ -410,10 +410,10 @@ typedef struct bSizeLimitConstraint { typedef struct bDistLimitConstraint { struct Object *tar; char subtarget[64]; /* MAX_ID_NAME-2 */ - + float dist; /* distance (radius of clamping sphere) from target */ float soft; /* distance from clamping-sphere to start applying 'fade' */ - + short flag; /* settings */ short mode; /* how to limit in relation to clamping sphere */ int pad; @@ -465,7 +465,7 @@ typedef struct bTransformCacheConstraint { /* ------------------------------------------ */ -/* bConstraint->type +/* bConstraint->type * - Do not ever change the order of these, or else files could get * broken as their correct value cannot be resolved */ @@ -485,7 +485,7 @@ typedef enum eBConstraint_Types { CONSTRAINT_TYPE_ACTION = 12, CONSTRAINT_TYPE_LOCKTRACK = 13, /* New Tracking constraint that locks an axis in place - theeth */ CONSTRAINT_TYPE_DISTLIMIT = 14, /* limit distance */ - CONSTRAINT_TYPE_STRETCHTO = 15, /* claiming this to be mine :) is in tuhopuu bjornmose */ + CONSTRAINT_TYPE_STRETCHTO = 15, /* claiming this to be mine :) is in tuhopuu bjornmose */ CONSTRAINT_TYPE_MINMAX = 16, /* floor constraint */ CONSTRAINT_TYPE_RIGIDBODYJOINT = 17, /* rigidbody constraint */ CONSTRAINT_TYPE_CLAMPTO = 18, /* clampto constraint */ @@ -500,21 +500,21 @@ typedef enum eBConstraint_Types { CONSTRAINT_TYPE_CAMERASOLVER = 27, /* Camera Solver Constraint */ CONSTRAINT_TYPE_OBJECTSOLVER = 28, /* Object Solver Constraint */ CONSTRAINT_TYPE_TRANSFORM_CACHE = 29, /* Transform Cache Constraint */ - + /* NOTE: no constraints are allowed to be added after this */ NUM_CONSTRAINT_TYPES -} eBConstraint_Types; +} eBConstraint_Types; /* bConstraint->flag */ /* flags 0x2 (1<<1) and 0x8 (1<<3) were used in past */ /* flag 0x20 (1<<5) was used to indicate that a constraint was evaluated using a 'local' hack for posebones only */ typedef enum eBConstraint_Flags { /* expand for UI */ - CONSTRAINT_EXPAND = (1<<0), + CONSTRAINT_EXPAND = (1<<0), /* pre-check for illegal object name or bone name */ - CONSTRAINT_DISABLE = (1<<2), + CONSTRAINT_DISABLE = (1<<2), /* to indicate which Ipo should be shown, maybe for 3d access later too */ - CONSTRAINT_ACTIVE = (1<<4), + CONSTRAINT_ACTIVE = (1<<4), /* to indicate that the owner's space should only be changed into ownspace, but not out of it */ CONSTRAINT_SPACEONCE = (1<<6), /* influence ipo is on constraint itself, not in action channel */ @@ -531,8 +531,8 @@ typedef enum eBConstraint_Flags { typedef enum eBConstraint_SpaceTypes { /* default for all - worldspace */ CONSTRAINT_SPACE_WORLD = 0, - /* for objects (relative to parent/without parent influence), - * for bones (along normals of bone, without parent/restpositions) + /* for objects (relative to parent/without parent influence), + * for bones (along normals of bone, without parent/restpositions) */ CONSTRAINT_SPACE_LOCAL = 1, /* for posechannels - pose space */ @@ -575,12 +575,12 @@ typedef enum eCopyLocation_Flags { LOCLIKE_Z_INVERT = (1<<6), LOCLIKE_OFFSET = (1<<7) } eCopyLocation_Flags; - + /* bSizeLikeConstraint.flag */ typedef enum eCopyScale_Flags { SIZELIKE_X = (1<<0), SIZELIKE_Y = (1<<1), - SIZELIKE_Z = (1<<2), + SIZELIKE_Z = (1<<2), SIZELIKE_OFFSET = (1<<3) } eCopyScale_Flags; @@ -601,7 +601,7 @@ typedef enum eSameVolume_Modes { /* bActionConstraint.flag */ typedef enum eActionConstraint_Flags { /* Bones use "object" part of target action, instead of "same bone name" part */ - ACTCON_BONE_USE_OBJECT_ACTION = (1 << 0), + ACTCON_BONE_USE_OBJECT_ACTION = (1 << 0), } eActionConstraint_Flags; /* Locked-Axis Values (Locked Track) */ @@ -703,7 +703,7 @@ typedef enum eSplineIK_Flags { CONSTRAINT_SPLINEIK_EVENSPLITS = (1 << 3), /* don't adjust the x and z scaling of the bones by the curve radius */ CONSTRAINT_SPLINEIK_NO_CURVERAD = (1 << 4), - + /* for "volumetric" xz scale mode, limit the minimum or maximum scale values */ CONSTRAINT_SPLINEIK_USE_BULGE_MIN = (1 << 5), CONSTRAINT_SPLINEIK_USE_BULGE_MAX = (1 << 6), @@ -768,7 +768,7 @@ typedef enum eDistLimit_Modes { LIMITDIST_OUTSIDE = 1, LIMITDIST_ONSURFACE = 2 } eDistLimit_Modes; - + /* python constraint -> flag */ typedef enum ePyConstraint_Flags { PYCON_USETARGETS = (1<<0), @@ -794,14 +794,14 @@ typedef enum eChildOf_Flags { typedef enum ePivotConstraint_Axis { /* do not consider this activity-clamping */ PIVOTCON_AXIS_NONE = -1, - + /* consider -ve x-axis rotations */ PIVOTCON_AXIS_X_NEG = 0, /* consider -ve y-axis rotations */ PIVOTCON_AXIS_Y_NEG = 1, /* consider -ve z-axis rotations */ PIVOTCON_AXIS_Z_NEG = 2, - + /* consider +ve x-axis rotations */ PIVOTCON_AXIS_X = 3, /* consider +ve y-axis rotations */ diff --git a/source/blender/makesdna/DNA_controller_types.h b/source/blender/makesdna/DNA_controller_types.h index 154542d60c58..db0c8078211b 100644 --- a/source/blender/makesdna/DNA_controller_types.h +++ b/source/blender/makesdna/DNA_controller_types.h @@ -55,16 +55,16 @@ typedef struct bController { struct bController *next, *prev, *mynew; short type, flag, inputs, totlinks; short otype, totslinks, pad2, pad3; - + char name[64]; void *data; - + struct bActuator **links; struct bSensor **slinks; short val, valo; unsigned int state_mask; - + } bController; /* controller->type */ diff --git a/source/blender/makesdna/DNA_curve_types.h b/source/blender/makesdna/DNA_curve_types.h index fa40fd298d71..e4db69fb1b6a 100644 --- a/source/blender/makesdna/DNA_curve_types.h +++ b/source/blender/makesdna/DNA_curve_types.h @@ -110,14 +110,14 @@ typedef struct BevList { typedef struct BezTriple { float vec[3][3]; float alfa, weight, radius; /* alfa: tilt in 3D View, weight: used for softbody goal weight, radius: for bevel tapering */ - + char ipo; /* ipo: interpolation mode for segment from this BezTriple to the next */ - + char h1, h2; /* h1, h2: the handle type of the two handles */ char f1, f2, f3; /* f1, f2, f3: used for selection status */ - + char hide; /* hide: used to indicate whether BezTriple is hidden (3D), type of keyframe (eBezTriple_KeyframeType) */ - + char easing; /* easing: easing type for interpolation mode (eBezTriple_Easing) */ float back; /* BEZT_IPO_BACK */ float amplitude, period; /* BEZT_IPO_ELASTIC */ @@ -148,14 +148,14 @@ typedef struct Nurb { short resolu, resolv; /* tessellation resolution in the U or V directions */ short orderu, orderv; short flagu, flagv; - + float *knotsu, *knotsv; BPoint *bp; BezTriple *bezt; short tilt_interp; /* KEY_LINEAR, KEY_CARDINAL, KEY_BSPLINE */ short radius_interp; - + /* only used for dynamically generated Nurbs created from OB_FONT's */ int charidx; } Nurb; @@ -187,19 +187,19 @@ typedef struct EditNurb { typedef struct Curve { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct BoundBox *bb; - + ListBase nurb; /* actual data, called splines in rna */ - + EditNurb *editnurb; /* edited data, not in file, use pointer so we can check for it */ - + struct Object *bevobj, *taperobj, *textoncurve; struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ struct Key *key; struct Material **mat; - + /* texture space, copied as one block in editobject.c */ float loc[3]; float size[3]; @@ -215,7 +215,7 @@ typedef struct Curve { short bevresol, totcol; int flag; float width, ext1, ext2; - + /* default */ short resolu, resolv; short resolu_ren, resolv_ren; @@ -250,10 +250,10 @@ typedef struct Curve { struct VFont *vfontb; struct VFont *vfonti; struct VFont *vfontbi; - + struct TextBox *tb; int totbox, actbox; - + struct CharInfo *strinfo; struct CharInfo curinfo; /* font part end */ @@ -406,7 +406,7 @@ typedef enum eBezTriple_Interpolation { BEZT_IPO_CONST = 0, /* constant interpolation */ BEZT_IPO_LIN = 1, /* linear interpolation */ BEZT_IPO_BEZ = 2, /* bezier interpolation */ - + /* easing equations */ BEZT_IPO_BACK = 3, BEZT_IPO_BOUNCE = 4, @@ -423,7 +423,7 @@ typedef enum eBezTriple_Interpolation { /* easing modes (used only for Keyframes - BezTriple->easing) */ typedef enum eBezTriple_Easing { BEZT_IPO_EASE_AUTO = 0, - + BEZT_IPO_EASE_IN = 1, BEZT_IPO_EASE_OUT = 2, BEZT_IPO_EASE_IN_OUT = 3, @@ -469,4 +469,3 @@ enum { #define SURF_SEEN 4 #endif - diff --git a/source/blender/makesdna/DNA_dynamicpaint_types.h b/source/blender/makesdna/DNA_dynamicpaint_types.h index 17553e98817d..b0afe99a77d4 100644 --- a/source/blender/makesdna/DNA_dynamicpaint_types.h +++ b/source/blender/makesdna/DNA_dynamicpaint_types.h @@ -99,7 +99,7 @@ enum { }; typedef struct DynamicPaintSurface { - + struct DynamicPaintSurface *next, *prev; struct DynamicPaintCanvasSettings *canvas; /* for fast RNA access */ struct PaintSurfaceData *data; diff --git a/source/blender/makesdna/DNA_effect_types.h b/source/blender/makesdna/DNA_effect_types.h index 7ca3bbe3319d..36c46b23c9e4 100644 --- a/source/blender/makesdna/DNA_effect_types.h +++ b/source/blender/makesdna/DNA_effect_types.h @@ -46,7 +46,7 @@ /* emit only from faces*/ #define PAF_OFACE 64 /* show emitter (don't hide actual mesh)*/ -#define PAF_SHOWE 128 +#define PAF_SHOWE 128 /* true random emit from faces (not just ordered jitter)*/ #define PAF_TRAND 256 /* even distribution in face emission based on face areas*/ @@ -78,15 +78,15 @@ typedef struct Effect { struct Effect *next, *prev; short type, flag, buttype, rt; - + } Effect; typedef struct BuildEff { struct BuildEff *next, *prev; short type, flag, buttype, rt; - + float len, sfra; - + } BuildEff; # @@ -102,41 +102,40 @@ struct Group; typedef struct PartEff { struct PartEff *next, *prev; short type, flag, buttype, stype, vertgroup, userjit; - + float sta, end, lifetime; int totpart, totkey, seed; - + float normfac, obfac, randfac, texfac, randlife; float force[3]; float damp; - + float nabla, vectsize, maxlen, pad, defvec[3]; - + float mult[4], life[4]; short child[4], mat[4]; short texmap, curmult; short staticstep, omat, timetex, speedtex, flag2, flag2neg; short disp, vertgroup_v; - + char vgroupname[64], vgroupname_v[64]; /* MAX_VGROUP_NAME */ float imat[4][4]; /* inverse matrix of parent Object */ - + Particle *keys; struct Group *group; - + } PartEff; typedef struct WaveEff { struct WaveEff *next, *prev; short type, flag, buttype, stype; - + float startx, starty, height, width; float narrow, speed, minfac, damp; - + float timeoffs, lifetime; - + } WaveEff; #endif - diff --git a/source/blender/makesdna/DNA_fileglobal_types.h b/source/blender/makesdna/DNA_fileglobal_types.h index 2275f1854ecb..a38c03e52229 100644 --- a/source/blender/makesdna/DNA_fileglobal_types.h +++ b/source/blender/makesdna/DNA_fileglobal_types.h @@ -64,4 +64,3 @@ typedef struct FileGlobal { #endif - diff --git a/source/blender/makesdna/DNA_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h index 1c1190dfc6ad..45f2d6c70e4f 100644 --- a/source/blender/makesdna/DNA_gpencil_types.h +++ b/source/blender/makesdna/DNA_gpencil_types.h @@ -54,7 +54,7 @@ typedef struct bGPDspoint { typedef enum eGPDspoint_Flag { /* stroke point is selected (for editing) */ GP_SPOINT_SELECT = (1 << 0), - + /* stroke point is tagged (for some editing operation) */ GP_SPOINT_TAG = (1 << 1), } eGPSPoint_Flag; @@ -168,7 +168,7 @@ typedef struct bGPDstroke { short flag, pad[2]; /* various settings about this stroke */ double inittime; /* Init time of stroke */ - /* The pointer to color is only used during drawing, but not saved + /* The pointer to color is only used during drawing, but not saved * colorname is the join with the palette, but when draw, the pointer is update if the value is NULL * to speed up the drawing */ @@ -203,11 +203,11 @@ typedef enum eGPDstroke_Flag { */ typedef struct bGPDframe { struct bGPDframe *next, *prev; - + ListBase strokes; /* list of the simplified 'strokes' that make up the frame's data */ - + int framenum; /* frame number of this frame */ - + short flag; /* temp settings */ short key_type; /* keyframe type (eBezTriple_KeyframeType) */ } bGPDframe; @@ -223,30 +223,30 @@ typedef enum eGPDframe_Flag { /* Grease-Pencil Annotations - 'Layer' */ typedef struct bGPDlayer { struct bGPDlayer *next, *prev; - + ListBase frames; /* list of annotations to display for frames (bGPDframe list) */ bGPDframe *actframe; /* active frame (should be the frame that is currently being displayed) */ - + short flag; /* settings for layer */ short thickness; /* current thickness to apply to strokes */ - + short gstep; /* Ghosts Before: max number of ghost frames to show between active frame and the one before it (0 = only the ghost itself) */ short gstep_next; /* Ghosts After: max number of ghost frames to show after active frame and the following it (0 = only the ghost itself) */ - + float gcolor_prev[3]; /* optional color for ghosts before the active frame */ float gcolor_next[3]; /* optional color for ghosts after the active frame */ - + float color[4]; /* Color for strokes in layers (replaced by palettecolor). Only used for ruler (which uses GPencil internally) */ float fill[4]; /* Fill color for strokes in layers. Not used and replaced by palettecolor fill */ - + char info[128]; /* optional reference info about this layer (i.e. "director's comments, 12/3") * this is used for the name of the layer too and kept unique. */ - + struct Object *parent; /* parent object */ float inverse[4][4]; /* inverse matrix (only used if parented) */ char parsubstr[64]; /* String describing subobject info, MAX_ID_NAME-2 */ short partype, pad; - + float tintcolor[4]; /* Color used to tint layer, alpha value is used as factor */ float opacity; /* Opacity of the layer */ } bGPDlayer; @@ -287,13 +287,13 @@ typedef enum eGPDlayer_Flag { typedef struct bGPdata { ID id; /* Grease Pencil data is a datablock */ struct AnimData *adt; /* animation data - for animating draw settings */ - + /* saved Grease-Pencil data */ ListBase layers; /* bGPDlayers */ int flag; /* settings for this datablock */ - /* not-saved stroke buffer data (only used during paint-session) - * - buffer must be initialized before use, but freed after + /* not-saved stroke buffer data (only used during paint-session) + * - buffer must be initialized before use, but freed after * whole paint operation is over */ short sbuffer_size; /* number of elements currently in cache */ @@ -315,29 +315,29 @@ typedef struct bGPdata { typedef enum eGPdata_Flag { /* don't allow painting to occur at all */ /* GP_DATA_LMBPLOCK = (1 << 0), */ - + /* show debugging info in viewport (i.e. status print) */ GP_DATA_DISPINFO = (1 << 1), /* in Action Editor, show as expanded channel */ GP_DATA_EXPAND = (1 << 2), - + /* is the block overriding all clicks? */ /* GP_DATA_EDITPAINT = (1 << 3), */ - + /* ------------------------------------------------ DEPRECATED */ /* new strokes are added in viewport space */ GP_DATA_VIEWALIGN = (1 << 4), - + /* Project into the screen's Z values */ GP_DATA_DEPTH_VIEW = (1 << 5), GP_DATA_DEPTH_STROKE = (1 << 6), GP_DATA_DEPTH_STROKE_ENDPOINTS = (1 << 7), /* ------------------------------------------------ DEPRECATED */ - + /* Stroke Editing Mode - Toggle to enable alternative keymap for easier editing of stroke points */ GP_DATA_STROKE_EDITMODE = (1 << 8), - + /* Convenience/cache flag to make it easier to quickly toggle onion skinning on/off */ GP_DATA_SHOW_ONIONSKINS = (1 << 9), /* Draw a green and red point to indicate start and end of the stroke */ diff --git a/source/blender/makesdna/DNA_group_types.h b/source/blender/makesdna/DNA_group_types.h index 45dd0cb9ff2c..ae565427365f 100644 --- a/source/blender/makesdna/DNA_group_types.h +++ b/source/blender/makesdna/DNA_group_types.h @@ -50,7 +50,7 @@ typedef struct GroupObject { typedef struct Group { ID id; - + ListBase gobject; /* GroupObject */ struct PreviewImage *preview; diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h index b4bc26f45cd0..760e9b5461ee 100644 --- a/source/blender/makesdna/DNA_image_types.h +++ b/source/blender/makesdna/DNA_image_types.h @@ -98,12 +98,12 @@ enum { typedef struct Image { ID id; - + char name[1024]; /* file path, 1024 = FILE_MAX */ - + struct MovieCache *cache; /* not written in file */ struct GPUTexture *gputexture[2]; /* not written in file 2 = TEXTARGET_COUNT */ - + /* sources from: */ ListBase anims; struct RenderResult *rr; @@ -122,7 +122,7 @@ typedef struct Image { unsigned int bindcode[2]; /* only for current image... 2 = TEXTARGET_COUNT */ char pad1[4]; unsigned int *repbind; /* for repeat of parts of images */ - + struct PackedFile *packedfile DNA_DEPRECATED; /* deprecated */ struct ListBase packedfiles; struct PreviewImage *preview; @@ -133,13 +133,13 @@ typedef struct Image { short animspeed; short ok; - + /* for generated images */ int gen_x, gen_y; char gen_type, gen_flag; short gen_depth; float gen_color[4]; - + /* display aspect - for UV editing images resized for faster openGL display */ float aspx, aspy; @@ -188,7 +188,7 @@ enum { #define IMA_TWINANIM 2 #define IMA_COLCYCLE 4 /* Depreciated */ #define IMA_MIPMAP_COMPLETE 8 /* all mipmap levels in OpenGL texture set? */ -#define IMA_CLAMP_U 16 +#define IMA_CLAMP_U 16 #define IMA_CLAMP_V 32 #define IMA_TPAGE_REFRESH 64 #define IMA_GLBIND_IS_DATA 128 /* opengl image texture bound as non-color data */ diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h index 5ba822616ebb..5f6ca2776151 100644 --- a/source/blender/makesdna/DNA_ipo_types.h +++ b/source/blender/makesdna/DNA_ipo_types.h @@ -24,7 +24,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + /** \file DNA_ipo_types.h * \ingroup DNA * \deprecated @@ -32,7 +32,7 @@ * which has (as of 2.50) been replaced with a completely new system by Joshua Leung (aligorith). All defines, * etc. are only still maintained to provide backwards compatibility for old files. */ - + #ifndef __DNA_IPO_TYPES_H__ #define __DNA_IPO_TYPES_H__ @@ -53,7 +53,7 @@ typedef struct IpoDriver { struct Object *ob; /* target/driver ob */ short blocktype, adrcode; /* sub-channel to use */ - + short type, flag; /* driver settings */ char name[128]; /* bone, or python expression here */ } IpoDriver; @@ -63,7 +63,7 @@ typedef struct IpoDriver { /* IPO Curve */ typedef struct IpoCurve { struct IpoCurve *next, *prev; - + struct BPoint *bp; /* array of BPoints (sizeof(BPoint) * totvert) - i.e. baked/imported data */ struct BezTriple *bezt; /* array of BezTriples (sizeof(BezTriple) * totvert) - i.e. user-editable keyframes */ @@ -75,10 +75,10 @@ typedef struct IpoCurve { short flag, rt; /* flag= settings; rt= ??? */ float ymin, ymax; /* minimum/maximum y-extents for curve */ unsigned int bitmask; /* ??? */ - + float slide_min, slide_max; /* minimum/maximum values for sliders (in action editor) */ float curval; /* value of ipo-curve for current frame */ - + IpoDriver *driver; /* pointer to ipo-driver for this curve */ } IpoCurve; @@ -87,10 +87,10 @@ typedef struct IpoCurve { /* IPO Data-Block */ typedef struct Ipo { ID id; - + ListBase curve; /* A list of IpoCurve structs in a linked list. */ rctf cur; /* Rect defining extents of keyframes? */ - + short blocktype, showkey; /* blocktype: self-explanatory; showkey: either 0 or 1 (show vertical yellow lines for editing) */ short muteipo, pad; /* muteipo: either 0 or 1 (whether ipo block is muted) */ } Ipo; @@ -475,7 +475,7 @@ typedef struct Ipo { #define IPO_LIN 1 #define IPO_BEZ 2 /* not used yet */ -#define IPO_MIXED 3 +#define IPO_MIXED 3 /* icu->extrap */ #define IPO_HORIZ 0 @@ -496,7 +496,7 @@ typedef struct Ipo { /* ---------- IPO Drivers ----------- */ /* offset in driver->name for finding second posechannel for rot-diff */ -#define DRIVER_NAME_OFFS 32 +#define DRIVER_NAME_OFFS 32 /* driver->type */ #define IPO_DRIVER_TYPE_NORMAL 0 @@ -507,6 +507,3 @@ typedef struct Ipo { #define IPO_DRIVER_FLAG_INVALID (1<<0) #endif - - - diff --git a/source/blender/makesdna/DNA_key_types.h b/source/blender/makesdna/DNA_key_types.h index 60ab01c901b0..2b097092bc4f 100644 --- a/source/blender/makesdna/DNA_key_types.h +++ b/source/blender/makesdna/DNA_key_types.h @@ -58,7 +58,7 @@ typedef struct KeyBlock { int totelem; /* total number if items in the keyblock (compare with mesh/curve verts to check we match) */ int uid; /* for meshes only, match the unique number with the customdata layer */ - + void *data; /* array of shape key values, size is (Key->elemsize * KeyBlock->totelem) */ char name[64]; /* MAX_NAME (unique name, user assigned) */ char vgroup[64]; /* MAX_VGROUP_NAME (optional vertex group), array gets allocated into 'weights' when set */ @@ -72,7 +72,7 @@ typedef struct KeyBlock { typedef struct Key { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ /* commonly called 'Basis', (Key->type == KEY_RELATIVE) only. * Looks like this is _always_ 'key->block.first', @@ -85,7 +85,7 @@ typedef struct Key { char elemstr[32]; int elemsize; /* size of each element in #KeyBlock.data, use for allocation and stride */ int pad; - + ListBase block; /* list of KeyBlock's */ struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ diff --git a/source/blender/makesdna/DNA_lamp_types.h b/source/blender/makesdna/DNA_lamp_types.h index 733df2ef1cbc..e7eb54cd2e54 100644 --- a/source/blender/makesdna/DNA_lamp_types.h +++ b/source/blender/makesdna/DNA_lamp_types.h @@ -47,33 +47,33 @@ struct MTex; typedef struct Lamp { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + short type, flag; int mode; - + short colormodel, totex; float r, g, b, k; float shdwr, shdwg, shdwb, shdwpad; - + float energy, dist, spotsize, spotblend; float haint; - - + + float att1, att2; /* Quad1 and Quad2 attenuation */ float coeff_const, coeff_lin, coeff_quad, coeff_pad; float cutoff, radius; struct CurveMapping *curfalloff; short falloff_type; short pad2; - + float clipsta, clipend; float bias, slopebias, soft, compressthresh; float bleedbias, pad; float bufsharp; short bufsize, samp, buffers, filtertype; char bufflag, buftype; - + short ray_samp, ray_sampy, ray_sampz; short ray_samp_type; short area_shape; @@ -82,10 +82,10 @@ typedef struct Lamp { short ray_samp_method; short shadowmap_type; short shadow_filter, pad3[3]; - + /* texact is for buttons */ short texact, shadhalostep; - + /* sun/sky */ short sun_effect_type; short skyblendtype; @@ -121,7 +121,7 @@ typedef struct Lamp { /* flag */ #define LA_DS_EXPAND 1 - /* NOTE: this must have the same value as MA_DS_SHOW_TEXS, + /* NOTE: this must have the same value as MA_DS_SHOW_TEXS, * otherwise anim-editors will not read correctly */ #define LA_DS_SHOW_TEXS 4 @@ -223,4 +223,3 @@ typedef struct Lamp { #define LA_SHADMAP_VARIANCE 1 #endif /* __DNA_LAMP_TYPES_H__ */ - diff --git a/source/blender/makesdna/DNA_lattice_types.h b/source/blender/makesdna/DNA_lattice_types.h index 242d6f0feeb4..8fb0d58f1db9 100644 --- a/source/blender/makesdna/DNA_lattice_types.h +++ b/source/blender/makesdna/DNA_lattice_types.h @@ -52,22 +52,22 @@ typedef struct EditLatt { typedef struct Lattice { ID id; struct AnimData *adt; - + short pntsu, pntsv, pntsw, flag; short opntsu, opntsv, opntsw, pad2; char typeu, typev, typew, pad3; int actbp; /* active element index, unset with LT_ACTBP_NONE */ float fu, fv, fw, du, dv, dw; - + struct BPoint *def; - + struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ struct Key *key; - + struct MDeformVert *dvert; char vgroup[64]; /* multiply the influence, MAX_VGROUP_NAME */ - + struct EditLatt *editlatt; } Lattice; @@ -82,4 +82,3 @@ typedef struct Lattice { #define LT_ACTBP_NONE -1 #endif - diff --git a/source/blender/makesdna/DNA_listBase.h b/source/blender/makesdna/DNA_listBase.h index f6035cd66536..ad359efa4d51 100644 --- a/source/blender/makesdna/DNA_listBase.h +++ b/source/blender/makesdna/DNA_listBase.h @@ -67,4 +67,3 @@ typedef struct ListBase { #endif #endif - diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h index 6ace3f63a16f..bf9cae5ddc7e 100644 --- a/source/blender/makesdna/DNA_material_types.h +++ b/source/blender/makesdna/DNA_material_types.h @@ -63,7 +63,7 @@ typedef struct VolumeSettings { float density_scale; float depth_cutoff; float asymmetry; - + short stepsize_type; short shadeflag; short shade_type; @@ -92,8 +92,8 @@ typedef struct TexPaintSlot { typedef struct Material { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + short material_type, flag; /* note, keep this below synced with render_types.h */ float r, g, b; @@ -104,7 +104,7 @@ typedef struct Material { float alpha, ref, spec, zoffs, add; float translucency; /* end synced with render_types.h */ - + struct VolumeSettings vol; struct GameSettings game; @@ -115,7 +115,7 @@ typedef struct Material { short ray_depth, ray_depth_tra; short har; char seed1, seed2; - + float gloss_mir, gloss_tra; short samp_gloss_mir, samp_gloss_tra; float adapt_thresh_mir, adapt_thresh_tra; @@ -123,7 +123,7 @@ typedef struct Material { float dist_mir; short fadeto_mir; short shade_flag; /* like Cubic interpolation */ - + int mode, mode_l; /* mode_l is the or-ed result of all layer modes */ int mode2, mode2_l; /* additional mode flags */ short flarec, starc, linec, ringc; @@ -131,16 +131,16 @@ typedef struct Material { float strand_sta, strand_end, strand_ease, strand_surfnor; float strand_min, strand_widthfade; char strand_uvname[64]; /* MAX_CUSTOMDATA_LAYER_NAME */ - + float sbias; /* shadow bias to prevent terminator prob */ float lbias; /* factor to multiply lampbias with (0.0 = no mult) */ float shad_alpha; /* in use for irregular shadowbuffer */ int septex; - + /* for buttons and render*/ char rgbsel, texact, pr_type, use_nodes; short pr_lamp, pr_texture, ml_flag; /* ml_flag is for disable base material */ - + /* mapping */ char mapflag, pad; @@ -155,7 +155,7 @@ typedef struct Material { /* runtime - OR'd from 'mtex' */ short texco, mapto; - + /* ramp colors */ struct ColorBand *ramp_col; struct ColorBand *ramp_spec; @@ -263,7 +263,7 @@ typedef struct Material { /* for dopesheet */ #define MA_DS_EXPAND 2 /* for dopesheet (texture stack expander) - * NOTE: this must have the same value as other texture stacks, + * NOTE: this must have the same value as other texture stacks, * otherwise anim-editors will not read correctly */ #define MA_DS_SHOW_TEXS 4 @@ -382,8 +382,8 @@ typedef struct Material { #define MA_RAMP_SAT 13 #define MA_RAMP_VAL 14 #define MA_RAMP_COLOR 15 -#define MA_RAMP_SOFT 16 -#define MA_RAMP_LINEAR 17 +#define MA_RAMP_SOFT 16 +#define MA_RAMP_LINEAR 17 /* texco */ #define TEXCO_ORCO 1 @@ -492,4 +492,3 @@ typedef struct Material { #define MA_VOL_SHADE_SHADEDPLUSMULTIPLE 4 #endif - diff --git a/source/blender/makesdna/DNA_mesh_types.h b/source/blender/makesdna/DNA_mesh_types.h index 39e56925903b..a667d0e578d8 100644 --- a/source/blender/makesdna/DNA_mesh_types.h +++ b/source/blender/makesdna/DNA_mesh_types.h @@ -57,7 +57,7 @@ typedef struct Mesh { struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ struct BoundBox *bb; - + struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ struct Key *key; struct Material **mat; @@ -105,7 +105,7 @@ typedef struct Mesh { * this means the active face must always be selected, this is to keep track * of the last selected face and is similar to the old active face flag where * the face does not need to be selected, -1 is inactive */ - int act_face; + int act_face; /* texture space, copied as one block in editobject.c */ float loc[3]; @@ -232,9 +232,6 @@ enum { /* this is so we can save bmesh files that load in trunk, ignoring NGons * will eventually be removed */ -#define USE_BMESH_SAVE_AS_COMPAT -#define USE_BMESH_SAVE_WITHOUT_MFACE - /* enable this so meshes get tessfaces calculated by default */ /* #define USE_TESSFACE_DEFAULT */ diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h index 8bb711339f7f..d1c137492de1 100644 --- a/source/blender/makesdna/DNA_meshdata_types.h +++ b/source/blender/makesdna/DNA_meshdata_types.h @@ -401,7 +401,7 @@ enum { /* SELECT = (1 << 0), */ ME_VERT_TMP_TAG = (1 << 2), ME_HIDE = (1 << 4), - ME_VERT_MERGED = (1 << 6), +/* ME_VERT_MERGED = (1 << 6), */ ME_VERT_PBVH_UPDATE = (1 << 7), }; @@ -437,7 +437,7 @@ enum { enum { ME_SMOOTH = (1 << 0), ME_FACE_SEL = (1 << 1), -/* ME_HIDE = (1 << 4), */ +/* ME_HIDE = (1 << 4), */ }; #define ME_POLY_LOOP_PREV(mloop, mp, i) (&(mloop)[(mp)->loopstart + (((i) + (mp)->totloop - 1) % (mp)->totloop)]) diff --git a/source/blender/makesdna/DNA_meta_types.h b/source/blender/makesdna/DNA_meta_types.h index 68d16700a73b..aa926623e341 100644 --- a/source/blender/makesdna/DNA_meta_types.h +++ b/source/blender/makesdna/DNA_meta_types.h @@ -57,34 +57,34 @@ typedef struct MetaElem { float rad2; /* temp field, used only while processing */ float s; /* stiffness, how much of the element to fill */ float len; /* old, only used for backwards compat. use dimensions now */ - + float *mat, *imat; /* matrix and inverted matrix */ - + } MetaElem; typedef struct MetaBall { ID id; struct AnimData *adt; - + ListBase elems; ListBase disp; ListBase *editelems; /* not saved in files, note we use pointer for editmode check */ struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ /* material of the mother ball will define the material used of all others */ - struct Material **mat; + struct Material **mat; char flag, flag2; /* flag is enum for updates, flag2 is bitflags for settings */ short totcol; short texflag, pad; /* used to store MB_AUTOSPACE */ - + /* texture space, copied as one block in editobject.c */ float loc[3]; float size[3]; float rot[3]; - + float wiresize, rendersize; /* display and render res */ - + /* bias elements to have an offset volume. * mother ball changes will effect other objects thresholds, * but these may also have their own thresh as an offset */ diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h index cfd4a68a8410..00ae9ff8b606 100644 --- a/source/blender/makesdna/DNA_modifier_types.h +++ b/source/blender/makesdna/DNA_modifier_types.h @@ -174,7 +174,7 @@ typedef struct BuildModifierData { float start, length; short flag; - + short randomize; /* (bool) whether order of vertices is randomized - legacy files (for readfile conversion) */ int seed; /* (int) random seed */ } BuildModifierData; @@ -612,7 +612,7 @@ typedef struct ClothModifierData { float hair_grid_max[3]; int hair_grid_res[3]; float hair_grid_cellsize; - + struct ClothSolverResult *solver_result; } ClothModifierData; @@ -960,7 +960,7 @@ typedef struct OceanModifierData { struct Ocean *ocean; struct OceanCache *oceancache; - + int resolution; int spatial_size; @@ -1009,10 +1009,10 @@ enum { enum { MOD_OCEAN_REFRESH_RESET = (1 << 0), - MOD_OCEAN_REFRESH_SIM = (1 << 1), - MOD_OCEAN_REFRESH_ADD = (1 << 2), + /* MOD_OCEAN_REFRESH_SIM = (1 << 1), */ + /* MOD_OCEAN_REFRESH_ADD = (1 << 2), */ MOD_OCEAN_REFRESH_CLEAR_CACHE = (1 << 3), - MOD_OCEAN_REFRESH_TOPOLOGY = (1 << 4), + /* MOD_OCEAN_REFRESH_TOPOLOGY = (1 << 4), */ }; enum { diff --git a/source/blender/makesdna/DNA_nla_types.h b/source/blender/makesdna/DNA_nla_types.h index 16af3bb1be45..72db244c1fec 100644 --- a/source/blender/makesdna/DNA_nla_types.h +++ b/source/blender/makesdna/DNA_nla_types.h @@ -43,11 +43,11 @@ typedef struct bActionModifier { struct bActionModifier *next, *prev; short type, flag; char channel[32]; - + /* noise modifier */ float noisesize, turbul; short channels; - + /* path deform modifier */ short no_rot_axis; struct Object *ob; @@ -74,10 +74,10 @@ typedef struct bActionStrip { float scale; /* The amount the action range is scaled by */ float blendin, blendout; /* The number of frames on either end of the strip's length to fade in/out */ - + char stridechannel[32]; /* Instead of stridelen, it uses an action channel */ char offs_bone[32]; /* if repeat, use this bone/channel for defining offset */ - + ListBase modifiers; /* modifier stack */ } bActionStrip; @@ -102,4 +102,3 @@ typedef enum eActStrip_Flag { } eActStrip_Flag; #endif - diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h index 3cbcc86a6927..5c692cf85da2 100644 --- a/source/blender/makesdna/DNA_node_types.h +++ b/source/blender/makesdna/DNA_node_types.h @@ -85,36 +85,36 @@ typedef struct bNodeStack { typedef struct bNodeSocket { struct bNodeSocket *next, *prev, *new_sock; - + IDProperty *prop; /* user-defined properties */ - + char identifier[64]; /* unique identifier for mapping */ - + char name[64]; /* MAX_NAME */ - + /* XXX deprecated, only used for the Image and OutputFile nodes, * should be removed at some point. */ void *storage; /* custom storage */ - + short type, flag; short limit; /* max. number of links */ short in_out; /* input/output type */ struct bNodeSocketType *typeinfo; /* runtime type information */ char idname[64]; /* runtime type identifier */ - + float locx, locy; - + void *default_value; /* default input value used for unlinked sockets */ - + /* execution data */ short stack_index; /* local stack index */ /* XXX deprecated, kept for forward compatibility */ short stack_type DNA_DEPRECATED; char draw_shape, pad[3]; - + void *cache; /* cached data from execution */ - + /* internal data to retrieve relations and groups * DEPRECATED, now uses the generic identifier string instead */ @@ -123,7 +123,7 @@ typedef struct bNodeSocket { int to_index DNA_DEPRECATED; /* XXX deprecated, still forward compatible since verification restores pointer from matching own_index. */ struct bNodeSocket *groupsock DNA_DEPRECATED; - + struct bNodeLink *link; /* a link pointer, set in ntreeUpdateTree */ /* XXX deprecated, socket input values are stored in default_value now. kept for forward compatibility */ @@ -174,10 +174,10 @@ typedef struct bNode { struct bNode *next, *prev, *new_node; IDProperty *prop; /* user-defined properties */ - + struct bNodeType *typeinfo; /* runtime type information */ char idname[64]; /* runtime type identifier */ - + char name[64]; /* MAX_NAME */ int flag; short type, pad; @@ -186,23 +186,23 @@ typedef struct bNode { short stack_index; /* for groupnode, offset in global caller stack */ short nr; /* number of this node in list, used for UI exec events */ float color[3]; /* custom user-defined color */ - + ListBase inputs, outputs; struct bNode *parent; /* parent node */ struct ID *id; /* optional link to libdata */ void *storage; /* custom data, must be struct, for storage in file */ struct bNode *original; /* the original node in the tree (for localized tree) */ ListBase internal_links; /* list of cached internal links (input to output), for muted nodes and operators */ - + float locx, locy; /* root offset for drawing (parent space) */ float width, height; /* node custom width and height */ float miniwidth; /* node width if hidden */ float offsetx, offsety; /* additional offset from loc */ float anim_init_locx; /* initial locx for insert offset animation */ float anim_ofsx; /* offset that will be added to locx for insert offset animation */ - + int update; /* update flags */ - + char label[64]; /* custom user-defined label, MAX_NAME */ short custom1, custom2; /* to be abused for buttons */ float custom3, custom4; @@ -287,7 +287,7 @@ typedef struct bNodeInstanceKey { */ typedef struct bNodeInstanceHashEntry { bNodeInstanceKey key; - + /* tags for cleaning the cache */ short tag; short pad; @@ -296,7 +296,7 @@ typedef struct bNodeInstanceHashEntry { typedef struct bNodePreview { bNodeInstanceHashEntry hash_entry; /* must be first */ - + unsigned char *rect; short xsize, ysize; int pad; @@ -305,10 +305,10 @@ typedef struct bNodePreview { typedef struct bNodeLink { struct bNodeLink *next, *prev; - + bNode *fromnode, *tonode; bNodeSocket *fromsock, *tosock; - + int flag; int pad; } bNodeLink; @@ -335,41 +335,41 @@ typedef struct bNodeLink { /* only re-usable node trees are in the library though, materials and textures allocate own tree struct */ typedef struct bNodeTree { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct bNodeTreeType *typeinfo; /* runtime type information */ char idname[64]; /* runtime type identifier */ - + struct StructRNA *interface_type; /* runtime RNA type of the group interface */ - + struct bGPdata *gpd; /* grease pencil data */ float view_center[2]; /* node tree stores own offset for consistent editor view */ - + ListBase nodes, links; - + int type, init; /* set init on fileread */ - int cur_index; /* sockets in groups have unique identifiers, adding new sockets always + int cur_index; /* sockets in groups have unique identifiers, adding new sockets always * will increase this counter */ int flag; int update; /* update flags */ short is_updating; /* flag to prevent reentrant update calls */ short done; /* generic temporary flag for recursion check (DFS/BFS) */ int pad2; - + int nodetype DNA_DEPRECATED; /* specific node type this tree is used for */ short edit_quality; /* Quality setting when editing */ short render_quality; /* Quality setting when rendering */ int chunksize; /* tile size for compositor engine */ - + rctf viewer_border; - + /* Lists of bNodeSocket to hold default values and own_index. * Warning! Don't make links to these sockets, input/output nodes are used for that. * These sockets are used only for generating external interfaces. */ ListBase inputs, outputs; - + /* Node preview hash table * Only available in base node trees (e.g. scene->node_tree) */ @@ -379,7 +379,7 @@ typedef struct bNodeTree { */ bNodeInstanceKey active_viewer_key; int pad; - + /* execution data */ /* XXX It would be preferable to completely move this data out of the underlying node tree, * so node tree execution could finally run independent of the tree itself. This would allow node trees @@ -388,7 +388,7 @@ typedef struct bNodeTree { * as long as necessary, even while the tree is being modified. */ struct bNodeTreeExec *execdata; - + /* callbacks */ void (*progress)(void *, float progress); /** \warning may be called by different threads */ @@ -398,7 +398,7 @@ typedef struct bNodeTree { void *tbh, *prh, *sdh, *udh; void *duplilock; - + } bNodeTree; /* ntree->type, index */ @@ -628,7 +628,7 @@ typedef struct NodeImageMultiFileSocket { int pad1; char path[1024]; /* 1024 = FILE_MAX */ ImageFormatData format; - + /* multilayer output */ char layer[30]; /* EXR_TOT_MAXNAME-2 ('.' and channel char are appended) */ char pad2[2]; @@ -700,7 +700,7 @@ typedef struct NodeColorBalance { float power[3]; float offset_basis; char _pad[4]; - + /* LGG parameters */ float lift[3]; float gamma[3]; @@ -778,6 +778,8 @@ typedef struct NodeTexNoise { typedef struct NodeTexVoronoi { NodeTexBase base; int coloring; + int distance; + int feature; int pad; } NodeTexVoronoi; @@ -905,6 +907,14 @@ typedef struct NodeSunBeams { float ray_length; } NodeSunBeams; +typedef struct NodeCryptomatte { + float add[3]; + float remove[3]; + char *matte_id; + int num_inputs; + int pad; +} NodeCryptomatte; + /* script node mode */ #define NODE_SCRIPT_INTERNAL 0 #define NODE_SCRIPT_EXTERNAL 1 @@ -953,6 +963,11 @@ typedef struct NodeSunBeams { #define SHD_HAIR_REFLECTION 0 #define SHD_HAIR_TRANSMISSION 1 +/* principled hair parametrization */ +#define SHD_PRINCIPLED_HAIR_REFLECTANCE 0 +#define SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION 1 +#define SHD_PRINCIPLED_HAIR_DIRECT_ABSORPTION 2 + /* blend texture */ #define SHD_BLEND_LINEAR 0 #define SHD_BLEND_QUADRATIC 1 @@ -976,17 +991,20 @@ typedef struct NodeSunBeams { #define SHD_NOISE_HARD 1 /* voronoi texture */ -#define SHD_VORONOI_DISTANCE_SQUARED 0 -#define SHD_VORONOI_ACTUAL_DISTANCE 1 -#define SHD_VORONOI_MANHATTAN 2 -#define SHD_VORONOI_CHEBYCHEV 3 -#define SHD_VORONOI_MINKOVSKY_H 4 -#define SHD_VORONOI_MINKOVSKY_4 5 -#define SHD_VORONOI_MINKOVSKY 6 +#define SHD_VORONOI_DISTANCE 0 +#define SHD_VORONOI_MANHATTAN 1 +#define SHD_VORONOI_CHEBYCHEV 2 +#define SHD_VORONOI_MINKOWSKI 3 #define SHD_VORONOI_INTENSITY 0 #define SHD_VORONOI_CELLS 1 +#define SHD_VORONOI_F1 0 +#define SHD_VORONOI_F2 1 +#define SHD_VORONOI_F3 2 +#define SHD_VORONOI_F4 3 +#define SHD_VORONOI_F2F1 4 + /* musgrave texture */ #define SHD_MUSGRAVE_MULTIFRACTAL 0 #define SHD_MUSGRAVE_FBM 1 @@ -1073,6 +1091,10 @@ enum { NODE_MATH_MOD = 17, NODE_MATH_ABS = 18, NODE_MATH_ATAN2 = 19, + NODE_MATH_FLOOR = 20, + NODE_MATH_CEIL = 21, + NODE_MATH_FRACT = 22, + NODE_MATH_SQRT = 23, }; /* mix rgb node flags */ diff --git a/source/blender/makesdna/DNA_object_fluidsim_types.h b/source/blender/makesdna/DNA_object_fluidsim_types.h index b305235083a6..0b0c1c40ef44 100644 --- a/source/blender/makesdna/DNA_object_fluidsim_types.h +++ b/source/blender/makesdna/DNA_object_fluidsim_types.h @@ -38,14 +38,14 @@ #ifdef __cplusplus extern "C" { #endif - + struct Mesh; struct Ipo; typedef struct FluidVertexVelocity { float vel[3]; } FluidVertexVelocity; - + typedef struct FluidsimSettings { struct FluidsimModifierData *fmd; /* for fast RNA access */ /* threadcont the calculation is done with */ @@ -83,7 +83,7 @@ typedef struct FluidsimSettings { float gstar; /* activate refinement? */ int maxRefine; - + /* fluid object type settings */ /* gravity strength */ float iniVelx, iniVely, iniVelz; @@ -127,19 +127,19 @@ typedef struct FluidsimSettings { struct FluidVertexVelocity *meshVelocities; /* number of vertices in simulated fluid mesh */ int totvert; - + /* Fluid control settings */ float cpsTimeStart; float cpsTimeEnd; float cpsQuality; - + float attractforceStrength; float attractforceRadius; float velocityforceStrength; float velocityforceRadius; int lastgoodframe; - + /* Simulation/flow rate control (i.e. old "Fac-Time") */ float animRate; } FluidsimSettings; @@ -190,4 +190,3 @@ typedef struct FluidsimSettings { #endif #endif /* __DNA_OBJECT_FLUIDSIM_TYPES_H__ */ - diff --git a/source/blender/makesdna/DNA_object_force_types.h b/source/blender/makesdna/DNA_object_force_types.h index 55f192727e12..117a5a3272d7 100644 --- a/source/blender/makesdna/DNA_object_force_types.h +++ b/source/blender/makesdna/DNA_object_force_types.h @@ -67,7 +67,7 @@ typedef struct PartDeflect { short tex_mode; /* texture effector */ short kink, kink_axis; /* for curve guide */ short zdir; - + /* Main effector values */ float f_strength; /* The strength of the force (+ or - ) */ float f_damp; /* Damping ratio of the harmonic effector. */ @@ -93,7 +93,7 @@ typedef struct PartDeflect { float pdef_stickness;/* surface particle stickiness */ float absorption; /* used for forces */ - + /* softbody collisions */ float pdef_sbdamp; /* Damping factor for softbody deflection */ float pdef_sbift; /* inner face thickness for softbody deflection */ @@ -117,7 +117,7 @@ typedef struct PartDeflect { typedef struct EffectorWeights { struct Group *group; /* only use effectors from this group of objects */ - + float weight[14]; /* effector type specific weights */ float global_gravity; short flag, rt[3]; @@ -170,7 +170,7 @@ typedef struct PTCacheMem { typedef struct PointCache { struct PointCache *next, *prev; int flag; /* generic flag */ - + int step; /* The number of frames between cached frames. * This should probably be an upper bound for a per point adaptive step in the future, * buf for now it's the same for all points. Without adaptivity this can effect the perceived @@ -195,7 +195,7 @@ typedef struct PointCache { int totpoint; /* number of cached points */ int index; /* modifier stack index */ short compression, rt; - + char name[64]; char prev_name[64]; char info[64]; @@ -274,9 +274,9 @@ typedef struct SoftBody { char pad; char msg_lock; short msg_value; - + /* part of UI: */ - + /* general options */ float nodemass; /* softbody mass of *vertex* */ char namedVG_Mass[64]; /* MAX_VGROUP_NAME */ @@ -287,7 +287,7 @@ typedef struct SoftBody { float mediafrict; /* friction to env */ float rklimit; /* error limit for ODE solver */ float physics_speed;/* user control over simulation speed */ - + /* goal */ float goalspring; /* softbody goal springs */ float goalfrict; /* softbody goal springs friction */ @@ -300,7 +300,7 @@ typedef struct SoftBody { * rather find them by name tag to find it -> jow20090613 */ short fuzzyness; /* */ - + /* springs */ float inspring; /* softbody inner springs */ float infrict; /* softbody inner springs friction */ @@ -308,12 +308,12 @@ typedef struct SoftBody { /* along with it introduce Spring_K painting * starting to fix old bug .. nastiness that VG are indexes * rather find them by name tag to find it -> jow20090613 */ - + /* baking */ int sfra, efra; int interval; short local, solverflags; /* local==1: use local coords for baking */ - + /* -- these must be kept for backwards compatibility -- */ SBVertex **keys; /* array of size totpointkey */ int totpointkey, totkey; /* if totpointkey != totpoint or totkey!- (efra-sfra)/interval -> free keys */ @@ -343,7 +343,7 @@ typedef struct SoftBody { struct Group *collision_group; struct EffectorWeights *effector_weights; - /* reverse esimated obmatrix .. no need to store in blend file .. how ever who cares */ + /* reverse esimated obmatrix .. no need to store in blend file .. how ever who cares */ float lcom[3]; float lrot[3][3]; float lscale[3][3]; @@ -439,9 +439,9 @@ typedef struct SoftBody { #define OB_SB_AERO_ANGLE 16384 /* sb->solverflags */ -#define SBSO_MONITOR 1 -#define SBSO_OLDERR 2 -#define SBSO_ESTIMATEIPO 4 +#define SBSO_MONITOR 1 +#define SBSO_OLDERR 2 +#define SBSO_ESTIMATEIPO 4 /* sb->sbc_mode */ #define SBC_MODE_MANUAL 0 @@ -455,4 +455,3 @@ typedef struct SoftBody { #endif #endif /* __DNA_OBJECT_FORCE_TYPES_H__ */ - diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h index d07845f4ffae..290659fe7f9e 100644 --- a/source/blender/makesdna/DNA_object_types.h +++ b/source/blender/makesdna/DNA_object_types.h @@ -131,10 +131,10 @@ enum { typedef struct Object { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ struct SculptSession *sculpt; - + short type, partype; int par1, par2, par3; /* can be vertexnrs */ char parsubstr[64]; /* String describing subobject info, MAX_ID_NAME-2 */ @@ -149,13 +149,13 @@ typedef struct Object { struct bAction *poselib; struct bPose *pose; /* pose data, armature objects only */ void *data; /* pointer to objects data - an 'ID' or NULL */ - + struct bGPdata *gpd; /* Grease Pencil data */ - + bAnimVizSettings avs; /* settings for visualization of object-transform animation */ bMotionPath *mpath; /* motion path cache for this object */ void *pad1; - + ListBase constraintChannels DNA_DEPRECATED; // XXX deprecated... old animation system ListBase effect DNA_DEPRECATED; // XXX deprecated... keep for readfile ListBase defbase; /* list of bDeformGroup (vertex groups) names and flag only */ @@ -169,7 +169,7 @@ typedef struct Object { char *matbits; /* a boolean field, with each byte 1 if corresponding material is linked to object */ int totcol; /* copy of mesh, curve & meta struct member of same name (keep in sync) */ int actcol; /* currently selected material in the UI */ - + /* rot en drot have to be together! (transform('r' en 's')) */ float loc[3], dloc[3], orig[3]; float size[3]; /* scale in fact */ @@ -186,18 +186,18 @@ typedef struct Object { /* note: this isn't assured to be valid as with 'obmat', * before using this value you should do... * invert_m4_m4(ob->imat, ob->obmat); */ - + /* Previously 'imat' was used at render time, but as other places use it too * the interactive ui of 2.5 creates problems. So now only 'imat_ren' should * be used when ever the inverse of ob->obmat * re->viewmat is needed! - jahka */ float imat_ren[4][4]; - + unsigned int lay; /* copy of Base's layer in the scene */ short flag; /* copy of Base */ short colbits DNA_DEPRECATED; /* deprecated, use 'matbits' */ - + short transflag, protectflag; /* transformation settings and transform locks */ short trackflag, upflag; short nlaflag; /* used for DopeSheet filtering settings (expanded/collapsed) */ @@ -215,7 +215,7 @@ typedef struct Object { /* during realtime */ /* note that inertia is only called inertia for historical reasons - * and is not changed to avoid DNA surgery. It actually reflects the + * and is not changed to avoid DNA surgery. It actually reflects the * Size value in the GameButtons (= radius) */ float mass, damping, inertia; @@ -235,7 +235,7 @@ typedef struct Object { float max_angvel; /* clamp the maximum angular velocity, 0.0 is disabled */ float min_angvel; /* clamp the minimum angular velocity, 0.0 is disabled */ float obstacleRad; - + /* "Character" physics properties */ float step_height; float jump_speed; @@ -258,7 +258,7 @@ typedef struct Object { char empty_drawtype; float empty_drawsize; float dupfacesca; /* dupliface scale */ - + ListBase prop; /* game logic property list (not to be confused with IDProperties) */ ListBase sensors; /* game logic sensors */ ListBase controllers; /* game logic controllers */ @@ -290,7 +290,7 @@ typedef struct Object { ListBase nlastrips DNA_DEPRECATED; // XXX deprecated... old animation system ListBase hooks DNA_DEPRECATED; // XXX deprecated... old animation system ListBase particlesystem; /* particle systems */ - + struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */ struct PartDeflect *pd; /* particle deflector/attractor/collision data */ struct SoftBody *soft; /* if exists, saved in file */ @@ -315,7 +315,7 @@ typedef struct Object { ListBase gpulamp; /* runtime, for glsl lamp display only */ ListBase pc_ids; ListBase *duplilist; /* for temporary dupli list storage, only for use by RNA API */ - + struct RigidBodyOb *rigidbody_object; /* settings for Bullet rigid body */ struct RigidBodyCon *rigidbody_constraint; /* settings for Bullet constraint */ @@ -335,13 +335,13 @@ typedef struct Object { /* Warning, this is not used anymore because hooks are now modifiers */ typedef struct ObHook { struct ObHook *next, *prev; - + struct Object *parent; float parentinv[4][4]; /* matrix making current transform unmodified */ float mat[4][4]; /* temp matrix while hooking */ float cent[3]; /* visualization of hook */ float falloff; /* if not zero, falloff is distance where influence zero */ - + char name[64]; /* MAX_NAME */ int *indexar; @@ -706,7 +706,7 @@ enum { OB_LOCK_ROTW = 1 << 9, OB_LOCK_ROT4D = 1 << 10, }; - + #define MAX_DUPLI_RECUR 8 #ifdef __cplusplus @@ -714,4 +714,3 @@ enum { #endif #endif - diff --git a/source/blender/makesdna/DNA_outliner_types.h b/source/blender/makesdna/DNA_outliner_types.h index 984e3334414b..ed78e302022d 100644 --- a/source/blender/makesdna/DNA_outliner_types.h +++ b/source/blender/makesdna/DNA_outliner_types.h @@ -107,4 +107,3 @@ typedef struct TreeStore { #endif - diff --git a/source/blender/makesdna/DNA_packedFile_types.h b/source/blender/makesdna/DNA_packedFile_types.h index 00a54c2db7f8..d2e0dd92cbc7 100644 --- a/source/blender/makesdna/DNA_packedFile_types.h +++ b/source/blender/makesdna/DNA_packedFile_types.h @@ -57,5 +57,3 @@ enum ePF_FileStatus { }; #endif /* PACKEDFILE_TYPES_H */ - - diff --git a/source/blender/makesdna/DNA_particle_types.h b/source/blender/makesdna/DNA_particle_types.h index 9dbd1a18703f..f1c22a884f12 100644 --- a/source/blender/makesdna/DNA_particle_types.h +++ b/source/blender/makesdna/DNA_particle_types.h @@ -97,7 +97,7 @@ typedef struct ParticleData { ParticleKey state; /* current global coordinates */ ParticleKey prev_state; /* previous state */ - + HairKey *hair; /* hair vertices */ ParticleKey *keys; /* keyed keys */ @@ -297,7 +297,7 @@ typedef struct ParticleSystem { struct ListBase targets; /* used for keyed and boid physics */ char name[64]; /* particle system name, MAX_NAME */ - + float imat[4][4]; /* used for duplicators */ float cfra, tree_frame, bvhtree_frame; int seed, child_seed; @@ -375,7 +375,7 @@ typedef enum eParticleDrawFlag { #define PART_UNBORN 32 /*show unborn particles*/ #define PART_DIED 64 /*show died particles*/ -#define PART_TRAND 128 +#define PART_TRAND 128 #define PART_EDISTR 256 /* particle/face from face areas */ #define PART_ROTATIONS 512 /* calculate particle rotations (and store them in pointcache) */ @@ -410,7 +410,7 @@ typedef enum eParticleDrawFlag { #define PART_FROM_VERT 0 #define PART_FROM_FACE 1 #define PART_FROM_VOLUME 2 -/* #define PART_FROM_PARTICLE 3 deprecated! */ +/* #define PART_FROM_PARTICLE 3 deprecated! */ #define PART_FROM_CHILD 4 /* part->distr */ diff --git a/source/blender/makesdna/DNA_property_types.h b/source/blender/makesdna/DNA_property_types.h index 77cd7c3e1022..82568e93f54d 100644 --- a/source/blender/makesdna/DNA_property_types.h +++ b/source/blender/makesdna/DNA_property_types.h @@ -46,7 +46,7 @@ typedef struct bProperty { short type, flag; int data; /* data should be 4 bytes to store int,float stuff */ void *poin; /* references data unless its a string which is malloc'd */ - + } bProperty; /* property->type XXX Game Property, not RNA */ diff --git a/source/blender/makesdna/DNA_rigidbody_types.h b/source/blender/makesdna/DNA_rigidbody_types.h index 381ee5d40e55..19e49644816d 100644 --- a/source/blender/makesdna/DNA_rigidbody_types.h +++ b/source/blender/makesdna/DNA_rigidbody_types.h @@ -52,23 +52,23 @@ typedef struct RigidBodyWorld { struct Group *group; /* Group containing objects to use for Rigid Bodies */ struct Object **objects; /* Array to access group objects by index, only used at runtime */ - + struct Group *constraints; /* Group containing objects to use for Rigid Body Constraints*/ int pad; float ltime; /* last frame world was evaluated for (internal) */ - + /* cache */ struct PointCache *pointcache; struct ListBase ptcaches; int numbodies; /* number of objects in rigid body group */ - + short steps_per_second; /* number of simulation steps thaken per second */ short num_solver_iterations;/* number of constraint solver iterations made per simulation step */ - + int flag; /* (eRigidBodyWorld_Flag) settings for this RigidBodyWorld */ float time_scale; /* used to speed up or slow down the simulation */ - + /* References to Physics Sim objects. Exist at runtime only ---------------------- */ void *physics_world; /* Physics sim world (i.e. btDiscreteDynamicsWorld) */ } RigidBodyWorld; @@ -96,30 +96,30 @@ typedef struct RigidBodyOb { /* References to Physics Sim objects. Exist at runtime only */ void *physics_object; /* Physics object representation (i.e. btRigidBody) */ void *physics_shape; /* Collision shape used by physics sim (i.e. btCollisionShape) */ - + /* General Settings for this RigidBodyOb */ short type; /* (eRigidBodyOb_Type) role of RigidBody in sim */ - short shape; /* (eRigidBody_Shape) collision shape to use */ - + short shape; /* (eRigidBody_Shape) collision shape to use */ + int flag; /* (eRigidBodyOb_Flag) */ int col_groups; /* Collision groups that determines wich rigid bodies can collide with each other */ short mesh_source; /* (eRigidBody_MeshSource) mesh source for mesh based collision shapes */ short pad; - + /* Physics Parameters */ float mass; /* how much object 'weighs' (i.e. absolute 'amount of stuff' it holds) */ - + float friction; /* resistance of object to movement */ float restitution; /* how 'bouncy' object is when it collides */ - - float margin; /* tolerance for detecting collisions */ - + + float margin; /* tolerance for detecting collisions */ + float lin_damping; /* damping for linear velocities */ float ang_damping; /* damping for angular velocities */ - + float lin_sleep_thresh; /* deactivation threshold for linear velocities */ float ang_sleep_thresh; /* deactivation threshold for angular velocities */ - + float orn[4]; /* rigid body orientation */ float pos[3]; /* rigid body position */ float pad1; @@ -166,12 +166,12 @@ typedef enum eRigidBody_Shape { RB_SHAPE_CYLINDER, /* cone (i.e. party hat) */ RB_SHAPE_CONE, - + /* convex hull (minimal shrinkwrap encompassing all verts) */ RB_SHAPE_CONVEXH, /* triangulated mesh */ RB_SHAPE_TRIMESH, - + /* concave mesh approximated using primitives */ //RB_SHAPE_COMPOUND, } eRigidBody_Shape; @@ -203,7 +203,8 @@ typedef struct RigidBodyCon { int flag; /* (eRigidBodyCon_Flag) */ float breaking_threshold; /* breaking impulse threshold */ - float pad; + char spring_type; /* spring implementation to use */ + char pad[3]; /* limits */ /* translation limits */ @@ -273,9 +274,15 @@ typedef enum eRigidBodyCon_Type { /* Simplified spring constraint with only once axis that's automatically placed between the connected bodies */ RBC_TYPE_SPRING, /* dirves bodies by applying linear and angular forces */ - RBC_TYPE_MOTOR + RBC_TYPE_MOTOR, } eRigidBodyCon_Type; +/* Spring implementation type for RigidBodyOb */ +typedef enum eRigidBodyCon_SpringType { + RBC_SPRING_TYPE1 = 0, /* btGeneric6DofSpringConstraint */ + RBC_SPRING_TYPE2, /* btGeneric6DofSpring2Constraint */ +} eRigidBodyCon_SpringType; + /* Flags for RigidBodyCon */ typedef enum eRigidBodyCon_Flag { /* constraint influences rigid body motion */ @@ -311,4 +318,3 @@ typedef enum eRigidBodyCon_Flag { /* ******************************** */ #endif /* __DNA_RIGIDBODY_TYPES_H__ */ - diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h index 963ba7b80665..32747d34a86f 100644 --- a/source/blender/makesdna/DNA_scene_types.h +++ b/source/blender/makesdna/DNA_scene_types.h @@ -188,12 +188,12 @@ typedef struct AudioData { /* Render Layer */ typedef struct SceneRenderLayer { struct SceneRenderLayer *next, *prev; - + char name[64]; /* MAX_NAME */ - + struct Material *mat_override; struct Group *light_override; - + unsigned int lay; /* Scene.lay itself has priority over this */ unsigned int lay_zmask; /* has to be after lay, this is for Z-masking */ unsigned int lay_exclude; /* not used by internal, exclude */ @@ -560,7 +560,7 @@ typedef enum eBakePassFilter { typedef struct RenderData { struct ImageFormatData im_format; - + struct AviCodecData *avicodecdata; struct FFMpegCodecData ffcodecdata; @@ -587,13 +587,13 @@ typedef struct RenderData { int frame_step; /* frames to jump during render/playback */ short stereomode DNA_DEPRECATED; /* standalone player stereo settings */ // XXX deprecated since 2.5 - + short dimensionspreset; /* for the dimensions presets menu */ short filtertype; /* filter is box, tent, gauss, mitch, etc */ short size; /* size in % */ - + short maximsize DNA_DEPRECATED; /* max in Kb */ short pad6; @@ -623,7 +623,7 @@ typedef struct RenderData { int tilex, tiley; short planes DNA_DEPRECATED, imtype DNA_DEPRECATED, subimtype DNA_DEPRECATED, quality DNA_DEPRECATED; /*deprecated!*/ - + /** * Render to image editor, fullscreen or to new window. */ @@ -645,7 +645,7 @@ typedef struct RenderData { * Flags for raytrace settings. Use bit-masking to access the settings. */ int raytrace_options; - + /** * Raytrace acceleration structure */ @@ -656,7 +656,7 @@ typedef struct RenderData { /* octree resolution */ short ocres; short pad4; - + /** * What to do with the sky/background. Picks sky/premul/key * blending for the background @@ -670,39 +670,39 @@ typedef struct RenderData { short frs_sec, edgeint; - + /* safety, border and display rect */ rctf safety, border; rcti disprect; - + /* information on different layers to be rendered */ ListBase layers; short actlay; - + /* number of mblur samples */ short mblur_samples; - + /** * Adjustment factors for the aspect ratio in the x direction, was a short in 2.45 */ float xasp, yasp; float frs_sec_base; - + /** * Value used to define filter size for all filter options */ float gauss; - - + + /* color management settings - color profiles, gamma correction, etc */ int color_mgt_flag; - + /** post-production settings. deprecated, but here for upwards compat (initialized to 1) */ float postgamma, posthue, postsat; - + /* Dither noise intensity */ float dither_intensity; - + /* Bake Render options */ short bake_osa, bake_filter, bake_mode, bake_flag; short bake_normal_space, bake_quad_split; @@ -742,7 +742,7 @@ typedef struct RenderData { /* cineon */ short cineonwhite DNA_DEPRECATED, cineonblack DNA_DEPRECATED; /*deprecated*/ float cineongamma DNA_DEPRECATED; /*deprecated*/ - + /* jpeg2000 */ short jp2_preset DNA_DEPRECATED, jp2_depth DNA_DEPRECATED; /*deprecated*/ int rpad3; @@ -782,14 +782,14 @@ typedef struct RenderData { typedef struct RenderProfile { struct RenderProfile *next, *prev; char name[32]; - + short particle_perc; short subsurf_max; short shadbufsample_max; short pad1; - + float ao_error, pad2; - + } RenderProfile; /* *************************************************************** */ @@ -1020,7 +1020,7 @@ typedef struct Paint { /* Paint stroke can use up to PAINT_MAX_INPUT_SAMPLES inputs to * smooth the stroke */ int num_input_samples; - + /* flags used for symmetry */ int symmetry_flags; @@ -1036,7 +1036,7 @@ typedef struct ImagePaintSettings { Paint paint; short flag, missing_data; - + /* for projection painting only */ short seam_bleed, normal_angle; short screen_grab_size[2]; /* capture size for re-projection */ @@ -1179,10 +1179,10 @@ typedef enum eGP_EditBrush_Flag { GP_EDITBRUSH_FLAG_INVERT = (1 << 0), /* adjust strength using pen pressure */ GP_EDITBRUSH_FLAG_USE_PRESSURE = (1 << 1), - + /* strength of brush falls off with distance from cursor */ GP_EDITBRUSH_FLAG_USE_FALLOFF = (1 << 2), - + /* smooth brush affects pressure values as well */ GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE = (1 << 3) } eGP_EditBrush_Flag; @@ -1193,7 +1193,7 @@ typedef enum eGP_EditBrush_Flag { typedef struct GP_BrushEdit_Settings { GP_EditBrush_Data brush[11]; /* TOT_GP_EDITBRUSH_TYPES */ void *paintcursor; /* runtime */ - + int brushtype; /* eGP_EditBrush_Types */ int flag; /* eGP_BrushEdit_SettingsFlag */ int lock_axis; /* eGP_Lockaxis_Types lock drawing to one axis */ @@ -1216,13 +1216,13 @@ typedef enum eGP_BrushEdit_SettingsFlag { /* Settings for GP Interpolation Operators */ typedef struct GP_Interpolate_Settings { short flag; /* eGP_Interpolate_SettingsFlag */ - - char type; /* eGP_Interpolate_Type - Interpolation Mode */ + + char type; /* eGP_Interpolate_Type - Interpolation Mode */ char easing; /* eBezTriple_Easing - Easing mode (if easing equation used) */ - + float back; /* BEZT_IPO_BACK */ float amplitude, period; /* BEZT_IPO_ELASTIC */ - + struct CurveMapping *custom_ipo; /* custom interpolation curve (for use with GP_IPO_CURVEMAP) */ } GP_Interpolate_Settings; @@ -1238,10 +1238,10 @@ typedef enum eGP_Interpolate_SettingsFlag { typedef enum eGP_Interpolate_Type { /* Traditional Linear Interpolation */ GP_IPO_LINEAR = 0, - + /* CurveMap Defined Interpolation */ GP_IPO_CURVEMAP = 1, - + /* Easing Equations */ GP_IPO_BACK = 3, GP_IPO_BOUNCE = 4, @@ -1299,11 +1299,11 @@ typedef struct UnifiedPaintSettings { /* record movement of mouse so that rake can start at an intuitive angle */ float last_rake[2]; float last_rake_angle; - + int last_stroke_valid; float average_stroke_accum[3]; int average_stroke_counter; - + float brush_rotation; float brush_rotation_sec; @@ -1439,7 +1439,7 @@ typedef struct ToolSettings { VPaint *wpaint; /* weight paint */ Sculpt *sculpt; UvSculpt *uvsculpt; /* uv smooth */ - + /* Vertex group weight - used only for editmode, not weight * paint */ float vgroup_weight; @@ -1470,22 +1470,22 @@ typedef struct ToolSettings { char gpencil_v2d_align; /* : General 2D Editor */ char gpencil_seq_align; /* : Sequencer Preview */ char gpencil_ima_align; /* : Image Editor */ - + /* Grease Pencil Sculpt */ struct GP_BrushEdit_Settings gp_sculpt; - + /* Grease Pencil Interpolation Tool(s) */ struct GP_Interpolate_Settings gp_interpolate; - + /* Grease Pencil Drawing Brushes (bGPDbrush) */ - ListBase gp_brushes; + ListBase gp_brushes; /* Image Paint (8 byttse aligned please!) */ struct ImagePaintSettings imapaint; /* Particle Editing */ struct ParticleEditSettings particle; - + /* Transform Proportional Area of Effect */ float proportional_size; @@ -1526,7 +1526,7 @@ typedef struct ToolSettings { char skgen_retarget_roll; char skgen_side_string[8]; char skgen_num_string[8]; - + /* Alt+RMB option */ char edge_mode; char edge_mode_live_unwrap; @@ -1619,33 +1619,33 @@ typedef struct DisplaySafeAreas { typedef struct Scene { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct Object *camera; struct World *world; - + struct Scene *set; - + ListBase base; struct Base *basact; /* active base */ struct Object *obedit; /* name replaces old G.obedit */ - + float cursor[3]; /* 3d cursor location */ char _pad[4]; - + unsigned int lay; /* bitflags for layer visibility */ int layact; /* active layer */ unsigned int lay_updated; /* runtime flag, has layer ever been updated since load? */ - + short flag; /* various settings */ - + char use_nodes; char pad[1]; - + struct bNodeTree *nodetree; - + struct Editing *ed; /* sequence editor data is allocated here */ - + struct ToolSettings *toolsettings; /* default allocated now */ struct SceneStats *stats; /* default allocated now */ struct DisplaySafeAreas safe_areas; @@ -1654,17 +1654,17 @@ typedef struct Scene { /* no, is on the right place (ton) */ struct RenderData r; struct AudioData audio; - + ListBase markers; ListBase transform_spaces; - + void *sound_scene; void *playback_handle; void *sound_scrub_handle; void *speaker_handles; - + void *fps_info; /* (runtime) info/cache used for presenting playback framerate info to the user */ - + /* none of the dependency graph vars is mean to be saved */ struct Depsgraph *depsgraph; void *pad1; @@ -1675,14 +1675,14 @@ typedef struct Scene { /* User-Defined KeyingSets */ int active_keyingset; /* index of the active KeyingSet. first KeyingSet has index 1, 'none' active is 0, 'add new' is -1 */ ListBase keyingsets; /* KeyingSets for this scene */ - + /* Game Settings */ struct GameFraming framing DNA_DEPRECATED; // XXX deprecated since 2.5 struct GameData gm; /* Units */ struct UnitSettings unit; - + /* Grease Pencil */ struct bGPdata *gpd; @@ -1699,7 +1699,7 @@ typedef struct Scene { ColorManagedViewSettings view_settings; ColorManagedDisplaySettings display_settings; ColorManagedColorspaceSettings sequencer_colorspace_settings; - + /* RigidBody simulation world+settings */ struct RigidBodyWorld *rigidbody_world; @@ -1741,7 +1741,7 @@ typedef struct Scene { /* threads obsolete... is there for old files, now use for autodetect threads */ #define R_THREADS 0x80000 /* Use the same flag for autothreads */ -#define R_FIXED_THREADS 0x80000 +#define R_FIXED_THREADS 0x80000 #define R_SPEED 0x100000 #define R_SSS 0x200000 @@ -2205,14 +2205,14 @@ typedef enum eGPencil_Source_3D { typedef enum eGPencil_Placement_Flags { /* New strokes are added in viewport/data space (i.e. not screen space) */ GP_PROJECT_VIEWSPACE = (1 << 0), - + /* Viewport space, but relative to render canvas (Sequencer Preview Only) */ GP_PROJECT_CANVAS = (1 << 1), - + /* Project into the screen's Z values */ GP_PROJECT_DEPTH_VIEW = (1 << 2), GP_PROJECT_DEPTH_STROKE = (1 << 3), - + /* "Use Endpoints" */ GP_PROJECT_DEPTH_STROKE_ENDPOINTS = (1 << 4), } eGPencil_Placement_Flags; diff --git a/source/blender/makesdna/DNA_screen_types.h b/source/blender/makesdna/DNA_screen_types.h index a9767f506dc7..bdcbf9cb856f 100644 --- a/source/blender/makesdna/DNA_screen_types.h +++ b/source/blender/makesdna/DNA_screen_types.h @@ -48,7 +48,7 @@ struct wmTooltipState; typedef struct bScreen { ID id; - + ListBase vertbase; /* screens have vertices/edges to define areas */ ListBase edgebase; ListBase areabase; @@ -71,7 +71,7 @@ typedef struct bScreen { char skip_handling; /* set to delay screen handling after switching back from maximized area */ char scrubbing; /* set when scrubbing to avoid some costly updates */ char pad[6]; - + short mainwin; /* screensize subwindow, for screenedges and global menus */ short subwinactive; /* active subwindow */ @@ -204,7 +204,7 @@ typedef struct uiPreview { /* some preview UI data need to be saved in typedef struct ScrArea { struct ScrArea *next, *prev; - + ScrVert *v1, *v2, *v3, *v4; /* ordered (bl, tl, tr, br) */ bScreen *full; /* if area==full, this is the parent */ @@ -212,14 +212,14 @@ typedef struct ScrArea { char spacetype, butspacetype; /* SPACE_..., butspacetype is button arg */ short winx, winy; /* size */ - + short headertype; /* OLD! 0=no header, 1= down, 2= up */ short do_refresh; /* private, for spacetype refresh callback */ short flag; short region_active_win; /* index of last used region of 'RGN_TYPE_WINDOW' * runtime variable, updated by executing operators */ char temp, pad; - + struct SpaceType *type; /* callbacks for this space type */ /* A list of space links (editors) that were open in this area before. When @@ -238,29 +238,29 @@ typedef struct ScrArea { typedef struct ARegion { struct ARegion *next, *prev; - + View2D v2d; /* 2D-View scrolling/zoom info (most regions are 2d anyways) */ rcti winrct; /* coordinates of region */ rcti drawrct; /* runtime for partial redraw, same or smaller than winrct */ short winx, winy; /* size */ - + short swinid; short regiontype; /* window, header, etc. identifier for drawing */ short alignment; /* how it should split */ short flag; /* hide, ... */ - + float fsize; /* current split size in float (unused) */ short sizex, sizey; /* current split size in pixels (if zero it uses regiontype) */ - + short do_draw; /* private, cached notifier events */ short do_draw_overlay; /* private, cached notifier events */ short swap; /* private, indicator to survive swap-exchange */ short overlap; /* private, set for indicate drawing overlapped */ short flagfullscreen; /* temporary copy of flag settings for clean fullscreen */ short pad; - + struct ARegionType *type; /* callbacks for this region type */ - + ListBase uiblocks; /* uiBlock */ ListBase panels; /* Panel */ ListBase panels_category_active; /* Stack of panel categories */ @@ -268,9 +268,9 @@ typedef struct ARegion { ListBase ui_previews; /* uiPreview */ ListBase handlers; /* wmEventHandler */ ListBase panels_category; /* Panel categories runtime */ - + struct wmTimer *regiontimer; /* blend in/out */ - + char *headerstr; /* use this string to draw info */ void *regiondata; /* XXX 2.50, need spacedata equivalent? */ } ARegion; @@ -416,4 +416,3 @@ enum { #define RGN_DRAWING 4 #define RGN_DRAW_REFRESH_UI 8 /* re-create uiBlock's where possible */ #endif - diff --git a/source/blender/makesdna/DNA_sdna_types.h b/source/blender/makesdna/DNA_sdna_types.h index bd8f23f30c1b..27d18e496345 100644 --- a/source/blender/makesdna/DNA_sdna_types.h +++ b/source/blender/makesdna/DNA_sdna_types.h @@ -82,4 +82,3 @@ typedef struct BHead8 { } BHead8; #endif - diff --git a/source/blender/makesdna/DNA_sensor_types.h b/source/blender/makesdna/DNA_sensor_types.h index 2eeda3ae8572..cd57d06adb31 100644 --- a/source/blender/makesdna/DNA_sensor_types.h +++ b/source/blender/makesdna/DNA_sensor_types.h @@ -52,7 +52,7 @@ typedef struct bNearSensor { */ typedef struct bMouseSensor { /** - * The type of key this sensor listens to. + * The type of key this sensor listens to. */ short type; short flag; @@ -169,9 +169,9 @@ typedef struct bSensor { short freq, totlinks, pad1, pad2; /* freq makes reference to skipped ticks between 2 active pulses */ char name[64]; /* MAX_NAME */ void *data; - + struct bController **links; - + struct Object *ob; /* just add here, to avoid align errors... */ diff --git a/source/blender/makesdna/DNA_sequence_types.h b/source/blender/makesdna/DNA_sequence_types.h index b7e118d20537..ef076c98b5f1 100644 --- a/source/blender/makesdna/DNA_sequence_types.h +++ b/source/blender/makesdna/DNA_sequence_types.h @@ -215,7 +215,7 @@ typedef struct Editing { ListBase *seqbasep; /* pointer to the current list of seq's being edited (can be within a meta strip) */ ListBase seqbase; /* pointer to the top-most seq's */ ListBase metastack; - + /* Context vars, used to be static */ Sequence *act_seq; char act_imagedir[1024]; /* 1024 = FILE_MAX */ @@ -233,7 +233,7 @@ typedef struct WipeVars { short forward, wipetype; } WipeVars; -typedef struct GlowVars { +typedef struct GlowVars { float fMini; /* Minimum intensity to trigger a glow */ float fClamp; float fBoost; /* Amount to multiply glow intensity */ @@ -439,7 +439,7 @@ enum { SEQ_AUDIO_PITCH_ANIMATED = (1 << 25), SEQ_AUDIO_PAN_ANIMATED = (1 << 26), SEQ_AUDIO_DRAW_WAVEFORM = (1 << 27), - + /* don't include Grease Pencil in OpenGL previews of Scene strips */ SEQ_SCENE_NO_GPENCIL = (1 << 28), SEQ_USE_VIEWS = (1 << 29), diff --git a/source/blender/makesdna/DNA_smoke_types.h b/source/blender/makesdna/DNA_smoke_types.h index c1565bde882d..d74d46aebbd4 100644 --- a/source/blender/makesdna/DNA_smoke_types.h +++ b/source/blender/makesdna/DNA_smoke_types.h @@ -174,7 +174,7 @@ typedef struct SmokeDomainSettings { int flags; /* show up-res or low res, etc */ int viewsettings; short noise; /* noise type: wave, curl, anisotropic */ - short diss_percent; + short diss_percent; int diss_speed;/* in frames */ float strength; int res_wt[3]; diff --git a/source/blender/makesdna/DNA_sound_types.h b/source/blender/makesdna/DNA_sound_types.h index aefe1a7d5a3f..02d3aa928c78 100644 --- a/source/blender/makesdna/DNA_sound_types.h +++ b/source/blender/makesdna/DNA_sound_types.h @@ -65,13 +65,15 @@ typedef struct bSound { */ struct PackedFile *newpackedfile; struct Ipo *ipo; + float volume; float attenuation; float pitch; float min_gain; float max_gain; float distance; - int flags; + short flags; + short tags; /* Runtime only, always reset in readfile. */ int pad; /* unused currently @@ -116,13 +118,19 @@ enum { SND_CFRA_NUM = 2, }; +/* bSound->flags */ enum { #ifdef DNA_DEPRECATED SOUND_FLAGS_3D = (1 << 3), /* deprecated! used for sound actuator loading */ #endif SOUND_FLAGS_CACHING = (1 << 4), SOUND_FLAGS_MONO = (1 << 5), - SOUND_FLAGS_WAVEFORM_LOADING = (1 << 6), +}; + +/* bSound->tags */ +enum { + SOUND_TAGS_WAVEFORM_NO_RELOAD = 1 << 0, /* Do not free/reset waveform on sound load, only used by undo code. */ + SOUND_TAGS_WAVEFORM_LOADING = (1 << 6), }; /* to DNA_sound_types.h*/ diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h index c90de471b2c9..6988a8e53be7 100644 --- a/source/blender/makesdna/DNA_space_types.h +++ b/source/blender/makesdna/DNA_space_types.h @@ -630,7 +630,7 @@ typedef struct FileSelectParams { char renamefile[256]; char renameedit[256]; /* annoying but the first is only used for initialization */ - char filter_glob[256]; /* list of filetypes to filter */ + char filter_glob[256]; /* FILE_MAXFILE */ /* list of filetypes to filter */ char filter_search[64]; /* text items' name must match to be shown. */ int filter_id; /* same as filter, but for ID types (aka library groups). */ diff --git a/source/blender/makesdna/DNA_speaker_types.h b/source/blender/makesdna/DNA_speaker_types.h index 8ad987818aeb..a7408293131e 100644 --- a/source/blender/makesdna/DNA_speaker_types.h +++ b/source/blender/makesdna/DNA_speaker_types.h @@ -34,7 +34,7 @@ struct bSound; typedef struct Speaker { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ struct bSound *sound; @@ -65,4 +65,3 @@ typedef struct Speaker { #define SPK_RELATIVE (1<<2) #endif /* __DNA_SPEAKER_TYPES_H__ */ - diff --git a/source/blender/makesdna/DNA_text_types.h b/source/blender/makesdna/DNA_text_types.h index c191bd2dc6d5..65ab0324de6d 100644 --- a/source/blender/makesdna/DNA_text_types.h +++ b/source/blender/makesdna/DNA_text_types.h @@ -49,16 +49,16 @@ typedef struct TextLine { typedef struct Text { ID id; - + char *name; void *compiled; int flags, nlines; - + ListBase lines; TextLine *curl, *sell; int curc, selc; - + double mtime; const char *cmmt_pfx; diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h index d88d0db3f3d1..c72dbfe43067 100644 --- a/source/blender/makesdna/DNA_texture_types.h +++ b/source/blender/makesdna/DNA_texture_types.h @@ -60,7 +60,7 @@ typedef struct MTex { struct Object *object; struct Tex *tex; char uvname[64]; /* MAX_CUSTOMDATA_LAYER_NAME */ - + char projx, projy, projz, mapping; char brush_map_mode, brush_angle_mode; char pad[2]; @@ -70,10 +70,10 @@ typedef struct MTex { short normapspace, which_output; float r, g, b, k; float def_var, rt; - + /* common */ float colfac, varfac; - + /* material */ float norfac, dispfac, warpfac; float parallaxsteps, parallaxbumpsc; @@ -154,10 +154,10 @@ typedef struct PointDensity { float radius; short source; short pad0; - + short color_source; /* psys_color_source */ short ob_color_source; - + int totpoints; struct Object *object; /* for 'Object' or 'Particle system' type - source object */ @@ -165,20 +165,20 @@ typedef struct PointDensity { short psys_cache_space; /* cache points in worldspace, object space, ... ? */ short ob_cache_space; /* cache points in worldspace, object space, ... ? */ char vertex_attribute_name[64]; /* vertex attribute layer for color source, MAX_CUSTOMDATA_LAYER_NAME */ - + void *point_tree; /* the acceleration tree containing points */ float *point_data; /* dynamically allocated extra for extra information, like particle age */ - + float noise_size; short noise_depth; short noise_influence; short noise_basis; short pad1[3]; float noise_fac; - + float speed_scale, falloff_speed_scale, pad2; struct ColorBand *coba; /* for time -> color */ - + struct CurveMapping *falloff_curve; /* falloff density curve */ } PointDensity; @@ -192,7 +192,7 @@ typedef struct VoxelData { short hair_type; short data_type; int _pad; - + struct Object *object; /* for rendering smoke sims */ float int_multiplier; int still_frame; @@ -202,22 +202,22 @@ typedef struct VoxelData { float *dataset; int cachedframe; int ok; - + } VoxelData; typedef struct OceanTex { struct Object *object; char oceanmod[64]; - + int output; int pad; - + } OceanTex; - + typedef struct Tex { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + float noisesize, turbul; float bright, contrast, saturation, rfac, gfac, bfac; float filtersize, pad2; @@ -243,7 +243,7 @@ typedef struct Tex { short imaflag, flag; short type, stype; - + float cropxmin, cropymin, cropxmax, cropymax; int texfilter; int afmax; // anisotropic filter maximum value, ewa -> max eccentricity, feline -> max probes @@ -254,12 +254,12 @@ typedef struct Tex { short fie_ima; int len; int frames, offset, sfra; - + float checkerdist, nabla; float pad1; - + struct ImageUser iuser; - + struct bNodeTree *nodetree; struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ struct Image *ima; @@ -269,10 +269,10 @@ typedef struct Tex { struct PointDensity *pd; struct VoxelData *vd; struct OceanTex *ot; - + char use_nodes; char pad[7]; - + } Tex; /* used for mapping and texture nodes. note: rot is now in radians */ @@ -282,7 +282,7 @@ typedef struct TexMapping { int flag; char projx, projy, projz, mapping; int type; - + float mat[4][4]; float min[3], max[3]; struct Object *ob; @@ -400,7 +400,7 @@ typedef struct ColorMapping { #define TEX_PRV_NOR 64 #define TEX_REPEAT_XMIR 128 #define TEX_REPEAT_YMIR 256 -#define TEX_FLAG_MASK ( TEX_COLORBAND | TEX_FLIPBLEND | TEX_NEGALPHA | TEX_CHECKER_ODD | TEX_CHECKER_EVEN | TEX_PRV_ALPHA | TEX_PRV_NOR | TEX_REPEAT_XMIR | TEX_REPEAT_YMIR ) +#define TEX_FLAG_MASK ( TEX_COLORBAND | TEX_FLIPBLEND | TEX_NEGALPHA | TEX_CHECKER_ODD | TEX_CHECKER_EVEN | TEX_PRV_ALPHA | TEX_PRV_NOR | TEX_REPEAT_XMIR | TEX_REPEAT_YMIR ) #define TEX_DS_EXPAND 512 #define TEX_NO_CLAMP 1024 @@ -536,7 +536,7 @@ typedef struct ColorMapping { #define MTEX_BLEND_SAT 11 #define MTEX_BLEND_VAL 12 #define MTEX_BLEND_COLOR 13 -#define MTEX_SOFT_LIGHT 15 +#define MTEX_SOFT_LIGHT 15 #define MTEX_LIN_LIGHT 16 /* brush_map_mode */ @@ -684,16 +684,15 @@ enum { #define TEX_OCN_DISPLACEMENT 1 #define TEX_OCN_FOAM 2 #define TEX_OCN_JPLUS 3 -#define TEX_OCN_EMINUS 4 +#define TEX_OCN_EMINUS 4 #define TEX_OCN_EPLUS 5 /* flag */ -#define TEX_OCN_GENERATE_NORMALS 1 -#define TEX_OCN_XZ 2 - +#define TEX_OCN_GENERATE_NORMALS 1 +#define TEX_OCN_XZ 2 + #ifdef __cplusplus } #endif #endif - diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h index a7759a1d1438..f78b48b2d25d 100644 --- a/source/blender/makesdna/DNA_userdef_types.h +++ b/source/blender/makesdna/DNA_userdef_types.h @@ -53,7 +53,7 @@ struct ColorBand; typedef enum eUIFont_ID { UIFONT_DEFAULT = 0, /* UIFONT_BITMAP = 1 */ /* UNUSED */ - + /* free slots */ UIFONT_CUSTOM1 = 2, UIFONT_CUSTOM2 = 3 @@ -67,7 +67,7 @@ typedef struct uiFont { short blf_id; /* from blfont lib */ short uifont_id; /* own id (eUIFont_ID) */ short r_to_l; /* fonts that read from left to right */ - short hinting; + short pad; } uiFont; /* this state defines appearance of text */ @@ -97,16 +97,16 @@ typedef enum eFontStyle_Align { typedef struct uiStyle { struct uiStyle *next, *prev; - + char name[64]; /* MAX_STYLE_NAME */ - + uiFontStyle paneltitle; uiFontStyle grouplabel; uiFontStyle widgetlabel; uiFontStyle widget; - + float panelzoom; - + short minlabelchars; /* in characters */ short minwidgetchars; /* in characters */ @@ -165,7 +165,7 @@ typedef struct ThemeUI { uiWidgetColors wcol_num, wcol_numslider; uiWidgetColors wcol_menu, wcol_pulldown, wcol_menu_back, wcol_menu_item, wcol_tooltip; uiWidgetColors wcol_box, wcol_scroll, wcol_progress, wcol_list_item, wcol_pie_menu; - + uiWidgetStateColors wcol_state; uiPanelColors panel; /* depricated, but we keep it for do_versions (2.66.1) */ @@ -175,9 +175,9 @@ typedef struct ThemeUI { /* fac: 0 - 1 for blend factor, width in pixels */ float menu_shadow_fac; short menu_shadow_width; - + short pad[3]; - + char iconfile[256]; // FILE_MAXFILE length float icon_alpha; @@ -194,7 +194,7 @@ typedef struct ThemeSpace { char title[4]; /* panel title */ char text[4]; char text_hi[4]; - + /* header colors */ char header[4]; /* region background */ char header_title[4]; /* unused */ @@ -212,19 +212,19 @@ typedef struct ThemeSpace { char button_title[4]; /* panel title */ char button_text[4]; char button_text_hi[4]; - + /* listview regions */ char list[4]; /* region background */ char list_title[4]; /* panel title */ char list_text[4]; char list_text_hi[4]; - + /* float panel */ /* char panel[4]; unused */ /* char panel_title[4]; unused */ /* char panel_text[4]; unused */ /* char panel_text_hi[4]; unused */ - + /* note, cannot use name 'panel' because of DNA mapping old files */ uiPanelColors panelcolors; @@ -232,10 +232,10 @@ typedef struct ThemeSpace { char shade1[4]; char shade2[4]; - + char hilite[4]; - char grid[4]; - + char grid[4]; + char view_overlay[4]; char wire[4], wire_edit[4], select[4]; @@ -255,58 +255,58 @@ typedef struct ThemeSpace { char cframe[4]; char time_keyframe[4], time_gp_keyframe[4]; char freestyle_edge_mark[4], freestyle_face_mark[4]; - + char nurb_uline[4], nurb_vline[4]; char act_spline[4], nurb_sel_uline[4], nurb_sel_vline[4], lastsel_point[4]; - + char handle_free[4], handle_auto[4], handle_vect[4], handle_align[4], handle_auto_clamped[4]; char handle_sel_free[4], handle_sel_auto[4], handle_sel_vect[4], handle_sel_align[4], handle_sel_auto_clamped[4]; - + char ds_channel[4], ds_subchannel[4]; /* dopesheet */ char keytype_keyframe[4], keytype_extreme[4], keytype_breakdown[4], keytype_jitter[4]; /* keytypes */ char keytype_keyframe_select[4], keytype_extreme_select[4], keytype_breakdown_select[4], keytype_jitter_select[4]; /* keytypes */ char keyborder[4], keyborder_select[4]; - + char console_output[4], console_input[4], console_info[4], console_error[4]; char console_cursor[4], console_select[4]; - + char vertex_size, outline_width, facedot_size; char noodle_curving; /* syntax for textwindow and nodes */ - char syntaxl[4], syntaxs[4]; // in nodespace used for backdrop matte + char syntaxl[4], syntaxs[4]; // in nodespace used for backdrop matte char syntaxb[4], syntaxn[4]; // in nodespace used for color input char syntaxv[4], syntaxc[4]; // in nodespace used for converter group - char syntaxd[4], syntaxr[4]; // in nodespace used for distort + char syntaxd[4], syntaxr[4]; // in nodespace used for distort char nodeclass_output[4], nodeclass_filter[4]; char nodeclass_vector[4], nodeclass_texture[4]; char nodeclass_shader[4], nodeclass_script[4]; char nodeclass_pattern[4], nodeclass_layout[4]; - + char movie[4], movieclip[4], mask[4], image[4], scene[4], audio[4]; /* for sequence editor */ char effect[4], transition[4], meta[4], text_strip[4]; - + float keyframe_scale_fac; /* for dopesheet - scale factor for size of keyframes (i.e. height of channels) */ - - char editmesh_active[4]; + + char editmesh_active[4]; char handle_vertex[4]; char handle_vertex_select[4]; - + char handle_vertex_size; char clipping_border_3d[4]; - + char marker_outline[4], marker[4], act_marker[4], sel_marker[4], dis_marker[4], lock_marker[4]; char bundle_solid[4]; char path_before[4], path_after[4]; char camera_path[4]; char hpad[2]; - + char gp_vertex_size; char gp_vertex[4], gp_vertex_select[4]; - + char preview_back[4]; char preview_stitch_face[4]; char preview_stitch_edge[4]; @@ -314,7 +314,7 @@ typedef struct ThemeSpace { char preview_stitch_stitchable[4]; char preview_stitch_unstitchable[4]; char preview_stitch_active[4]; - + char uv_shadow[4]; /* two uses, for uvs with modifier applied on mesh and uvs during painting */ char uv_others[4]; /* uvs of other objects */ @@ -322,14 +322,14 @@ typedef struct ThemeSpace { char selected_highlight[4]; /* outliner - selected item */ char skin_root[4]; /* Skin modifier root color */ - + /* NLA */ char anim_active[4]; /* Active Action + Summary Channel */ char anim_non_active[4]; /* Active Action = NULL */ - + char nla_tweaking[4]; /* NLA 'Tweaking' action/strip */ char nla_tweakdupli[4]; /* NLA - warning color for duplicate instances of tweaking strip */ - + char nla_transition[4], nla_transition_sel[4]; /* NLA "Transition" strips */ char nla_meta[4], nla_meta_sel[4]; /* NLA "Meta" strips */ char nla_sound[4], nla_sound_sel[4]; /* NLA "Sound" strips */ @@ -354,10 +354,10 @@ typedef struct ThemeWireColor { char solid[4]; char select[4]; char active[4]; - + short flag; /* eWireColor_Flags */ short pad; -} ThemeWireColor; +} ThemeWireColor; /* ThemeWireColor.flag */ typedef enum eWireColor_Flags { @@ -369,9 +369,9 @@ typedef enum eWireColor_Flags { typedef struct bTheme { struct bTheme *next, *prev; char name[32]; - + ThemeUI tui; - + /* Individual Spacetypes */ /* note: ensure UI_THEMESPACE_END is updated when adding */ ThemeSpace tbuts; @@ -391,11 +391,11 @@ typedef struct bTheme { ThemeSpace tuserpref; ThemeSpace tconsole; ThemeSpace tclip; - + /* 20 sets of bone colors for this theme */ ThemeWireColor tarm[20]; /*ThemeWireColor tobj[20];*/ - + int active_theme_area, pad; } bTheme; @@ -433,7 +433,7 @@ typedef struct WalkNavigation { typedef struct UserDef { /* UserDef has separate do-version handling, and can be read from other files */ int versionfile, subversionfile; - + int flag; /* eUserPref_Flag */ int dupflag; /* eDupli_ID_Flags */ int savetime; @@ -449,13 +449,13 @@ typedef struct UserDef { char image_editor[1024]; /* 1024 = FILE_MAX */ char anim_player[1024]; /* 1024 = FILE_MAX */ int anim_player_preset; - + short v2d_min_gridsize; /* minimum spacing between gridlines in View2D grids */ short timecode_style; /* eTimecodeStyles, style of timecode display */ - + short versions; short dbl_click_time; - + short gameflags; short wheellinescroll; int uiflag; /* eUserpref_UI_Flag */ @@ -465,7 +465,7 @@ typedef struct UserDef { short app_flag; short language; short userpref, viewzoom; - + int mixbufsize; int audiodevice; int audiorate; @@ -492,7 +492,7 @@ typedef struct UserDef { struct ListBase addons; struct ListBase autoexec_paths; char keyconfigstr[64]; - + short undosteps; short pad1; int undomemory; @@ -527,9 +527,8 @@ typedef struct UserDef { int view_frame_keyframes; /* number of keyframes to zoom around current frame */ float view_frame_seconds; /* seconds to zoom around current frame */ - short scrcastfps; /* frame rate for screencast to be played back */ - short scrcastwait; /* milliseconds between screencast snapshots */ - + char _pad0[4]; + short widget_unit; /* private, defaults to 20 for 72 DPI setting */ short anisotropic_filter; short use_16bit_textures, use_gpu_mipmap; @@ -543,12 +542,12 @@ typedef struct UserDef { /* eImageDrawMethod, Method to be used to draw the images (AUTO, GLSL, Textures or DrawPixels) */ short image_draw_method; - + float glalphaclip; - + short autokey_mode; /* eAutokey_Mode, autokeying mode */ short autokey_flag; /* flags for autokeying */ - + short text_render, pad9; /* options for text rendering */ struct ColorBand coba_weight; /* from texture.h */ @@ -566,7 +565,7 @@ typedef struct UserDef { int compute_device_type; int compute_device_id; - + float fcu_inactive_alpha; /* opacity of inactive F-Curves in F-Curve Editor */ float pixelsize; /* private, set by GHOST, to multiply DPI with */ int virtual_pixel; /* virtual pixelsize mode */ @@ -613,7 +612,7 @@ typedef enum eUserPref_Flag { USER_FLAG_DEPRECATED_7 = (1 << 7), /* cleared */ USER_MAT_ON_OB = (1 << 8), USER_FLAG_DEPRECATED_9 = (1 << 9), /* cleared */ - USER_FLAG_DEPRECATED_10 = (1 << 10), /* cleared */ + USER_DEVELOPER_UI = (1 << 10), USER_TOOLTIPS = (1 << 11), USER_TWOBUTTONMOUSE = (1 << 12), USER_NONUMPAD = (1 << 13), @@ -717,7 +716,7 @@ typedef enum eUserpref_APP_Flag { typedef enum eAutokey_Mode { /* AUTOKEY_ON is a bitflag */ AUTOKEY_ON = 1, - + /* AUTOKEY_ON + 2**n... (i.e. AUTOKEY_MODE_NORMAL = AUTOKEY_ON + 2) to preserve setting, even when autokey turned off */ AUTOKEY_MODE_NORMAL = 3, AUTOKEY_MODE_EDITKEYS = 5 @@ -740,7 +739,7 @@ typedef enum eAutokey_Flag { AUTOKEY_FLAG_INSERTNEEDED = (1 << 1), AUTOKEY_FLAG_AUTOMATKEY = (1 << 2), AUTOKEY_FLAG_XYZ2RGB = (1 << 3), - + /* toolsettings->autokey_flag */ AUTOKEY_FLAG_ONLYKEYINGSET = (1 << 6), AUTOKEY_FLAG_NOWARNING = (1 << 7), @@ -805,7 +804,11 @@ typedef enum eWM_DrawMethod { /* text draw options * UserDef.text_render */ typedef enum eText_Draw_Options { - USER_TEXT_DISABLE_AA = (1 << 0), + USER_TEXT_DISABLE_AA = (1 << 0), + + USER_TEXT_HINTING_NONE = (1 << 1), + USER_TEXT_HINTING_SLIGHT = (1 << 2), + USER_TEXT_HINTING_FULL = (1 << 3), } eText_Draw_Options; /* tw_flag (transform widget) */ @@ -831,7 +834,7 @@ typedef enum eColorPicker_Types { * UserDef.timecode_style */ typedef enum eTimecodeStyles { /* as little info as is necessary to show relevant info - * with '+' to denote the frames + * with '+' to denote the frames * i.e. HH:MM:SS+FF, MM:SS+FF, SS+FF, or MM:SS */ USER_TIMECODE_MINIMAL = 0, diff --git a/source/blender/makesdna/DNA_vec_types.h b/source/blender/makesdna/DNA_vec_types.h index 7ec259370b51..4a7aaaaa940e 100644 --- a/source/blender/makesdna/DNA_vec_types.h +++ b/source/blender/makesdna/DNA_vec_types.h @@ -95,4 +95,3 @@ typedef struct rctf { } rctf; #endif - diff --git a/source/blender/makesdna/DNA_vfont_types.h b/source/blender/makesdna/DNA_vfont_types.h index 7025a5767c4b..721a97742b97 100644 --- a/source/blender/makesdna/DNA_vfont_types.h +++ b/source/blender/makesdna/DNA_vfont_types.h @@ -44,9 +44,9 @@ struct VFontData; typedef struct VFont { ID id; - + char name[1024]; /* 1024 = FILE_MAX */ - + struct VFontData *data; struct PackedFile *packedfile; diff --git a/source/blender/makesdna/DNA_view2d_types.h b/source/blender/makesdna/DNA_view2d_types.h index 3319fed8cdd8..4132e17a249c 100644 --- a/source/blender/makesdna/DNA_view2d_types.h +++ b/source/blender/makesdna/DNA_view2d_types.h @@ -41,23 +41,23 @@ typedef struct View2D { rctf tot, cur; /* tot - area that data can be drawn in; cur - region of tot that is visible in viewport */ rcti vert, hor; /* vert - vertical scrollbar region; hor - horizontal scrollbar region */ rcti mask; /* mask - region (in screenspace) within which 'cur' can be viewed */ - + float min[2], max[2]; /* min/max sizes of 'cur' rect (only when keepzoom not set) */ float minzoom, maxzoom; /* allowable zoom factor range (only when (keepzoom & V2D_LIMITZOOM)) is set */ - + short scroll; /* scroll - scrollbars to display (bitflag) */ short scroll_ui; /* scroll_ui - temp settings used for UI drawing of scrollers */ - + short keeptot; /* keeptot - 'cur' rect cannot move outside the 'tot' rect? */ short keepzoom; /* keepzoom - axes that zooming cannot occur on, and also clamp within zoom-limits */ short keepofs; /* keepofs - axes that translation is not allowed to occur on */ - + short flag; /* settings */ short align; /* alignment of content in totrect */ - + short winx, winy; /* storage of current winx/winy values, set in UI_view2d_size_update */ short oldwinx, oldwiny; /* storage of previous winx/winy values encountered by UI_view2d_curRect_validate(), for keepaspect */ - + short around; /* pivot point for transforms (rotate and scale) */ float *tab_offset; /* different offset per tab, for buttons */ @@ -164,4 +164,3 @@ enum { }; #endif - diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h index 1b4bca1993dd..9fde815464c0 100644 --- a/source/blender/makesdna/DNA_view3d_types.h +++ b/source/blender/makesdna/DNA_view3d_types.h @@ -79,7 +79,7 @@ typedef struct BGpic { /* ********************************* */ typedef struct RegionView3D { - + float winmat[4][4]; /* GL_PROJECTION matrix */ float viewmat[4][4]; /* GL_MODELVIEW matrix */ float viewinv[4][4]; /* inverse of viewmat */ @@ -162,10 +162,10 @@ typedef struct View3D { unsigned int lay_prev; /* for active layer toggle */ unsigned int lay_used; /* used while drawing */ - + short persp DNA_DEPRECATED; short view DNA_DEPRECATED; - + struct Object *camera, *ob_centre; rctf render_border; @@ -173,20 +173,21 @@ typedef struct View3D { struct BGpic *bgpic DNA_DEPRECATED; /* deprecated, use bgpicbase, only kept for do_versions(...) */ struct View3D *localvd; /* allocated backup of its self while in localview */ - + char ob_centre_bone[64]; /* optional string for armature bone to define center, MAXBONENAME */ - + unsigned int lay; int layact; - + /** * The drawing mode for the 3d display. Set to OB_BOUNDBOX, OB_WIRE, OB_SOLID, * OB_TEXTURE, OB_MATERIAL or OB_RENDER */ - short drawtype; - short ob_centre_cursor; /* optional bool for 3d cursor to define center */ + char drawtype; + char ob_centre_cursor; /* optional bool for 3d cursor to define center */ short scenelock, around; - short flag, flag2; - + short flag; + int flag2; + float lens, grid; float near, far; float ofs[3] DNA_DEPRECATED; /* XXX deprecated */ @@ -200,9 +201,9 @@ typedef struct View3D { /* transform widget info */ char twtype, twmode, twflag; - - short flag3; - + + short _pad1; + /* afterdraw, for xray & transparent */ struct ListBase afterdraw_transp; struct ListBase afterdraw_xray; @@ -297,7 +298,7 @@ typedef struct View3D { #define RV3D_VIEW_IS_AXIS(view) \ (((view) >= RV3D_VIEW_FRONT) && ((view) <= RV3D_VIEW_BOTTOM)) -/* View3d->flag2 (short) */ +/* View3d->flag2 (int) */ #define V3D_RENDER_OVERRIDE (1 << 2) #define V3D_SOLID_TEX (1 << 3) #define V3D_SHOW_GPENCIL (1 << 4) @@ -312,12 +313,10 @@ typedef struct View3D { #define V3D_SHOW_SOLID_MATCAP (1 << 13) /* runtime flag */ #define V3D_OCCLUDE_WIRE (1 << 14) #define V3D_SHADELESS_TEX (1 << 15) +#define V3D_SHOW_WORLD (1 << 16) +#define V3D_SHOW_MIST (1 << 17) -/* View3d->flag3 (short) */ -#define V3D_SHOW_WORLD (1 << 0) -#define V3D_SHOW_MIST (1 << 1) - /* View3D->around */ enum { /* center of the bounding box */ @@ -399,4 +398,3 @@ enum { #define RV3D_CAMZOOM_MAX_FACTOR 44.9852813742385702928f #endif - diff --git a/source/blender/makesdna/DNA_windowmanager_types.h b/source/blender/makesdna/DNA_windowmanager_types.h index 7af10a596ff4..7e55eb4633ec 100644 --- a/source/blender/makesdna/DNA_windowmanager_types.h +++ b/source/blender/makesdna/DNA_windowmanager_types.h @@ -233,7 +233,7 @@ typedef struct wmWindow { #endif /* These two Lines with # tell makesdna this struct can be excluded. */ -/* should be something like DNA_EXCLUDE +/* should be something like DNA_EXCLUDE * but the preprocessor first removes all comments, spaces etc */ # # @@ -317,7 +317,7 @@ typedef struct wmKeyMap { /* runtime */ /** Verify if enabled in the current context, use #WM_keymap_poll instead of direct calls. */ - int (*poll)(struct bContext *); + bool (*poll)(struct bContext *); /** For modal, #EnumPropertyItem for now. */ const void *modal_items; } wmKeyMap; diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h index 5fd4c9fd4070..0ae9bcd0256b 100644 --- a/source/blender/makesdna/DNA_world_types.h +++ b/source/blender/makesdna/DNA_world_types.h @@ -51,8 +51,8 @@ struct MTex; * data and modeling data. */ typedef struct World { ID id; - struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ - + struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ + short colormodel, totex; short texact, mistype; @@ -77,7 +77,7 @@ typedef struct World { * Radius of the activity bubble, in Manhattan length. Objects * outside the box are activity-culled. */ float activityBoxRadius; // XXX moved to scene->gamedata in 2.5 - + short skytype; /** * Some world modes @@ -86,22 +86,22 @@ typedef struct World { * bit 2: (reserved) depth of field * bit 3: (gameengine): Activity culling is enabled. * bit 4: ambient occlusion - * bit 5: (gameengine) : enable Bullet DBVT tree for view frustum culling + * bit 5: (gameengine) : enable Bullet DBVT tree for view frustum culling */ short mode; // partially moved to scene->gamedata in 2.5 short occlusionRes; /* resolution of occlusion Z buffer in pixel */ // XXX moved to scene->gamedata in 2.5 short physicsEngine; /* here it's aligned */ // XXX moved to scene->gamedata in 2.5 short ticrate, maxlogicstep, physubstep, maxphystep; // XXX moved to scene->gamedata in 2.5 - + float misi, miststa, mistdist, misthi; - + float starr DNA_DEPRECATED, starg DNA_DEPRECATED, starb DNA_DEPRECATED, stark DNA_DEPRECATED; /* Deprecated */ float starsize DNA_DEPRECATED, starmindist DNA_DEPRECATED; float stardist DNA_DEPRECATED, starcolnoise DNA_DEPRECATED; - + /* unused now: DOF */ short dofsta, dofend, dofmin, dofmax; - + /* ambient occlusion */ float aodist, aodistfac, aoenergy, aobias; short aomode, aosamp, aomix, aocolor; @@ -110,14 +110,14 @@ typedef struct World { float ao_indirect_energy, ao_env_energy, ao_pad2; short ao_indirect_bounces, ao_pad; short ao_samp_method, ao_gather_method, ao_approx_passes; - + /* assorted settings (in the middle of ambient occlusion settings for padding reasons) */ short flag; - + /* ambient occlusion (contd...) */ float *aosphere, *aotables; - - + + struct Ipo *ipo DNA_DEPRECATED; /* old animation system, deprecated for 2.5 */ struct MTex *mtex[18]; /* MAX_MTEX */ short pr_texture, use_nodes, pad[2]; @@ -195,10 +195,9 @@ enum { /* flag */ #define WO_DS_EXPAND (1<<0) - /* NOTE: this must have the same value as MA_DS_SHOW_TEXS, + /* NOTE: this must have the same value as MA_DS_SHOW_TEXS, * otherwise anim-editors will not read correctly */ #define WO_DS_SHOW_TEXS (1<<2) #endif - diff --git a/source/blender/makesdna/intern/dna_genfile.c b/source/blender/makesdna/intern/dna_genfile.c index 2e21223d042d..d8d29c9c8124 100644 --- a/source/blender/makesdna/intern/dna_genfile.c +++ b/source/blender/makesdna/intern/dna_genfile.c @@ -201,10 +201,10 @@ static int elementsize(const SDNA *sdna, short type, short name) { int mul, namelen, len; const char *cp; - + cp = sdna->names[name]; len = 0; - + namelen = strlen(cp); /* is it a pointer or function pointer? */ if (ispointer(cp)) { @@ -213,7 +213,7 @@ static int elementsize(const SDNA *sdna, short type, short name) if (cp[namelen - 1] == ']') { mul = DNA_elem_array_size(cp); } - + len = sdna->pointerlen * mul; } else if (sdna->typelens[type]) { @@ -222,11 +222,11 @@ static int elementsize(const SDNA *sdna, short type, short name) if (cp[namelen - 1] == ']') { mul = DNA_elem_array_size(cp); } - + len = mul * sdna->typelens[type]; - + } - + return len; } @@ -236,13 +236,13 @@ static void printstruct(SDNA *sdna, short strnr) /* is for debug */ int b, nr; short *sp; - + sp = sdna->structs[strnr]; - + printf("struct %s\n", sdna->types[sp[0]]); nr = sp[1]; sp += 2; - + for (b = 0; b < nr; b++, sp += 2) { printf(" %s %s\n", sdna->types[sp[0]], sdna->names[sp[1]]); } @@ -322,7 +322,7 @@ static bool init_structDNA( int *data, *verg, gravity_fix = -1; short *sp; char str[8]; - + verg = (int *)str; data = (int *)sdna->data; @@ -343,17 +343,17 @@ static bool init_structDNA( const char *cp; data++; - + /* load names array */ strcpy(str, "NAME"); if (*data == *verg) { data++; - + sdna->nr_names = *data; if (do_endian_swap) { BLI_endian_switch_int32(&sdna->nr_names); } - + data++; sdna->names = MEM_callocN(sizeof(void *) * sdna->nr_names, "sdnanames"); } @@ -361,7 +361,7 @@ static bool init_structDNA( *r_error_message = "NAME error in SDNA file"; return false; } - + cp = (char *)data; for (int nr = 0; nr < sdna->nr_names; nr++) { sdna->names[nr] = cp; @@ -381,7 +381,7 @@ static bool init_structDNA( } cp = pad_up_4(cp); - + /* load type names array */ data = (int *)cp; strcpy(str, "TYPE"); @@ -392,7 +392,7 @@ static bool init_structDNA( if (do_endian_swap) { BLI_endian_switch_int32(&sdna->nr_types); } - + data++; sdna->types = MEM_callocN(sizeof(void *) * sdna->nr_types, "sdnatypes"); } @@ -400,25 +400,25 @@ static bool init_structDNA( *r_error_message = "TYPE error in SDNA file"; return false; } - + cp = (char *)data; for (int nr = 0; nr < sdna->nr_types; nr++) { sdna->types[nr] = cp; - + /* this is a patch, to change struct names without a conflict with SDNA */ /* be careful to use it, in this case for a system-struct (opengl/X) */ - + if (*cp == 'b') { /* struct Screen was already used by X, 'bScreen' replaces the old IrisGL 'Screen' struct */ if (strcmp("bScreen", cp) == 0) sdna->types[nr] = cp + 1; } - + while (*cp) cp++; cp++; } cp = pad_up_4(cp); - + /* load typelen array */ data = (int *)cp; strcpy(str, "TLEN"); @@ -426,11 +426,11 @@ static bool init_structDNA( data++; sp = (short *)data; sdna->typelens = sp; - + if (do_endian_swap) { BLI_endian_switch_int16_array(sp, sdna->nr_types); } - + sp += sdna->nr_types; } else { @@ -444,12 +444,12 @@ static bool init_structDNA( strcpy(str, "STRC"); if (*data == *verg) { data++; - + sdna->nr_structs = *data; if (do_endian_swap) { BLI_endian_switch_int32(&sdna->nr_structs); } - + data++; sdna->structs = MEM_callocN(sizeof(void *) * sdna->nr_structs, "sdnastrcs"); } @@ -457,17 +457,17 @@ static bool init_structDNA( *r_error_message = "STRC error in SDNA file"; return false; } - + sp = (short *)data; for (int nr = 0; nr < sdna->nr_structs; nr++) { sdna->structs[nr] = sp; - + if (do_endian_swap) { short a; - + BLI_endian_switch_int16(&sp[0]); BLI_endian_switch_int16(&sp[1]); - + a = sp[1]; sp += 2; while (a--) { @@ -552,7 +552,7 @@ SDNA *DNA_sdna_from_data( sdna->data = data; } sdna->data_alloc = data_alloc; - + if (init_structDNA(sdna, do_endian_swap, &error_message)) { return sdna; @@ -606,11 +606,11 @@ static void recurs_test_compflags(const SDNA *sdna, char *compflags, int structn int a, b, typenr, elems; const short *sp; const char *cp; - + /* check all structs, test if it's inside another struct */ sp = sdna->structs[structnr]; typenr = sp[0]; - + for (a = 0; a < sdna->nr_structs; a++) { if ((a != structnr) && (compflags[a] == SDNA_CMP_EQUAL)) { sp = sdna->structs[a]; @@ -627,7 +627,7 @@ static void recurs_test_compflags(const SDNA *sdna, char *compflags, int structn } } } - + } @@ -641,7 +641,7 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna const short *sp_old, *sp_new; const char *str1, *str2; char *compflags; - + if (oldsdna->nr_structs == 0) { printf("error: file without SDNA\n"); return NULL; @@ -649,14 +649,14 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna compflags = MEM_callocN(oldsdna->nr_structs, "compflags"); - /* we check all structs in 'oldsdna' and compare them with + /* we check all structs in 'oldsdna' and compare them with * the structs in 'newsdna' */ unsigned int newsdna_index_last = 0; - + for (a = 0; a < oldsdna->nr_structs; a++) { sp_old = oldsdna->structs[a]; - + /* search for type in cur */ int sp_new_index = DNA_struct_find_nr_ex(newsdna, oldsdna->types[sp_old[0]], &newsdna_index_last); @@ -667,7 +667,7 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna sp_new = newsdna->structs[sp_new_index]; /* initial assumption */ compflags[a] = SDNA_CMP_NOT_EQUAL; - + /* compare length and amount of elems */ if (sp_new[1] == sp_old[1]) { if (newsdna->typelens[sp_new[0]] == oldsdna->typelens[sp_old[0]]) { @@ -701,7 +701,7 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna } } - + } } @@ -718,7 +718,7 @@ const char *DNA_struct_get_compareflags(const SDNA *oldsdna, const SDNA *newsdna recurs_test_compflags(oldsdna, compflags, a); } } - + #if 0 for (a = 0; a < oldsdna->nr_structs; a++) { if (compflags[a] == SDNA_CMP_NOT_EQUAL) { @@ -801,7 +801,7 @@ static void cast_elem( case SDNA_TYPE_UINT64: val = *( (uint64_t *)olddata); break; } - + switch (ctypenr) { case SDNA_TYPE_CHAR: *curdata = val; break; @@ -846,11 +846,11 @@ static void cast_pointer(int curlen, int oldlen, const char *name, char *curdata { int64_t lval; int arrlen; - + arrlen = DNA_elem_array_size(name); - + while (arrlen > 0) { - + if (curlen == oldlen) { memcpy(curdata, olddata, curlen); } @@ -869,7 +869,7 @@ static void cast_pointer(int curlen, int oldlen, const char *name, char *curdata /* for debug */ printf("errpr: illegal pointersize!\n"); } - + olddata += oldlen; curdata += curlen; arrlen--; @@ -883,7 +883,7 @@ static void cast_pointer(int curlen, int oldlen, const char *name, char *curdata static int elem_strcmp(const char *name, const char *oname) { int a = 0; - + while (1) { if (name[a] != oname[a]) return 1; if (name[a] == '[' || oname[a] == '[') break; @@ -893,11 +893,48 @@ static int elem_strcmp(const char *name, const char *oname) return 0; } +/** + * Returns whether the specified field exists according to the struct format + * pointed to by old. + * + * \param sdna Old SDNA + * \param type Current field type name + * \param name Current field name + * \param old Pointer to struct information in sdna + * \return true when existsing, false otherwise. + */ +static bool elem_exists( + const SDNA *sdna, + const char *type, + const char *name, + const short *old) +{ + int a, elemcount; + const char *otype, *oname; + + /* in old is the old struct */ + elemcount = old[1]; + old += 2; + for (a = 0; a < elemcount; a++, old += 2) { + otype = sdna->types[old[0]]; + oname = sdna->names[old[1]]; + + if (elem_strcmp(name, oname) == 0) { /* name equal */ + return strcmp(type, otype) == 0; /* type equal */ + } + } + return false; +} + /** * Returns the address of the data for the specified field within olddata * according to the struct format pointed to by old, or NULL if no such * field can be found. * + * Passing olddata=NULL doesn't work reliably for existence checks; it will + * return NULL both when the field is found at offset 0 and when it is not + * found at all. For field existence checks, use elem_exists() instead. + * * \param sdna Old SDNA * \param type Current field type name * \param name Current field name @@ -916,9 +953,9 @@ static const char *find_elem( { int a, elemcount, len; const char *otype, *oname; - + /* without arraypart, so names can differ: return old namenr and type */ - + /* in old is the old struct */ elemcount = old[1]; old += 2; @@ -934,10 +971,10 @@ static const char *find_elem( if (sppo) *sppo = old; return olddata; } - + return NULL; } - + olddata += len; } return NULL; @@ -975,7 +1012,7 @@ static void reconstruct_elem( */ int a, elemcount, len, countpos, oldsize, cursize, mul; const char *otype, *oname, *cp; - + /* is 'name' an array? */ cp = name; countpos = 0; @@ -983,7 +1020,7 @@ static void reconstruct_elem( cp++; countpos++; } if (*cp != '[') countpos = 0; - + /* in old is the old struct */ elemcount = old[1]; old += 2; @@ -991,9 +1028,9 @@ static void reconstruct_elem( otype = oldsdna->types[old[0]]; oname = oldsdna->names[old[1]]; len = elementsize(oldsdna, old[0], old[1]); - + if (strcmp(name, oname) == 0) { /* name equal */ - + if (ispointer(name)) { /* pointer of functionpointer afhandelen */ cast_pointer(newsdna->pointerlen, oldsdna->pointerlen, name, curdata, olddata); } @@ -1009,7 +1046,7 @@ static void reconstruct_elem( else if (countpos != 0) { /* name is an array */ if (oname[countpos] == '[' && strncmp(name, oname, countpos) == 0) { /* basis equal */ - + cursize = DNA_elem_array_size(name); oldsize = DNA_elem_array_size(oname); @@ -1022,7 +1059,7 @@ static void reconstruct_elem( mul = len / oldsize; /* size of single old array element */ mul *= (cursize < oldsize) ? cursize : oldsize; /* smaller of sizes of old and new arrays */ memcpy(curdata, olddata, mul); - + if (oldsize > cursize && strcmp(type, "char") == 0) { /* string had to be truncated, ensure it's still null-terminated */ curdata[mul - 1] = '\0'; @@ -1086,7 +1123,7 @@ static void reconstruct_struct( spo = oldsdna->structs[oldSDNAnr]; elen = oldsdna->typelens[spo[0]]; memcpy(cur, data, elen); - + return; } @@ -1102,7 +1139,7 @@ static void reconstruct_struct( for (a = 0; a < elemcount; a++, spc += 2) { /* convert each field */ type = newsdna->types[spc[0]]; name = newsdna->names[spc[1]]; - + elen = elementsize(newsdna, spc[0], spc[1]); /* test: is type a struct? */ @@ -1110,26 +1147,26 @@ static void reconstruct_struct( /* struct field type */ /* where does the old struct data start (and is there an old one?) */ cpo = (char *)find_elem(oldsdna, type, name, spo, data, &sppo); - + if (cpo) { oldSDNAnr = DNA_struct_find_nr_ex(oldsdna, type, &oldsdna_index_last); curSDNAnr = DNA_struct_find_nr_ex(newsdna, type, &cursdna_index_last); - + /* array! */ mul = DNA_elem_array_size(name); nameo = oldsdna->names[sppo[1]]; mulo = DNA_elem_array_size(nameo); - + eleno = elementsize(oldsdna, sppo[0], sppo[1]); - + elen /= mul; eleno /= mulo; - + while (mul--) { reconstruct_struct(newsdna, oldsdna, compflags, oldSDNAnr, cpo, curSDNAnr, cpc); cpo += eleno; cpc += elen; - + /* new struct array larger than old */ mulo--; if (mulo <= 0) break; @@ -1167,18 +1204,18 @@ void DNA_struct_switch_endian(const SDNA *oldsdna, int oldSDNAnr, char *data) if (oldSDNAnr == -1) return; firststructtypenr = *(oldsdna->structs[0]); - + spo = spc = oldsdna->structs[oldSDNAnr]; elemcount = spo[1]; spc += 2; cur = data; - + for (a = 0; a < elemcount; a++, spc += 2) { type = oldsdna->types[spc[0]]; name = oldsdna->names[spc[1]]; - + /* elementsize = including arraysize */ elen = elementsize(oldsdna, spc[0], spc[1]); @@ -1189,7 +1226,7 @@ void DNA_struct_switch_endian(const SDNA *oldsdna, int oldSDNAnr, char *data) char *cpo = (char *)find_elem(oldsdna, type, name, spo, data, NULL); if (cpo) { oldSDNAnr = DNA_struct_find_nr_ex(oldsdna, type, &oldsdna_index_last); - + mul = DNA_elem_array_size(name); elena = elen / mul; @@ -1255,7 +1292,7 @@ void *DNA_struct_reconstruct( char *cur, *cpc; const char *cpo; const char *type; - + /* oldSDNAnr == structnr, we're looking for the corresponding 'cur' number */ spo = oldsdna->structs[oldSDNAnr]; type = oldsdna->types[spo[0]]; @@ -1304,12 +1341,12 @@ bool DNA_struct_find(const SDNA *sdna, const char *stype) bool DNA_struct_elem_find(const SDNA *sdna, const char *stype, const char *vartype, const char *name) { const int SDNAnr = DNA_struct_find_nr(sdna, stype); - + if (SDNAnr != -1) { const short * const spo = sdna->structs[SDNAnr]; - const char * const cp = find_elem(sdna, vartype, name, spo, NULL, NULL); - - if (cp) { + const bool found = elem_exists(sdna, vartype, name, spo); + + if (found) { return true; } } diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c index 717005c8e9f5..8b4d5a4ab4e0 100644 --- a/source/blender/makesdna/intern/makesdna.c +++ b/source/blender/makesdna/intern/makesdna.c @@ -227,7 +227,7 @@ static int add_type(const char *str, int len) { int nr; char *cp; - + /* first do validity check */ if (str[0] == 0) { return -1; @@ -237,7 +237,7 @@ static int add_type(const char *str, int len) * 'struct SomeStruct* somevar;' <-- correct but we cant handle right now. */ return -1; } - + /* search through type array */ for (nr = 0; nr < nr_types; nr++) { if (strcmp(str, types[nr]) == 0) { @@ -249,7 +249,7 @@ static int add_type(const char *str, int len) return nr; } } - + /* append new type */ if (nr_types == 0) { cp = typedata; @@ -262,13 +262,13 @@ static int add_type(const char *str, int len) typelens_native[nr_types] = len; typelens_32[nr_types] = len; typelens_64[nr_types] = len; - + if (nr_types >= maxnr) { printf("too many types\n"); return nr_types - 1; } nr_types++; - + return nr_types - 1; } @@ -289,7 +289,7 @@ static int add_name(const char *str) const char *name; additional_slen_offset = 0; - + if (str[0] == 0 /* || (str[1] == 0) */) return -1; if (str[0] == '(' && str[1] == '*') { @@ -307,7 +307,7 @@ static int add_name(const char *str) buf[i] = str[i]; i++; } - + /* Another number we need is the extra slen offset. This extra * offset is the overshoot after a space. If there is no * space, no overshoot should be calculated. */ @@ -323,7 +323,7 @@ static int add_name(const char *str) if (debugSDNA > 3) printf("seen %c ( %d)\n" "special after offset%d\n", str[j], str[j], j); - + if (!isfuncptr) { /* multidimensional array pointer case */ if (str[j] == 0) { @@ -333,7 +333,7 @@ static int add_name(const char *str) printf("Error during tokening multidim array pointer\n"); } else if (str[j] == 0) { - if (debugSDNA > 3) printf("offsetting for space\n"); + if (debugSDNA > 3) printf("offsetting for space\n"); /* get additional offset */ k = 0; while (str[j] != ')') { @@ -350,7 +350,7 @@ static int add_name(const char *str) else { printf("Error during tokening function pointer argument list\n"); } - + /* * Put )(void) at the end? Maybe )(). Should check this with * old sdna. Actually, sometimes )(), sometimes )(void...) @@ -364,7 +364,7 @@ static int add_name(const char *str) * * */ buf[i] = 0; - if (debugSDNA > 3) printf("Name before chomping: %s\n", buf); + if (debugSDNA > 3) printf("Name before chomping: %s\n", buf); if ((strncmp(buf, "(*headdraw", 10) == 0) || (strncmp(buf, "(*windraw", 9) == 0) ) { @@ -391,14 +391,14 @@ static int add_name(const char *str) /* normal field: old code */ name = str; } - + /* search name array */ for (nr = 0; nr < nr_names; nr++) { if (strcmp(name, names[nr]) == 0) { return nr; } } - + /* append new type */ if (nr_names == 0) { cp = namedata; @@ -408,13 +408,13 @@ static int add_name(const char *str) } strcpy(cp, name); names[nr_names] = cp; - + if (nr_names >= maxnr) { printf("too many names\n"); return nr_names - 1; } nr_names++; - + return nr_names - 1; } @@ -431,16 +431,16 @@ static short *add_struct(int namecode) len = sp[1]; structs[nr_structs] = sp + 2 * len + 2; } - + sp = structs[nr_structs]; sp[0] = namecode; - + if (nr_structs >= maxnr) { printf("too many structs\n"); return sp; } nr_structs++; - + return sp; } @@ -448,14 +448,14 @@ static int preprocess_include(char *maindata, int len) { int a, newlen, comment = 0; char *cp, *temp, *md; - + /* note: len + 1, last character is a dummy to prevent * comparisons using uninitialized memory */ temp = MEM_mallocN(len + 1, "preprocess_include"); temp[len] = ' '; memcpy(temp, maindata, len); - + /* remove all c++ comments */ /* replace all enters/tabs/etc with spaces */ cp = temp; @@ -471,7 +471,7 @@ static int preprocess_include(char *maindata, int len) if (comment || *cp < 32 || *cp > 128) *cp = 32; cp++; } - + /* data from temp copy to maindata, remove comments and double spaces */ cp = temp; @@ -480,7 +480,7 @@ static int preprocess_include(char *maindata, int len) comment = 0; a = len; while (a--) { - + if (cp[0] == '/' && cp[1] == '*') { comment = 1; cp[0] = cp[1] = 32; @@ -512,7 +512,7 @@ static int preprocess_include(char *maindata, int len) } cp++; } - + MEM_freeN(temp); return newlen; } @@ -553,7 +553,7 @@ static void *read_file_data(const char *filename, int *r_len) fclose(fp); return NULL; } - + fclose(fp); return data; } @@ -567,7 +567,7 @@ static int convert_include(const char *filename) short *structpoin, *sp; char *maindata, *mainend, *md, *md1; bool skip_struct; - + md = maindata = read_file_data(filename, &filelen); if (filelen == -1) { fprintf(stderr, "Can't read file %s\n", filename); @@ -581,12 +581,12 @@ static int convert_include(const char *filename) count = 0; skip_struct = false; while (count < filelen) { - + /* code for skipping a struct: two hashes on 2 lines. (preprocess added a space) */ if (md[0] == '#' && md[1] == ' ' && md[2] == '#') { skip_struct = true; } - + if (md[0] == '{') { md[0] = 0; if (skip_struct) { @@ -597,7 +597,7 @@ static int convert_include(const char *filename) md1 = md - 2; while (*md1 != 32) md1--; /* to beginning of word */ md1++; - + /* we've got a struct name when... */ if (strncmp(md1 - 7, "struct", 6) == 0) { @@ -616,22 +616,22 @@ static int convert_include(const char *filename) md1 = md + 1; while (*md1 != '}') { if (md1 > mainend) break; - + if (*md1 == ',' || *md1 == ' ') *md1 = 0; md1++; } - + /* read types and names until first character that is not '}' */ md1 = md + 1; while (*md1 != '}') { if (md1 > mainend) break; - + /* skip when it says 'struct' or 'unsigned' or 'const' */ if (*md1) { if (strncmp(md1, "struct", 6) == 0) md1 += 7; if (strncmp(md1, "unsigned", 8) == 0) md1 += 9; if (strncmp(md1, "const", 5) == 0) md1 += 6; - + /* we've got a type! */ type = add_type(md1, 0); if (type == -1) { @@ -643,11 +643,11 @@ static int convert_include(const char *filename) md1 += strlen(md1); - + /* read until ';' */ while (*md1 != ';') { if (md1 > mainend) break; - + if (*md1) { /* We've got a name. slen needs * correction for function @@ -666,11 +666,11 @@ static int convert_include(const char *filename) structpoin[1]++; sp += 2; - + md1 += slen; break; } - + name = add_name(md1); slen += additional_slen_offset; @@ -681,7 +681,7 @@ static int convert_include(const char *filename) structpoin[1]++; sp += 2; - + md1 += slen; } md1++; @@ -698,7 +698,7 @@ static int convert_include(const char *filename) count++; md++; } - + MEM_freeN(maindata); return 0; @@ -708,7 +708,7 @@ static int arraysize(const char *str) { int a, mul = 1; const char *cp = NULL; - + for (a = 0; str[a]; a++) { if (str[a] == '[') { cp = &(str[a + 1]); @@ -719,7 +719,7 @@ static int arraysize(const char *str) mul *= atoi(cp); } } - + return mul; } @@ -753,7 +753,7 @@ static int calculate_structlens(int firststruct) while (unknown) { lastunknown = unknown; unknown = 0; - + /* check all structs... */ for (int a = 0; a < nr_structs; a++) { const short *structpoin = structs[a]; @@ -761,13 +761,13 @@ static int calculate_structlens(int firststruct) /* when length is not known... */ if (typelens_native[structtype] == 0) { - + const short *sp = structpoin + 2; int len_native = 0; int len_32 = 0; int len_64 = 0; bool has_pointer = false; - + /* check all elements in struct */ for (int b = 0; b < structpoin[1]; b++, sp += 2) { int type = sp[0]; @@ -839,7 +839,7 @@ static int calculate_structlens(int firststruct) dna_error = 1; } } - + /* Check 2-4-8 aligned. */ if (!check_field_alignment(firststruct, structtype, type, len_32, cp, "32 bit")) { dna_error = 1; @@ -851,7 +851,7 @@ static int calculate_structlens(int firststruct) len_native += mul * typelens_native[type]; len_32 += mul * typelens_32[type]; len_64 += mul * typelens_64[type]; - + } else { len_native = 0; @@ -860,7 +860,7 @@ static int calculate_structlens(int firststruct) break; } } - + if (len_native == 0) { unknown++; } @@ -877,30 +877,30 @@ static int calculate_structlens(int firststruct) dna_error = 1; } } - + if (len_native % 4) { fprintf(stderr, "Sizeerror 4 in struct: %s (add %d bytes)\n", types[structtype], len_native % 4); dna_error = 1; } - + } } } - + if (unknown == lastunknown) break; } - + if (unknown) { fprintf(stderr, "ERROR: still %d structs unknown\n", unknown); if (debugSDNA) { fprintf(stderr, "*** Known structs :\n"); - + for (int a = 0; a < nr_structs; a++) { const short *structpoin = structs[a]; const int structtype = structpoin[0]; - + /* length unknown */ if (typelens_native[structtype] != 0) { fprintf(stderr, " %s\n", types[structtype]); @@ -908,9 +908,9 @@ static int calculate_structlens(int firststruct) } } - + fprintf(stderr, "*** Unknown structs :\n"); - + for (int a = 0; a < nr_structs; a++) { const short *structpoin = structs[a]; const int structtype = structpoin[0]; @@ -936,7 +936,7 @@ static void dna_write(FILE *file, const void *pntr, const int size) const char *data; data = (const char *)pntr; - + for (i = 0; i < size; i++) { fprintf(file, "%d, ", data[i]); linelength++; @@ -957,7 +957,7 @@ void printStructLengths(void) while (unknown) { /*lastunknown = unknown;*/ /*UNUSED*/ unknown = 0; - + /* check all structs... */ for (a = 0; a < nr_structs; a++) { structpoin = structs[a]; @@ -979,17 +979,17 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs /* it a bit. Hope this is enough :) -nzc- */ char str[SDNA_MAX_FILENAME_LENGTH], *cp; int firststruct; - + if (debugSDNA > 0) { fflush(stdout); printf("Running makesdna at debug level %d\n", debugSDNA); } - + /* the longest known struct is 50k, so we assume 100k is sufficent! */ namedata = MEM_callocN(maxdata, "namedata"); typedata = MEM_callocN(maxdata, "typedata"); structdata = MEM_callocN(maxdata, "structdata"); - + /* a maximum of 5000 variables, must be sufficient? */ names = MEM_callocN(sizeof(char *) * maxnr, "names"); types = MEM_callocN(sizeof(char *) * maxnr, "types"); @@ -1024,12 +1024,12 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs /* the defines above shouldn't be output in the padding file... */ firststruct = nr_types; - + /* add all include files defined in the global array */ /* Since the internal file+path name buffer has limited length, I do a */ /* little test first... */ /* Mind the breaking condition here! */ - if (debugSDNA) printf("\tStart of header scan:\n"); + if (debugSDNA) printf("\tStart of header scan:\n"); for (i = 0; *(includefiles[i]) != '\0'; i++) { sprintf(str, "%s%s", baseDirectory, includefiles[i]); if (debugSDNA) printf("\t|-- Converting %s\n", str); @@ -1037,7 +1037,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs return (1); } } - if (debugSDNA) printf("\tFinished scanning %d headers.\n", i); + if (debugSDNA) printf("\tFinished scanning %d headers.\n", i); if (calculate_structlens(firststruct)) { /* error */ @@ -1055,13 +1055,13 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs printf(" %s\n", names[a]); } printf("\n"); - + sp = typelens_native; for (a = 0; a < nr_types; a++, sp++) { printf(" %s %d\n", types[a], *sp); } printf("\n"); - + for (a = 0; a < nr_structs; a++) { sp = structs[a]; printf(" struct %s elems: %d size: %d\n", types[sp[0]], sp[1], typelens_native[sp[0]]); @@ -1077,63 +1077,63 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs /* file writing */ if (debugSDNA > 0) printf("Writing file ... "); - + if (nr_names == 0 || nr_structs == 0) { /* pass */ } else { dna_write(file, "SDNA", 4); - + /* write names */ dna_write(file, "NAME", 4); len = nr_names; dna_write(file, &len, 4); - + /* calculate size of datablock with strings */ cp = names[nr_names - 1]; cp += strlen(names[nr_names - 1]) + 1; /* +1: null-terminator */ len = (intptr_t) (cp - (char *) names[0]); len = (len + 3) & ~3; dna_write(file, names[0], len); - + /* write TYPES */ dna_write(file, "TYPE", 4); len = nr_types; dna_write(file, &len, 4); - + /* calculate datablock size */ cp = types[nr_types - 1]; cp += strlen(types[nr_types - 1]) + 1; /* +1: null-terminator */ len = (intptr_t) (cp - (char *) types[0]); len = (len + 3) & ~3; - + dna_write(file, types[0], len); - + /* WRITE TYPELENGTHS */ dna_write(file, "TLEN", 4); - + len = 2 * nr_types; if (nr_types & 1) len += 2; dna_write(file, typelens_native, len); - + /* WRITE STRUCTS */ dna_write(file, "STRC", 4); len = nr_structs; dna_write(file, &len, 4); - + /* calc datablock size */ sp = structs[nr_structs - 1]; sp += 2 + 2 * (sp[1]); len = (intptr_t) ((char *) sp - (char *) structs[0]); len = (len + 3) & ~3; - + dna_write(file, structs[0], len); - + /* a simple dna padding test */ if (0) { FILE *fp; int a; - + fp = fopen("padding.c", "w"); if (fp == NULL) { /* pass */ @@ -1161,7 +1161,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs } /* end end padding test */ } - + /* write a simple enum with all structs offsets, * should only be accessed via SDNA_TYPE_FROM_STRUCT macro */ { @@ -1175,7 +1175,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs fprintf(file_offsets, "\tSDNA_TYPE_MAX = %d,\n", nr_structs); fprintf(file_offsets, "};\n"); } - + MEM_freeN(namedata); MEM_freeN(typedata); MEM_freeN(structdata); @@ -1187,7 +1187,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs MEM_freeN(structs); if (debugSDNA > 0) printf("done.\n"); - + return(0); } @@ -1255,7 +1255,7 @@ int main(int argc, char **argv) } } - + return(return_status); } @@ -1298,14 +1298,14 @@ int main(int argc, char **argv) #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_modifier_types.h" -#include "DNA_lattice_types.h" +#include "DNA_lattice_types.h" #include "DNA_object_types.h" #include "DNA_object_force_types.h" #include "DNA_object_fluidsim_types.h" #include "DNA_world_types.h" #include "DNA_scene_types.h" #include "DNA_view3d_types.h" -#include "DNA_view2d_types.h" +#include "DNA_view2d_types.h" #include "DNA_space_types.h" #include "DNA_userdef_types.h" #include "DNA_screen_types.h" diff --git a/source/blender/makesrna/RNA_access.h b/source/blender/makesrna/RNA_access.h index 7082ae19849c..641a10dbfae9 100644 --- a/source/blender/makesrna/RNA_access.h +++ b/source/blender/makesrna/RNA_access.h @@ -803,7 +803,7 @@ bool RNA_struct_bl_idname_ok_or_report(struct ReportList *reports, const char *i /* Property Information */ -const char *RNA_property_identifier(PropertyRNA *prop); +const char *RNA_property_identifier(const PropertyRNA *prop); const char *RNA_property_description(PropertyRNA *prop); PropertyType RNA_property_type(PropertyRNA *prop); @@ -876,7 +876,7 @@ bool RNA_property_enum_item_from_value_gettexted( int RNA_property_enum_bitflag_identifiers(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **identifier); StructRNA *RNA_property_pointer_type(PointerRNA *ptr, PropertyRNA *prop); -int RNA_property_pointer_poll(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *value); +bool RNA_property_pointer_poll(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *value); bool RNA_property_editable(PointerRNA *ptr, PropertyRNA *prop); bool RNA_property_editable_info(PointerRNA *ptr, PropertyRNA *prop, const char **r_info); @@ -896,15 +896,15 @@ void RNA_property_update_cache_free(void); /* Property Data */ -int RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop); -void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, int value); -void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, int *values); -int RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index); -void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const int *values); -void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, int value); -int RNA_property_boolean_get_default(PointerRNA *ptr, PropertyRNA *prop); -void RNA_property_boolean_get_default_array(PointerRNA *ptr, PropertyRNA *prop, int *values); -int RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index); +bool RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop); +void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, bool value); +void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, bool *values); +bool RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index); +void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const bool *values); +void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, bool value); +bool RNA_property_boolean_get_default(PointerRNA *ptr, PropertyRNA *prop); +void RNA_property_boolean_get_default_array(PointerRNA *ptr, PropertyRNA *prop, bool *values); +bool RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index); int RNA_property_int_get(PointerRNA *ptr, PropertyRNA *prop); void RNA_property_int_set(PointerRNA *ptr, PropertyRNA *prop, int value); @@ -1038,10 +1038,10 @@ char *RNA_path_property_py(struct PointerRNA *ptr, struct PropertyRNA *prop, int * There is no support for pointers and collections here yet, these can be * added when ID properties support them. */ -int RNA_boolean_get(PointerRNA *ptr, const char *name); -void RNA_boolean_set(PointerRNA *ptr, const char *name, int value); -void RNA_boolean_get_array(PointerRNA *ptr, const char *name, int *values); -void RNA_boolean_set_array(PointerRNA *ptr, const char *name, const int *values); +bool RNA_boolean_get(PointerRNA *ptr, const char *name); +void RNA_boolean_set(PointerRNA *ptr, const char *name, bool value); +void RNA_boolean_get_array(PointerRNA *ptr, const char *name, bool *values); +void RNA_boolean_set_array(PointerRNA *ptr, const char *name, const bool *values); int RNA_int_get(PointerRNA *ptr, const char *name); void RNA_int_set(PointerRNA *ptr, const char *name, int value); diff --git a/source/blender/makesrna/RNA_define.h b/source/blender/makesrna/RNA_define.h index 5f71f2ccdcf5..ee8c19773449 100644 --- a/source/blender/makesrna/RNA_define.h +++ b/source/blender/makesrna/RNA_define.h @@ -76,11 +76,11 @@ void RNA_def_struct_translation_context(StructRNA *srna, const char *context); typedef void StructOrFunctionRNA; -PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont, const char *identifier, int default_value, const char *ui_name, const char *ui_description); -PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont, const char *identifier, int len, int *default_value, const char *ui_name, const char *ui_description); -PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont, const char *identifier, int len, int *default_value, const char *ui_name, const char *ui_description); -PropertyRNA *RNA_def_boolean_layer_member(StructOrFunctionRNA *cont, const char *identifier, int len, int *default_value, const char *ui_name, const char *ui_description); -PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont, const char *identifier, int len, int *default_value, const char *ui_name, const char *ui_description); +PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont, const char *identifier, bool default_value, const char *ui_name, const char *ui_description); +PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description); +PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description); +PropertyRNA *RNA_def_boolean_layer_member(StructOrFunctionRNA *cont, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description); +PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description); PropertyRNA *RNA_def_int(StructOrFunctionRNA *cont, const char *identifier, int default_value, int hardmin, int hardmax, const char *ui_name, const char *ui_description, int softmin, int softmax); PropertyRNA *RNA_def_int_vector(StructOrFunctionRNA *cont, const char *identifier, int len, const int *default_value, int hardmin, int hardmax, const char *ui_name, const char *ui_description, int softmin, int softmax); @@ -152,8 +152,8 @@ void RNA_def_property_string_maxlength(PropertyRNA *prop, int maxlength); void RNA_def_property_struct_type(PropertyRNA *prop, const char *type); void RNA_def_property_struct_runtime(PropertyRNA *prop, StructRNA *type); -void RNA_def_property_boolean_default(PropertyRNA *prop, int value); -void RNA_def_property_boolean_array_default(PropertyRNA *prop, const int *array); +void RNA_def_property_boolean_default(PropertyRNA *prop, bool value); +void RNA_def_property_boolean_array_default(PropertyRNA *prop, const bool *array); void RNA_def_property_int_default(PropertyRNA *prop, int value); void RNA_def_property_int_array_default(PropertyRNA *prop, const int *array); void RNA_def_property_float_default(PropertyRNA *prop, float value); @@ -247,4 +247,3 @@ extern const int rna_matrix_dimsize_4x2[]; #endif #endif /* __RNA_DEFINE_H__ */ - diff --git a/source/blender/makesrna/RNA_enum_types.h b/source/blender/makesrna/RNA_enum_types.h index a7f0a71f5f50..196895451ba8 100644 --- a/source/blender/makesrna/RNA_enum_types.h +++ b/source/blender/makesrna/RNA_enum_types.h @@ -112,6 +112,8 @@ extern const EnumPropertyItem rna_enum_brush_sculpt_tool_items[]; extern const EnumPropertyItem rna_enum_brush_vertex_tool_items[]; extern const EnumPropertyItem rna_enum_brush_image_tool_items[]; +extern const EnumPropertyItem rna_enum_particle_edit_hair_brush_items[]; +extern const EnumPropertyItem rna_enum_particle_edit_disconnected_hair_brush_items[]; extern const EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[]; extern const EnumPropertyItem rna_enum_uv_sculpt_tool_items[]; @@ -209,18 +211,18 @@ int rna_node_tree_type_to_enum(struct bNodeTreeType *typeinfo); int rna_node_tree_idname_to_enum(const char *idname); struct bNodeTreeType *rna_node_tree_type_from_enum(int value); const EnumPropertyItem *rna_node_tree_type_itemf( - void *data, int (*poll)(void *data, struct bNodeTreeType *), bool *r_free); + void *data, bool (*poll)(void *data, struct bNodeTreeType *), bool *r_free); int rna_node_type_to_enum(struct bNodeType *typeinfo); int rna_node_idname_to_enum(const char *idname); struct bNodeType *rna_node_type_from_enum(int value); -const EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, struct bNodeType *), bool *r_free); +const EnumPropertyItem *rna_node_type_itemf(void *data, bool (*poll)(void *data, struct bNodeType *), bool *r_free); int rna_node_socket_type_to_enum(struct bNodeSocketType *typeinfo); int rna_node_socket_idname_to_enum(const char *idname); struct bNodeSocketType *rna_node_socket_type_from_enum(int value); const EnumPropertyItem *rna_node_socket_type_itemf( - void *data, int (*poll)(void *data, struct bNodeSocketType *), bool *r_free); + void *data, bool (*poll)(void *data, struct bNodeSocketType *), bool *r_free); struct bContext; struct PointerRNA; diff --git a/source/blender/makesrna/RNA_types.h b/source/blender/makesrna/RNA_types.h index 912ea0084d76..05a166f46640 100644 --- a/source/blender/makesrna/RNA_types.h +++ b/source/blender/makesrna/RNA_types.h @@ -306,6 +306,7 @@ typedef enum RawPropertyType { PROP_RAW_INT, // XXX - abused for types that are not set, eg. MFace.verts, needs fixing. PROP_RAW_SHORT, PROP_RAW_CHAR, + PROP_RAW_BOOLEAN, PROP_RAW_DOUBLE, PROP_RAW_FLOAT } RawPropertyType; @@ -340,10 +341,10 @@ typedef struct EnumPropertyItem { } EnumPropertyItem; /* extended versions with PropertyRNA argument */ -typedef int (*BooleanPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop); -typedef void (*BooleanPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, int value); -typedef void (*BooleanArrayPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values); -typedef void (*BooleanArrayPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values); +typedef bool (*BooleanPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop); +typedef void (*BooleanPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, bool value); +typedef void (*BooleanArrayPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, bool *values); +typedef void (*BooleanArrayPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, const bool *values); typedef int (*IntPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop); typedef void (*IntPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, int value); typedef void (*IntArrayPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values); diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c index 782346aab186..4bb250bf8462 100644 --- a/source/blender/makesrna/intern/makesrna.c +++ b/source/blender/makesrna/intern/makesrna.c @@ -418,6 +418,7 @@ static const char *rna_type_type_name(PropertyRNA *prop) { switch (prop->type) { case PROP_BOOLEAN: + return "bool"; case PROP_INT: case PROP_ENUM: return "int"; @@ -1617,6 +1618,21 @@ static void rna_def_property_funcs_header(FILE *f, StructRNA *srna, PropertyDefR switch (prop->type) { case PROP_BOOLEAN: + { + if (!prop->arraydimension) { + fprintf(f, "bool %sget(PointerRNA *ptr);\n", func); + fprintf(f, "void %sset(PointerRNA *ptr, bool value);\n", func); + } + else if (prop->arraydimension && prop->totarraylength) { + fprintf(f, "void %sget(PointerRNA *ptr, bool values[%u]);\n", func, prop->totarraylength); + fprintf(f, "void %sset(PointerRNA *ptr, const bool values[%u]);\n", func, prop->totarraylength); + } + else { + fprintf(f, "void %sget(PointerRNA *ptr, bool values[]);\n", func); + fprintf(f, "void %sset(PointerRNA *ptr, const bool values[]);\n", func); + } + break; + } case PROP_INT: { if (!prop->arraydimension) { @@ -1749,15 +1765,15 @@ static void rna_def_property_funcs_header_cpp(FILE *f, StructRNA *srna, Property { if (!prop->arraydimension) { fprintf(f, "\tinline bool %s(void);\n", rna_safe_id(prop->identifier)); - fprintf(f, "\tinline void %s(int value);", rna_safe_id(prop->identifier)); + fprintf(f, "\tinline void %s(bool value);", rna_safe_id(prop->identifier)); } else if (prop->totarraylength) { - fprintf(f, "\tinline Array %s(void);\n", prop->totarraylength, rna_safe_id(prop->identifier)); - fprintf(f, "\tinline void %s(int values[%u]);", rna_safe_id(prop->identifier), prop->totarraylength); + fprintf(f, "\tinline Array %s(void);\n", prop->totarraylength, rna_safe_id(prop->identifier)); + fprintf(f, "\tinline void %s(bool values[%u]);", rna_safe_id(prop->identifier), prop->totarraylength); } else if (prop->getlength) { - fprintf(f, "\tinline DynamicArray %s(void);\n", rna_safe_id(prop->identifier)); - fprintf(f, "\tinline void %s(int values[]);", rna_safe_id(prop->identifier)); + fprintf(f, "\tinline DynamicArray %s(void);\n", rna_safe_id(prop->identifier)); + fprintf(f, "\tinline void %s(bool values[]);", rna_safe_id(prop->identifier)); } break; } @@ -2947,7 +2963,7 @@ static void rna_generate_property(FILE *f, StructRNA *srna, const char *nest, Pr unsigned int i; if (prop->arraydimension && prop->totarraylength) { - fprintf(f, "static int rna_%s%s_%s_default[%u] = {\n\t", srna->identifier, strnest, + fprintf(f, "static bool rna_%s%s_%s_default[%u] = {\n\t", srna->identifier, strnest, prop->identifier, prop->totarraylength); for (i = 0; i < prop->totarraylength; i++) { @@ -3553,22 +3569,22 @@ static const char *cpp_classes = "" "\n" "#define BOOLEAN_PROPERTY(sname, identifier) \\\n" " inline bool sname::identifier(void) { return sname##_##identifier##_get(&ptr) ? true: false; } \\\n" -" inline void sname::identifier(int value) { sname##_##identifier##_set(&ptr, value); }\n" +" inline void sname::identifier(bool value) { sname##_##identifier##_set(&ptr, value); }\n" "\n" "#define BOOLEAN_ARRAY_PROPERTY(sname, size, identifier) \\\n" -" inline Array sname::identifier(void) \\\n" -" { Array ar; sname##_##identifier##_get(&ptr, ar.data); return ar; } \\\n" -" inline void sname::identifier(int values[size]) \\\n" +" inline Array sname::identifier(void) \\\n" +" { Array ar; sname##_##identifier##_get(&ptr, ar.data); return ar; } \\\n" +" inline void sname::identifier(bool values[size]) \\\n" " { sname##_##identifier##_set(&ptr, values); } \\\n" "\n" "#define BOOLEAN_DYNAMIC_ARRAY_PROPERTY(sname, identifier) \\\n" -" inline DynamicArray sname::identifier(void) { \\\n" +" inline DynamicArray sname::identifier(void) { \\\n" " int arraylen[3]; \\\n" " int len = sname##_##identifier##_get_length(&ptr, arraylen); \\\n" -" DynamicArray ar(len); \\\n" +" DynamicArray ar(len); \\\n" " sname##_##identifier##_get(&ptr, ar.data); \\\n" " return ar; } \\\n" -" inline void sname::identifier(int values[]) \\\n" +" inline void sname::identifier(bool values[]) \\\n" " { sname##_##identifier##_set(&ptr, values); } \\\n" "\n" "#define INT_PROPERTY(sname, identifier) \\\n" diff --git a/source/blender/makesrna/intern/rna_ID.c b/source/blender/makesrna/intern/rna_ID.c index d3331e6ca524..6335869ca430 100644 --- a/source/blender/makesrna/intern/rna_ID.c +++ b/source/blender/makesrna/intern/rna_ID.c @@ -121,7 +121,8 @@ void rna_ID_name_set(PointerRNA *ptr, const char *value) { ID *id = (ID *)ptr->data; BLI_strncpy_utf8(id->name + 2, value, sizeof(id->name) - 2); - BLI_libblock_ensure_unique_name(G.main, id->name); + BLI_assert(BKE_id_is_in_gobal_main(id)); + BLI_libblock_ensure_unique_name(G_MAIN, id->name); } static int rna_ID_name_editable(PointerRNA *ptr, const char **UNUSED(r_info)) @@ -238,7 +239,7 @@ IDProperty *rna_ID_idprops(PointerRNA *ptr, bool create) return IDP_GetProperties(ptr->data, create); } -void rna_ID_fake_user_set(PointerRNA *ptr, int value) +void rna_ID_fake_user_set(PointerRNA *ptr, bool value) { ID *id = (ID *)ptr->data; @@ -359,7 +360,7 @@ static void rna_ID_user_remap(ID *id, Main *bmain, ID *new_id) } } -static struct ID *rna_ID_make_local(struct ID *self, Main *bmain, int clear_proxy) +static struct ID *rna_ID_make_local(struct ID *self, Main *bmain, bool clear_proxy) { /* Special case, as we can't rely on id_make_local(); it clears proxies. */ if (!clear_proxy && GS(self->name) == ID_OB) { @@ -414,7 +415,9 @@ int rna_IDMaterials_assign_int(PointerRNA *ptr, int key, const PointerRNA *assig short *totcol = give_totcolp_id(id); Material *mat_id = assign_ptr->id.data; if (totcol && (key >= 0 && key < *totcol)) { - assign_material_id(G.main, id, mat_id, key + 1); + BLI_assert(BKE_id_is_in_gobal_main(id)); + BLI_assert(BKE_id_is_in_gobal_main(&mat_id->id)); + assign_material_id(G_MAIN, id, mat_id, key + 1); return 1; } else { @@ -430,7 +433,8 @@ static void rna_IDMaterials_append_id(ID *id, Main *bmain, Material *ma) WM_main_add_notifier(NC_OBJECT | ND_OB_SHADING, id); } -static Material *rna_IDMaterials_pop_id(ID *id, Main *bmain, ReportList *reports, int index_i, int remove_material_slot) +static Material *rna_IDMaterials_pop_id( + ID *id, Main *bmain, ReportList *reports, int index_i, bool remove_material_slot) { Material *ma; short *totcol = give_totcolp_id(id); @@ -458,7 +462,7 @@ static Material *rna_IDMaterials_pop_id(ID *id, Main *bmain, ReportList *reports return ma; } -static void rna_IDMaterials_clear_id(ID *id, Main *bmain, int remove_material_slot) +static void rna_IDMaterials_clear_id(ID *id, Main *bmain, bool remove_material_slot) { BKE_material_clear_id(bmain, id, remove_material_slot); @@ -470,7 +474,8 @@ static void rna_IDMaterials_clear_id(ID *id, Main *bmain, int remove_material_sl static void rna_Library_filepath_set(PointerRNA *ptr, const char *value) { Library *lib = (Library *)ptr->data; - BKE_library_filepath_set(G.main, lib, value); + BLI_assert(BKE_id_is_in_gobal_main(&lib->id)); + BKE_library_filepath_set(G_MAIN, lib, value); } /* ***** ImagePreview ***** */ @@ -642,7 +647,7 @@ static void rna_ImagePreview_pixels_float_set(PointerRNA *ptr, const float *valu } -static void rna_ImagePreview_is_image_custom_set(PointerRNA *ptr, int value) +static void rna_ImagePreview_is_image_custom_set(PointerRNA *ptr, bool value) { rna_ImagePreview_is_custom_set(ptr, value, ICON_SIZE_PREVIEW); } @@ -688,7 +693,7 @@ static void rna_ImagePreview_image_pixels_float_set(PointerRNA *ptr, const float } -static void rna_ImagePreview_is_icon_custom_set(PointerRNA *ptr, int value) +static void rna_ImagePreview_is_icon_custom_set(PointerRNA *ptr, bool value) { rna_ImagePreview_is_custom_set(ptr, value, ICON_SIZE_ICON); } diff --git a/source/blender/makesrna/intern/rna_access.c b/source/blender/makesrna/intern/rna_access.c index daa01f58e123..d805d6138a70 100644 --- a/source/blender/makesrna/intern/rna_access.c +++ b/source/blender/makesrna/intern/rna_access.c @@ -952,7 +952,7 @@ bool RNA_struct_bl_idname_ok_or_report(ReportList *reports, const char *identifi /* Property Information */ -const char *RNA_property_identifier(PropertyRNA *prop) +const char *RNA_property_identifier(const PropertyRNA *prop) { return rna_ensure_property_identifier(prop); } @@ -1362,7 +1362,7 @@ StructRNA *RNA_property_pointer_type(PointerRNA *ptr, PropertyRNA *prop) return &RNA_UnknownType; } -int RNA_property_pointer_poll(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *value) +bool RNA_property_pointer_poll(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *value) { prop = rna_ensure_property(prop); @@ -2116,17 +2116,17 @@ void RNA_property_update_cache_free(void) /* Property Data */ -int RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop) +bool RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)prop; IDProperty *idprop; - int value; + bool value; BLI_assert(RNA_property_type(prop) == PROP_BOOLEAN); BLI_assert(RNA_property_array_check(prop) == false); if ((idprop = rna_idproperty_check(&prop, ptr))) - value = IDP_Int(idprop); + value = IDP_Int(idprop) != 0; else if (bprop->get) value = bprop->get(ptr); else if (bprop->get_ex) @@ -2139,7 +2139,7 @@ int RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop) return value; } -void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, int value) +void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, bool value) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)prop; IDProperty *idprop; @@ -2149,10 +2149,10 @@ void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, int value) BLI_assert(ELEM(value, false, true)); /* just in case other values are passed */ - if (value) value = 1; + BLI_assert(ELEM(value, true, false)); if ((idprop = rna_idproperty_check(&prop, ptr))) { - IDP_Int(idprop) = value; + IDP_Int(idprop) = (int)value; rna_idproperty_touch(idprop); } else if (bprop->set) { @@ -2173,7 +2173,7 @@ void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, int value) } } -void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, int *values) +void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, bool *values) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)prop; IDProperty *idprop; @@ -2182,10 +2182,15 @@ void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, int *val BLI_assert(RNA_property_array_check(prop) != false); if ((idprop = rna_idproperty_check(&prop, ptr))) { - if (prop->arraydimension == 0) + if (prop->arraydimension == 0) { values[0] = RNA_property_boolean_get(ptr, prop); - else - memcpy(values, IDP_Array(idprop), sizeof(int) * idprop->len); + } + else { + int *values_src = IDP_Array(idprop); + for (uint i = 0; i < idprop->len; i++) { + values[i] = (bool)values_src[i]; + } + } } else if (prop->arraydimension == 0) values[0] = RNA_property_boolean_get(ptr, prop); @@ -2194,16 +2199,16 @@ void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, int *val else if (bprop->getarray_ex) bprop->getarray_ex(ptr, prop, values); else if (bprop->defaultarray) - memcpy(values, bprop->defaultarray, sizeof(int) * prop->totarraylength); + memcpy(values, bprop->defaultarray, sizeof(bool) * prop->totarraylength); else - memset(values, 0, sizeof(int) * prop->totarraylength); + memset(values, 0, sizeof(bool) * prop->totarraylength); } -int RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index) +bool RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index) { - int tmp[RNA_MAX_ARRAY_LENGTH]; + bool tmp[RNA_MAX_ARRAY_LENGTH]; int len = rna_ensure_property_array_length(ptr, prop); - int value; + bool value; BLI_assert(RNA_property_type(prop) == PROP_BOOLEAN); BLI_assert(RNA_property_array_check(prop) != false); @@ -2215,9 +2220,9 @@ int RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index value = tmp[index]; } else { - int *tmparray; + bool *tmparray; - tmparray = MEM_mallocN(sizeof(int) * len, __func__); + tmparray = MEM_mallocN(sizeof(bool) * len, __func__); RNA_property_boolean_get_array(ptr, prop, tmparray); value = tmparray[index]; MEM_freeN(tmparray); @@ -2228,7 +2233,7 @@ int RNA_property_boolean_get_index(PointerRNA *ptr, PropertyRNA *prop, int index return value; } -void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const int *values) +void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const bool *values) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)prop; IDProperty *idprop; @@ -2237,11 +2242,15 @@ void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const in BLI_assert(RNA_property_array_check(prop) != false); if ((idprop = rna_idproperty_check(&prop, ptr))) { - if (prop->arraydimension == 0) + if (prop->arraydimension == 0) { IDP_Int(idprop) = values[0]; - else - memcpy(IDP_Array(idprop), values, sizeof(int) * idprop->len); - + } + else { + int *values_dst = IDP_Array(idprop); + for (uint i = 0; i < idprop->len; i++) { + values_dst[i] = (int)values[i]; + } + } rna_idproperty_touch(idprop); } else if (prop->arraydimension == 0) @@ -2261,14 +2270,17 @@ void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const in if (group) { idprop = IDP_New(IDP_ARRAY, &val, prop->identifier); IDP_AddToGroup(group, idprop); - memcpy(IDP_Array(idprop), values, sizeof(int) * idprop->len); + int *values_dst = IDP_Array(idprop); + for (uint i = 0; i < idprop->len; i++) { + values_dst[i] = (int)values[i]; + } } } } -void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, int value) +void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, bool value) { - int tmp[RNA_MAX_ARRAY_LENGTH]; + bool tmp[RNA_MAX_ARRAY_LENGTH]; int len = rna_ensure_property_array_length(ptr, prop); BLI_assert(RNA_property_type(prop) == PROP_BOOLEAN); @@ -2283,9 +2295,9 @@ void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int inde RNA_property_boolean_set_array(ptr, prop, tmp); } else { - int *tmparray; + bool *tmparray; - tmparray = MEM_mallocN(sizeof(int) * len, __func__); + tmparray = MEM_mallocN(sizeof(bool) * len, __func__); RNA_property_boolean_get_array(ptr, prop, tmparray); tmparray[index] = value; RNA_property_boolean_set_array(ptr, prop, tmparray); @@ -2293,7 +2305,7 @@ void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int inde } } -int RNA_property_boolean_get_default(PointerRNA *UNUSED(ptr), PropertyRNA *prop) +bool RNA_property_boolean_get_default(PointerRNA *UNUSED(ptr), PropertyRNA *prop) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)rna_ensure_property(prop); @@ -2304,7 +2316,7 @@ int RNA_property_boolean_get_default(PointerRNA *UNUSED(ptr), PropertyRNA *prop) return bprop->defaultvalue; } -void RNA_property_boolean_get_default_array(PointerRNA *UNUSED(ptr), PropertyRNA *prop, int *values) +void RNA_property_boolean_get_default_array(PointerRNA *UNUSED(ptr), PropertyRNA *prop, bool *values) { BoolPropertyRNA *bprop = (BoolPropertyRNA *)rna_ensure_property(prop); @@ -2314,14 +2326,14 @@ void RNA_property_boolean_get_default_array(PointerRNA *UNUSED(ptr), PropertyRNA if (prop->arraydimension == 0) values[0] = bprop->defaultvalue; else if (bprop->defaultarray) - memcpy(values, bprop->defaultarray, sizeof(int) * prop->totarraylength); + memcpy(values, bprop->defaultarray, sizeof(bool) * prop->totarraylength); else - memset(values, 0, sizeof(int) * prop->totarraylength); + memset(values, 0, sizeof(bool) * prop->totarraylength); } -int RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index) +bool RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index) { - int tmp[RNA_MAX_ARRAY_LENGTH]; + bool tmp[RNA_MAX_ARRAY_LENGTH]; int len = rna_ensure_property_array_length(ptr, prop); BLI_assert(RNA_property_type(prop) == PROP_BOOLEAN); @@ -2334,9 +2346,9 @@ int RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, i return tmp[index]; } else { - int *tmparray, value; + bool *tmparray, value; - tmparray = MEM_mallocN(sizeof(int) * len, __func__); + tmparray = MEM_mallocN(sizeof(bool) * len, __func__); RNA_property_boolean_get_default_array(ptr, prop, tmparray); value = tmparray[index]; MEM_freeN(tmparray); @@ -3727,6 +3739,7 @@ int RNA_property_collection_raw_array(PointerRNA *ptr, PropertyRNA *prop, Proper case PROP_RAW_CHAR: var = (dtype)((char *)raw.array)[a]; break; \ case PROP_RAW_SHORT: var = (dtype)((short *)raw.array)[a]; break; \ case PROP_RAW_INT: var = (dtype)((int *)raw.array)[a]; break; \ + case PROP_RAW_BOOLEAN: var = (dtype)((bool *)raw.array)[a]; break; \ case PROP_RAW_FLOAT: var = (dtype)((float *)raw.array)[a]; break; \ case PROP_RAW_DOUBLE: var = (dtype)((double *)raw.array)[a]; break; \ default: var = (dtype)0; \ @@ -3739,6 +3752,7 @@ int RNA_property_collection_raw_array(PointerRNA *ptr, PropertyRNA *prop, Proper case PROP_RAW_CHAR: ((char *)raw.array)[a] = (char)var; break; \ case PROP_RAW_SHORT: ((short *)raw.array)[a] = (short)var; break; \ case PROP_RAW_INT: ((int *)raw.array)[a] = (int)var; break; \ + case PROP_RAW_BOOLEAN: ((bool *)raw.array)[a] = (bool)var; break; \ case PROP_RAW_FLOAT: ((float *)raw.array)[a] = (float)var; break; \ case PROP_RAW_DOUBLE: ((double *)raw.array)[a] = (double)var; break; \ default: break; \ @@ -3751,6 +3765,7 @@ int RNA_raw_type_sizeof(RawPropertyType type) case PROP_RAW_CHAR: return sizeof(char); case PROP_RAW_SHORT: return sizeof(short); case PROP_RAW_INT: return sizeof(int); + case PROP_RAW_BOOLEAN: return sizeof(bool); case PROP_RAW_FLOAT: return sizeof(float); case PROP_RAW_DOUBLE: return sizeof(double); default: return 0; @@ -3852,8 +3867,9 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro int err = 0, j, a = 0; int needconv = 1; - if (((itemtype == PROP_BOOLEAN || itemtype == PROP_INT) && in.type == PROP_RAW_INT) || - (itemtype == PROP_FLOAT && in.type == PROP_RAW_FLOAT)) + if (((itemtype == PROP_INT) && (in.type == PROP_RAW_INT)) || + ((itemtype == PROP_BOOLEAN) && (in.type == PROP_RAW_BOOLEAN)) || + ((itemtype == PROP_FLOAT) && (in.type == PROP_RAW_FLOAT))) { /* avoid creating temporary buffer if the data type match */ needconv = 0; @@ -3903,7 +3919,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro case PROP_BOOLEAN: { int b; - RAW_GET(int, b, in, a); + RAW_GET(bool, b, in, a); RNA_property_boolean_set(&itemptr, iprop, b); break; } @@ -3930,7 +3946,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro case PROP_BOOLEAN: { int b = RNA_property_boolean_get(&itemptr, iprop); - RAW_SET(int, in, a, b); + RAW_SET(bool, in, a, b); break; } case PROP_INT: @@ -3968,7 +3984,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro case PROP_BOOLEAN: { for (j = 0; j < itemlen; j++, a++) - RAW_GET(int, ((int *)tmparray)[j], in, a); + RAW_GET(bool, ((bool *)tmparray)[j], in, a); RNA_property_boolean_set_array(&itemptr, iprop, tmparray); break; } @@ -3996,7 +4012,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro { RNA_property_boolean_get_array(&itemptr, iprop, tmparray); for (j = 0; j < itemlen; j++, a++) - RAW_SET(int, in, a, ((int *)tmparray)[j]); + RAW_SET(int, in, a, ((bool *)tmparray)[j]); break; } case PROP_INT: @@ -4023,7 +4039,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro switch (itemtype) { case PROP_BOOLEAN: { - RNA_property_boolean_set_array(&itemptr, iprop, &((int *)in.array)[a]); + RNA_property_boolean_set_array(&itemptr, iprop, &((bool *)in.array)[a]); a += itemlen; break; } @@ -4047,7 +4063,7 @@ static int rna_raw_access(ReportList *reports, PointerRNA *ptr, PropertyRNA *pro switch (itemtype) { case PROP_BOOLEAN: { - RNA_property_boolean_get_array(&itemptr, iprop, &((int *)in.array)[a]); + RNA_property_boolean_get_array(&itemptr, iprop, &((bool *)in.array)[a]); a += itemlen; break; } @@ -4086,7 +4102,7 @@ RawPropertyType RNA_property_raw_type(PropertyRNA *prop) /* this property has no raw access, yet we try to provide a raw type to help building the array */ switch (prop->type) { case PROP_BOOLEAN: - return PROP_RAW_INT; + return PROP_RAW_BOOLEAN; case PROP_INT: return PROP_RAW_INT; case PROP_FLOAT: @@ -5276,7 +5292,7 @@ char *RNA_path_property_py(PointerRNA *UNUSED(ptr), PropertyRNA *prop, int index /* Quick name based property access */ -int RNA_boolean_get(PointerRNA *ptr, const char *name) +bool RNA_boolean_get(PointerRNA *ptr, const char *name) { PropertyRNA *prop = RNA_struct_find_property(ptr, name); @@ -5289,7 +5305,7 @@ int RNA_boolean_get(PointerRNA *ptr, const char *name) } } -void RNA_boolean_set(PointerRNA *ptr, const char *name, int value) +void RNA_boolean_set(PointerRNA *ptr, const char *name, bool value) { PropertyRNA *prop = RNA_struct_find_property(ptr, name); @@ -5299,7 +5315,7 @@ void RNA_boolean_set(PointerRNA *ptr, const char *name, int value) printf("%s: %s.%s not found.\n", __func__, ptr->type->identifier, name); } -void RNA_boolean_get_array(PointerRNA *ptr, const char *name, int *values) +void RNA_boolean_get_array(PointerRNA *ptr, const char *name, bool *values) { PropertyRNA *prop = RNA_struct_find_property(ptr, name); @@ -5309,7 +5325,7 @@ void RNA_boolean_get_array(PointerRNA *ptr, const char *name, int *values) printf("%s: %s.%s not found.\n", __func__, ptr->type->identifier, name); } -void RNA_boolean_set_array(PointerRNA *ptr, const char *name, const int *values) +void RNA_boolean_set_array(PointerRNA *ptr, const char *name, const bool *values) { PropertyRNA *prop = RNA_struct_find_property(ptr, name); @@ -5937,8 +5953,8 @@ char *RNA_property_as_string(bContext *C, PointerRNA *ptr, PropertyRNA *prop, in BLI_dynstr_append(dynstr, bool_as_py_string(RNA_property_boolean_get_index(ptr, prop, index))); } else { - int fixedbuf[RNA_MAX_ARRAY_LENGTH]; - int *buf = ARRAY_SIZE(fixedbuf) >= len ? fixedbuf : MEM_mallocN(sizeof(*buf) * len, __func__); + bool fixedbuf[RNA_MAX_ARRAY_LENGTH]; + bool *buf = ARRAY_SIZE(fixedbuf) >= len ? fixedbuf : MEM_mallocN(sizeof(*buf) * len, __func__); RNA_property_boolean_get_array(ptr, prop, buf); BLI_dynstr_append(dynstr, "("); @@ -6559,9 +6575,9 @@ static int rna_function_parameter_parse(PointerRNA *ptr, PropertyRNA *prop, Prop } if (len == 0) - *((int *)dest) = *((int *)src); + *((bool *)dest) = *((bool *)src); else - memcpy(dest, src, len * sizeof(int)); + memcpy(dest, src, len * sizeof(bool)); break; } @@ -6909,7 +6925,7 @@ bool RNA_property_reset(PointerRNA *ptr, PropertyRNA *prop, int index) case PROP_BOOLEAN: if (len) { if (index == -1) { - int *tmparray = MEM_callocN(sizeof(int) * len, "reset_defaults - boolean"); + bool *tmparray = MEM_callocN(sizeof(bool) * len, "reset_defaults - boolean"); RNA_property_boolean_get_default_array(ptr, prop, tmparray); RNA_property_boolean_set_array(ptr, prop, tmparray); @@ -7027,7 +7043,7 @@ bool RNA_property_copy(PointerRNA *ptr, PointerRNA *fromptr, PropertyRNA *prop, case PROP_BOOLEAN: if (len) { if (index == -1) { - int *tmparray = MEM_callocN(sizeof(int) * len, "copy - boolean"); + bool *tmparray = MEM_callocN(sizeof(bool) * len, "copy - boolean"); RNA_property_boolean_get_array(fromptr, fromprop, tmparray); RNA_property_boolean_set_array(ptr, prop, tmparray); @@ -7159,17 +7175,17 @@ bool RNA_property_equals(PointerRNA *a, PointerRNA *b, PropertyRNA *prop, eRNAEq case PROP_BOOLEAN: { if (len) { - int fixed_a[16], fixed_b[16]; - int *array_a, *array_b; + bool fixed_a[16], fixed_b[16]; + bool *array_a, *array_b; bool equals; - array_a = (len > 16) ? MEM_mallocN(sizeof(int) * len, "RNA equals") : fixed_a; - array_b = (len > 16) ? MEM_mallocN(sizeof(int) * len, "RNA equals") : fixed_b; + array_a = (len > 16) ? MEM_mallocN(sizeof(bool) * len, "RNA equals") : fixed_a; + array_b = (len > 16) ? MEM_mallocN(sizeof(bool) * len, "RNA equals") : fixed_b; RNA_property_boolean_get_array(a, prop, array_a); RNA_property_boolean_get_array(b, prop, array_b); - equals = memcmp(array_a, array_b, sizeof(int) * len) == 0; + equals = memcmp(array_a, array_b, sizeof(bool) * len) == 0; if (array_a != fixed_a) MEM_freeN(array_a); if (array_b != fixed_b) MEM_freeN(array_b); diff --git a/source/blender/makesrna/intern/rna_action.c b/source/blender/makesrna/intern/rna_action.c index 6985cb543597..675ed42a6d2a 100644 --- a/source/blender/makesrna/intern/rna_action.c +++ b/source/blender/makesrna/intern/rna_action.c @@ -223,7 +223,7 @@ static void rna_Action_frame_range_get(PointerRNA *ptr, float *values) /* used to check if an action (value pointer) is suitable to be assigned to the ID-block that is ptr */ -int rna_Action_id_poll(PointerRNA *ptr, PointerRNA value) +bool rna_Action_id_poll(PointerRNA *ptr, PointerRNA value) { ID *srcId = (ID *)ptr->id.data; bAction *act = (bAction *)value.id.data; @@ -243,7 +243,7 @@ int rna_Action_id_poll(PointerRNA *ptr, PointerRNA value) } /* used to check if an action (value pointer) can be assigned to Action Editor given current mode */ -int rna_Action_actedit_assign_poll(PointerRNA *ptr, PointerRNA value) +bool rna_Action_actedit_assign_poll(PointerRNA *ptr, PointerRNA value) { SpaceAction *saction = (SpaceAction *)ptr->data; bAction *act = (bAction *)value.id.data; diff --git a/source/blender/makesrna/intern/rna_actuator.c b/source/blender/makesrna/intern/rna_actuator.c index 9c3af7c61fb0..22fdbaa9ba1c 100644 --- a/source/blender/makesrna/intern/rna_actuator.c +++ b/source/blender/makesrna/intern/rna_actuator.c @@ -332,7 +332,7 @@ static void rna_ConstraintActuator_spring_set(struct PointerRNA *ptr, float valu } /* ConstraintActuator uses the same property for Material and Property. * Therefore we need to clear the property when "use_material_detect" mode changes */ -static void rna_Actuator_constraint_detect_material_set(struct PointerRNA *ptr, int value) +static void rna_Actuator_constraint_detect_material_set(struct PointerRNA *ptr, bool value) { bActuator *act = (bActuator *)ptr->data; bConstraintActuator *ca = act->data; @@ -345,12 +345,12 @@ static void rna_Actuator_constraint_detect_material_set(struct PointerRNA *ptr, } } -static void rna_ActionActuator_add_set(struct PointerRNA *ptr, int value) +static void rna_ActionActuator_add_set(struct PointerRNA *ptr, bool value) { bActuator *act = (bActuator *)ptr->data; bActionActuator *aa = act->data; - if (value == 1) { + if (value) { aa->flag &= ~ACT_IPOFORCE; aa->flag |= ACT_IPOADD; } @@ -359,12 +359,12 @@ static void rna_ActionActuator_add_set(struct PointerRNA *ptr, int value) } } -static void rna_ActionActuator_force_set(struct PointerRNA *ptr, int value) +static void rna_ActionActuator_force_set(struct PointerRNA *ptr, bool value) { bActuator *act = (bActuator *)ptr->data; bActionActuator *aa = act->data; - if (value == 1) { + if (value) { aa->flag &= ~ACT_IPOADD; aa->flag |= ACT_IPOFORCE; } @@ -413,7 +413,7 @@ static void rna_ObjectActuator_integralcoefficient_set(struct PointerRNA *ptr, f oa->forcerot[0] = 60.0f * oa->forcerot[1]; } -static void rna_StateActuator_state_set(PointerRNA *ptr, const int *values) +static void rna_StateActuator_state_set(PointerRNA *ptr, const bool *values) { bActuator *act = (bActuator *)ptr->data; bStateActuator *sa = act->data; diff --git a/source/blender/makesrna/intern/rna_actuator_api.c b/source/blender/makesrna/intern/rna_actuator_api.c index 23fdd8a1d5bd..0047d7257cb4 100644 --- a/source/blender/makesrna/intern/rna_actuator_api.c +++ b/source/blender/makesrna/intern/rna_actuator_api.c @@ -74,4 +74,3 @@ void RNA_api_actuator(StructRNA *srna) } #endif - diff --git a/source/blender/makesrna/intern/rna_animation.c b/source/blender/makesrna/intern/rna_animation.c index 23071288c0af..6f1445d31ef0 100644 --- a/source/blender/makesrna/intern/rna_animation.c +++ b/source/blender/makesrna/intern/rna_animation.c @@ -118,7 +118,7 @@ static void rna_AnimData_action_set(PointerRNA *ptr, PointerRNA value) } } -static void rna_AnimData_tweakmode_set(PointerRNA *ptr, const int value) +static void rna_AnimData_tweakmode_set(PointerRNA *ptr, const bool value) { AnimData *adt = (AnimData *)ptr->data; @@ -138,7 +138,7 @@ static void rna_AnimData_tweakmode_set(PointerRNA *ptr, const int value) /* ****************************** */ /* wrapper for poll callback */ -static int RKS_POLL_rna_internal(KeyingSetInfo *ksi, bContext *C) +static bool RKS_POLL_rna_internal(KeyingSetInfo *ksi, bContext *C) { extern FunctionRNA rna_KeyingSetInfo_poll_func; @@ -162,7 +162,7 @@ static int RKS_POLL_rna_internal(KeyingSetInfo *ksi, bContext *C) /* read the result */ RNA_parameter_get_lookup(&list, "ok", &ret); - ok = *(int *)ret; + ok = *(bool *)ret; } RNA_parameter_list_free(&list); diff --git a/source/blender/makesrna/intern/rna_armature.c b/source/blender/makesrna/intern/rna_armature.c index b3b69e9c58a6..7af3746b8551 100644 --- a/source/blender/makesrna/intern/rna_armature.c +++ b/source/blender/makesrna/intern/rna_armature.c @@ -238,7 +238,7 @@ static IDProperty *rna_EditBone_idprops(PointerRNA *ptr, bool create) return ebone->prop; } -static void rna_bone_layer_set(int *layer, const int *values) +static void rna_bone_layer_set(int *layer, const bool *values) { int i, tot = 0; @@ -256,13 +256,13 @@ static void rna_bone_layer_set(int *layer, const int *values) } } -static void rna_Bone_layer_set(PointerRNA *ptr, const int *values) +static void rna_Bone_layer_set(PointerRNA *ptr, const bool *values) { Bone *bone = (Bone *)ptr->data; rna_bone_layer_set(&bone->layer, values); } -static void rna_Armature_layer_set(PointerRNA *ptr, const int *values) +static void rna_Armature_layer_set(PointerRNA *ptr, const bool *values) { bArmature *arm = (bArmature *)ptr->data; int i, tot = 0; @@ -315,7 +315,8 @@ static void rna_EditBone_name_set(PointerRNA *ptr, const char *value) BLI_strncpy_utf8(newname, value, sizeof(ebone->name)); BLI_strncpy(oldname, ebone->name, sizeof(ebone->name)); - ED_armature_bone_rename(G.main, arm, oldname, newname); + BLI_assert(BKE_id_is_in_gobal_main(&arm->id)); + ED_armature_bone_rename(G_MAIN, arm, oldname, newname); } static void rna_Bone_name_set(PointerRNA *ptr, const char *value) @@ -328,10 +329,11 @@ static void rna_Bone_name_set(PointerRNA *ptr, const char *value) BLI_strncpy_utf8(newname, value, sizeof(bone->name)); BLI_strncpy(oldname, bone->name, sizeof(bone->name)); - ED_armature_bone_rename(G.main, arm, oldname, newname); + BLI_assert(BKE_id_is_in_gobal_main(&arm->id)); + ED_armature_bone_rename(G_MAIN, arm, oldname, newname); } -static void rna_EditBone_layer_set(PointerRNA *ptr, const int values[]) +static void rna_EditBone_layer_set(PointerRNA *ptr, const bool values[]) { EditBone *data = (EditBone *)(ptr->data); rna_bone_layer_set(&data->layer, values); @@ -353,7 +355,7 @@ static void rna_EditBone_connected_check(EditBone *ebone) } } -static void rna_EditBone_connected_set(PointerRNA *ptr, int value) +static void rna_EditBone_connected_set(PointerRNA *ptr, bool value) { EditBone *ebone = (EditBone *)(ptr->data); @@ -473,7 +475,7 @@ static void rna_Armature_bones_next(CollectionPropertyIterator *iter) iter->valid = (internal->link != NULL); } -static int rna_Armature_is_editmode_get(PointerRNA *ptr) +static bool rna_Armature_is_editmode_get(PointerRNA *ptr) { bArmature *arm = (bArmature *)ptr->id.data; return (arm->edbo != NULL); diff --git a/source/blender/makesrna/intern/rna_brush.c b/source/blender/makesrna/intern/rna_brush.c index 71cdb24ffdc8..bb204bf8c815 100644 --- a/source/blender/makesrna/intern/rna_brush.c +++ b/source/blender/makesrna/intern/rna_brush.c @@ -135,25 +135,25 @@ const EnumPropertyItem rna_enum_brush_image_tool_items[] = { #include "WM_api.h" -static int rna_SculptToolCapabilities_has_accumulate_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_accumulate_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return SCULPT_TOOL_HAS_ACCUMULATE(br->sculpt_tool); } -static int rna_SculptToolCapabilities_has_auto_smooth_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_auto_smooth_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return !ELEM(br->sculpt_tool, SCULPT_TOOL_MASK, SCULPT_TOOL_SMOOTH); } -static int rna_SculptToolCapabilities_has_height_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_height_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return br->sculpt_tool == SCULPT_TOOL_LAYER; } -static int rna_SculptToolCapabilities_has_jitter_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_jitter_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (!(br->flag & BRUSH_ANCHORED) && @@ -163,19 +163,19 @@ static int rna_SculptToolCapabilities_has_jitter_get(PointerRNA *ptr) SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB)); } -static int rna_SculptToolCapabilities_has_normal_weight_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_normal_weight_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return SCULPT_TOOL_HAS_NORMAL_WEIGHT(br->sculpt_tool); } -static int rna_SculptToolCapabilities_has_rake_factor_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_rake_factor_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return SCULPT_TOOL_HAS_RAKE(br->sculpt_tool); } -static int rna_BrushCapabilities_has_overlay_get(PointerRNA *ptr) +static bool rna_BrushCapabilities_has_overlay_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return ELEM(br->mtex.brush_map_mode, @@ -184,26 +184,26 @@ static int rna_BrushCapabilities_has_overlay_get(PointerRNA *ptr) MTEX_MAP_MODE_STENCIL); } -static int rna_SculptToolCapabilities_has_persistence_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_persistence_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return br->sculpt_tool == SCULPT_TOOL_LAYER; } -static int rna_SculptToolCapabilities_has_pinch_factor_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_pinch_factor_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return ELEM(br->sculpt_tool, SCULPT_TOOL_BLOB, SCULPT_TOOL_CREASE, SCULPT_TOOL_SNAKE_HOOK); } -static int rna_SculptToolCapabilities_has_plane_offset_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_plane_offset_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return ELEM(br->sculpt_tool, SCULPT_TOOL_CLAY, SCULPT_TOOL_CLAY_STRIPS, SCULPT_TOOL_FILL, SCULPT_TOOL_FLATTEN, SCULPT_TOOL_SCRAPE); } -static int rna_SculptToolCapabilities_has_random_texture_angle_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_random_texture_angle_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (!ELEM(br->sculpt_tool, @@ -211,7 +211,7 @@ static int rna_SculptToolCapabilities_has_random_texture_angle_get(PointerRNA *p SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB)); } -static int rna_TextureCapabilities_has_random_texture_angle_get(PointerRNA *ptr) +static bool rna_TextureCapabilities_has_random_texture_angle_get(PointerRNA *ptr) { MTex *mtex = (MTex *)ptr->data; return ELEM(mtex->brush_map_mode, @@ -221,13 +221,13 @@ static int rna_TextureCapabilities_has_random_texture_angle_get(PointerRNA *ptr) } -static int rna_BrushCapabilities_has_random_texture_angle_get(PointerRNA *ptr) +static bool rna_BrushCapabilities_has_random_texture_angle_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return !(br->flag & BRUSH_ANCHORED); } -static int rna_SculptToolCapabilities_has_sculpt_plane_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_sculpt_plane_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return !ELEM(br->sculpt_tool, SCULPT_TOOL_INFLATE, @@ -235,13 +235,13 @@ static int rna_SculptToolCapabilities_has_sculpt_plane_get(PointerRNA *ptr) SCULPT_TOOL_SMOOTH); } -static int rna_SculptToolCapabilities_has_secondary_color_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_secondary_color_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return BKE_brush_sculpt_has_secondary_color(br); } -static int rna_SculptToolCapabilities_has_smooth_stroke_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_smooth_stroke_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (!(br->flag & BRUSH_ANCHORED) && @@ -253,7 +253,7 @@ static int rna_SculptToolCapabilities_has_smooth_stroke_get(PointerRNA *ptr) SCULPT_TOOL_SNAKE_HOOK, SCULPT_TOOL_THUMB)); } -static int rna_BrushCapabilities_has_smooth_stroke_get(PointerRNA *ptr) +static bool rna_BrushCapabilities_has_smooth_stroke_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (!(br->flag & BRUSH_ANCHORED) && @@ -262,7 +262,7 @@ static int rna_BrushCapabilities_has_smooth_stroke_get(PointerRNA *ptr) !(br->flag & BRUSH_CURVE)); } -static int rna_SculptToolCapabilities_has_space_attenuation_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_space_attenuation_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return ((br->flag & (BRUSH_SPACE | BRUSH_LINE | BRUSH_CURVE)) && @@ -270,38 +270,38 @@ static int rna_SculptToolCapabilities_has_space_attenuation_get(PointerRNA *ptr) SCULPT_TOOL_SMOOTH, SCULPT_TOOL_SNAKE_HOOK)); } -static int rna_ImapaintToolCapabilities_has_space_attenuation_get(PointerRNA *ptr) +static bool rna_ImapaintToolCapabilities_has_space_attenuation_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (br->flag & (BRUSH_SPACE | BRUSH_LINE | BRUSH_CURVE)) && br->imagepaint_tool != PAINT_TOOL_FILL; } -static int rna_BrushCapabilities_has_spacing_get(PointerRNA *ptr) +static bool rna_BrushCapabilities_has_spacing_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return (!(br->flag & BRUSH_ANCHORED)); } -static int rna_SculptToolCapabilities_has_strength_pressure_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_strength_pressure_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return !ELEM(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_SNAKE_HOOK); } -static int rna_TextureCapabilities_has_texture_angle_get(PointerRNA *ptr) +static bool rna_TextureCapabilities_has_texture_angle_get(PointerRNA *ptr) { MTex *mtex = (MTex *)ptr->data; return mtex->brush_map_mode != MTEX_MAP_MODE_3D; } -static int rna_SculptToolCapabilities_has_gravity_get(PointerRNA *ptr) +static bool rna_SculptToolCapabilities_has_gravity_get(PointerRNA *ptr) { Brush *br = (Brush *)ptr->data; return !ELEM(br->sculpt_tool, SCULPT_TOOL_MASK, SCULPT_TOOL_SMOOTH); } -static int rna_TextureCapabilities_has_texture_angle_source_get(PointerRNA *ptr) +static bool rna_TextureCapabilities_has_texture_angle_source_get(PointerRNA *ptr) { MTex *mtex = (MTex *)ptr->data; return ELEM(mtex->brush_map_mode, @@ -310,7 +310,7 @@ static int rna_TextureCapabilities_has_texture_angle_source_get(PointerRNA *ptr) MTEX_MAP_MODE_RANDOM); } -static int rna_ImapaintToolCapabilities_has_accumulate_get(PointerRNA *ptr) +static bool rna_ImapaintToolCapabilities_has_accumulate_get(PointerRNA *ptr) { /* only support for draw tool */ Brush *br = (Brush *)ptr->data; @@ -325,7 +325,7 @@ static int rna_ImapaintToolCapabilities_has_accumulate_get(PointerRNA *ptr) ) ? false : true; } -static int rna_ImapaintToolCapabilities_has_radius_get(PointerRNA *ptr) +static bool rna_ImapaintToolCapabilities_has_radius_get(PointerRNA *ptr) { /* only support for draw tool */ Brush *br = (Brush *)ptr->data; @@ -456,7 +456,7 @@ static void rna_Brush_set_size(PointerRNA *ptr, int value) brush->size = value; } -static void rna_Brush_use_gradient_set(PointerRNA *ptr, int value) +static void rna_Brush_use_gradient_set(PointerRNA *ptr, bool value) { Brush *br = (Brush *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_camera_api.c b/source/blender/makesrna/intern/rna_camera_api.c index ae15c58dd292..d1b25239cbea 100644 --- a/source/blender/makesrna/intern/rna_camera_api.c +++ b/source/blender/makesrna/intern/rna_camera_api.c @@ -85,4 +85,3 @@ void RNA_api_camera(StructRNA *srna) } #endif - diff --git a/source/blender/makesrna/intern/rna_color.c b/source/blender/makesrna/intern/rna_color.c index 1d85ba439956..aa1164068d8d 100644 --- a/source/blender/makesrna/intern/rna_color.c +++ b/source/blender/makesrna/intern/rna_color.c @@ -85,7 +85,7 @@ static void rna_CurveMapping_curves_begin(CollectionPropertyIterator *iter, Poin rna_iterator_array_begin(iter, cumap->cm, sizeof(CurveMap), rna_CurveMapping_curves_length(ptr), 0, NULL); } -static void rna_CurveMapping_clip_set(PointerRNA *ptr, int value) +static void rna_CurveMapping_clip_set(PointerRNA *ptr, bool value) { CurveMapping *cumap = (CurveMapping *)ptr->data; @@ -521,7 +521,7 @@ static const EnumPropertyItem *rna_ColorManagedViewSettings_look_itemf( return items; } -static void rna_ColorManagedViewSettings_use_curves_set(PointerRNA *ptr, int value) +static void rna_ColorManagedViewSettings_use_curves_set(PointerRNA *ptr, bool value) { ColorManagedViewSettings *view_settings = (ColorManagedViewSettings *) ptr->data; @@ -1128,8 +1128,9 @@ static void rna_def_colormanage(BlenderRNA *brna) prop = RNA_def_property(srna, "exposure", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "exposure"); - RNA_def_property_range(prop, -10.0f, 10.0f); RNA_def_property_float_default(prop, 0.0f); + RNA_def_property_range(prop, -32.0f, 32.0f); + RNA_def_property_ui_range(prop, -10.0f, 10.0f, 1, 3); RNA_def_property_ui_text(prop, "Exposure", "Exposure (stops) applied before display transform"); RNA_def_property_update(prop, NC_WINDOW, "rna_ColorManagement_update"); diff --git a/source/blender/makesrna/intern/rna_constraint.c b/source/blender/makesrna/intern/rna_constraint.c index 77aaff357227..e3e7b68dbc90 100644 --- a/source/blender/makesrna/intern/rna_constraint.c +++ b/source/blender/makesrna/intern/rna_constraint.c @@ -399,7 +399,7 @@ static void rna_SplineIKConstraint_joint_bindings_set(PointerRNA *ptr, const flo memcpy(ikData->points, values, ikData->numpoints * sizeof(float)); } -static int rna_Constraint_cameraObject_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_Constraint_cameraObject_poll(PointerRNA *ptr, PointerRNA value) { Object *ob = (Object *)value.data; @@ -446,7 +446,7 @@ static void rna_Constraint_followTrack_depthObject_set(PointerRNA *ptr, PointerR } } -static int rna_Constraint_followTrack_depthObject_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_Constraint_followTrack_depthObject_poll(PointerRNA *ptr, PointerRNA value) { Object *ob = (Object *)value.data; diff --git a/source/blender/makesrna/intern/rna_context.c b/source/blender/makesrna/intern/rna_context.c index 4bbf31d65004..04b531740ed5 100644 --- a/source/blender/makesrna/intern/rna_context.c +++ b/source/blender/makesrna/intern/rna_context.c @@ -220,4 +220,3 @@ void RNA_def_context(BlenderRNA *brna) } #endif - diff --git a/source/blender/makesrna/intern/rna_controller.c b/source/blender/makesrna/intern/rna_controller.c index 96e8878b938c..606f482c92ec 100644 --- a/source/blender/makesrna/intern/rna_controller.c +++ b/source/blender/makesrna/intern/rna_controller.c @@ -159,7 +159,7 @@ static void rna_Controller_state_get(PointerRNA *ptr, int *values) values[i] = (cont->state_mask & (1 << i)); } -static void rna_Controller_state_set(PointerRNA *ptr, const int *values) +static void rna_Controller_state_set(PointerRNA *ptr, const bool *values) { bController *cont = (bController *)ptr->data; int i, tot = 0; diff --git a/source/blender/makesrna/intern/rna_controller_api.c b/source/blender/makesrna/intern/rna_controller_api.c index 639d6a330a58..c36d678e064f 100644 --- a/source/blender/makesrna/intern/rna_controller_api.c +++ b/source/blender/makesrna/intern/rna_controller_api.c @@ -83,4 +83,3 @@ void RNA_api_controller(StructRNA *srna) } #endif - diff --git a/source/blender/makesrna/intern/rna_curve.c b/source/blender/makesrna/intern/rna_curve.c index 50abf00714bb..233303ef613c 100644 --- a/source/blender/makesrna/intern/rna_curve.c +++ b/source/blender/makesrna/intern/rna_curve.c @@ -393,7 +393,7 @@ static void rna_Curve_bevelObject_set(PointerRNA *ptr, PointerRNA value) } } -static int rna_Curve_otherObject_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_Curve_otherObject_poll(PointerRNA *ptr, PointerRNA value) { Curve *cu = (Curve *)ptr->id.data; Object *ob = (Object *)value.data; @@ -735,7 +735,7 @@ static void rna_Curve_splines_begin(CollectionPropertyIterator *iter, PointerRNA rna_iterator_listbase_begin(iter, BKE_curve_nurbs_get(cu), NULL); } -static int rna_Curve_is_editmode_get(PointerRNA *ptr) +static bool rna_Curve_is_editmode_get(PointerRNA *ptr) { Curve *cu = (Curve *)ptr->id.data; const short type = BKE_curve_type_get(cu); @@ -1759,6 +1759,8 @@ static void rna_def_curve_nurb(BlenderRNA *brna) RNA_def_property_update(prop, 0, "rna_Curve_update_data"); RNA_def_struct_path_func(srna, "rna_Curve_spline_path"); + + RNA_api_curve_nurb(srna); } void RNA_def_curve(BlenderRNA *brna) diff --git a/source/blender/makesrna/intern/rna_curve_api.c b/source/blender/makesrna/intern/rna_curve_api.c index be6808567bbe..d83a843c5c15 100644 --- a/source/blender/makesrna/intern/rna_curve_api.c +++ b/source/blender/makesrna/intern/rna_curve_api.c @@ -43,12 +43,17 @@ #include "rna_internal.h" /* own include */ #ifdef RNA_RUNTIME -static void rna_Curve_transform(Curve *cu, float *mat, int shape_keys) +static void rna_Curve_transform(Curve *cu, float *mat, bool shape_keys) { BKE_curve_transform(cu, (float (*)[4])mat, shape_keys, true); DAG_id_tag_update(&cu->id, 0); } +static float rna_Nurb_calc_length(Nurb *nu, int resolution_u) +{ + return BKE_nurb_calc_length(nu, resolution_u); +} + #else void RNA_api_curve(StructRNA *srna) @@ -69,4 +74,20 @@ void RNA_api_curve(StructRNA *srna) RNA_def_function_return(func, parm); } +void RNA_api_curve_nurb(StructRNA *srna) +{ + FunctionRNA *func; + PropertyRNA *parm; + + func = RNA_def_function(srna, "calc_length", "rna_Nurb_calc_length"); + RNA_def_function_ui_description(func, "Calculate spline length"); + RNA_def_int( + func, "resolution", 0, 0, 1024, "Resolution", + "Spline resolution to be used, 0 defaults to the resolution_u", 0, 64); + parm = RNA_def_float_distance( + func, "length", 0.0f, 0.0f, FLT_MAX, "Length", + "Length of the polygonaly approximated spline", 0.0f, FLT_MAX); + RNA_def_function_return(func, parm); +} + #endif diff --git a/source/blender/makesrna/intern/rna_define.c b/source/blender/makesrna/intern/rna_define.c index 2177c7b980a9..697e23a414ac 100644 --- a/source/blender/makesrna/intern/rna_define.c +++ b/source/blender/makesrna/intern/rna_define.c @@ -1633,7 +1633,7 @@ void RNA_def_property_string_maxlength(PropertyRNA *prop, int maxlength) } } -void RNA_def_property_boolean_default(PropertyRNA *prop, int value) +void RNA_def_property_boolean_default(PropertyRNA *prop, bool value) { StructRNA *srna = DefRNA.laststruct; @@ -1652,7 +1652,7 @@ void RNA_def_property_boolean_default(PropertyRNA *prop, int value) } } -void RNA_def_property_boolean_array_default(PropertyRNA *prop, const int *array) +void RNA_def_property_boolean_array_default(PropertyRNA *prop, const bool *array) { StructRNA *srna = DefRNA.laststruct; @@ -2624,7 +2624,7 @@ void RNA_def_py_data(PropertyRNA *prop, void *py_data) /* Compact definitions */ -PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont_, const char *identifier, int default_value, +PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont_, const char *identifier, bool default_value, const char *ui_name, const char *ui_description) { ContainerRNA *cont = cont_; @@ -2637,7 +2637,7 @@ PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont_, const char *identifier, return prop; } -PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont_, const char *identifier, int len, int *default_value, +PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont_, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description) { ContainerRNA *cont = cont_; @@ -2651,7 +2651,7 @@ PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont_, const char *ident return prop; } -PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont_, const char *identifier, int len, int *default_value, +PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont_, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description) { ContainerRNA *cont = cont_; @@ -2666,7 +2666,7 @@ PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont_, const char *ident } PropertyRNA *RNA_def_boolean_layer_member(StructOrFunctionRNA *cont_, const char *identifier, int len, - int *default_value, const char *ui_name, const char *ui_description) + bool *default_value, const char *ui_name, const char *ui_description) { ContainerRNA *cont = cont_; PropertyRNA *prop; @@ -2679,7 +2679,7 @@ PropertyRNA *RNA_def_boolean_layer_member(StructOrFunctionRNA *cont_, const char return prop; } -PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont_, const char *identifier, int len, int *default_value, +PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont_, const char *identifier, int len, bool *default_value, const char *ui_name, const char *ui_description) { ContainerRNA *cont = cont_; @@ -3218,6 +3218,7 @@ int rna_parameter_size(PropertyRNA *parm) if (len > 0) { switch (ptype) { case PROP_BOOLEAN: + return sizeof(bool) * len; case PROP_INT: return sizeof(int) * len; case PROP_FLOAT: @@ -3229,6 +3230,7 @@ int rna_parameter_size(PropertyRNA *parm) else { switch (ptype) { case PROP_BOOLEAN: + return sizeof(bool); case PROP_INT: case PROP_ENUM: return sizeof(int); @@ -3389,9 +3391,6 @@ void RNA_def_func_free_pointers(FunctionRNA *func) void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA *prop) { ContainerRNA *cont = cont_; - EnumPropertyItem *earray; - float *farray; - int *iarray; int a; /* annoying since we just added this to a hash, could make this add the correct key to the hash @@ -3406,8 +3405,12 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA } } - if (prop->name) prop->name = BLI_strdup(prop->name); - if (prop->description) prop->description = BLI_strdup(prop->description); + if (prop->name) { + prop->name = BLI_strdup(prop->name); + } + if (prop->description) { + prop->description = BLI_strdup(prop->description); + } switch (prop->type) { case PROP_BOOLEAN: @@ -3415,9 +3418,9 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA BoolPropertyRNA *bprop = (BoolPropertyRNA *)prop; if (bprop->defaultarray) { - iarray = MEM_callocN(sizeof(int) * prop->totarraylength, "RNA_def_property_store"); - memcpy(iarray, bprop->defaultarray, sizeof(int) * prop->totarraylength); - bprop->defaultarray = iarray; + bool *array = MEM_mallocN(sizeof(bool) * prop->totarraylength, "RNA_def_property_store"); + memcpy(array, bprop->defaultarray, sizeof(bool) * prop->totarraylength); + bprop->defaultarray = array; } break; } @@ -3426,9 +3429,9 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA IntPropertyRNA *iprop = (IntPropertyRNA *)prop; if (iprop->defaultarray) { - iarray = MEM_callocN(sizeof(int) * prop->totarraylength, "RNA_def_property_store"); - memcpy(iarray, iprop->defaultarray, sizeof(int) * prop->totarraylength); - iprop->defaultarray = iarray; + int *array = MEM_mallocN(sizeof(int) * prop->totarraylength, "RNA_def_property_store"); + memcpy(array, iprop->defaultarray, sizeof(int) * prop->totarraylength); + iprop->defaultarray = array; } break; } @@ -3437,17 +3440,20 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA EnumPropertyRNA *eprop = (EnumPropertyRNA *)prop; if (eprop->item) { - earray = MEM_callocN(sizeof(EnumPropertyItem) * (eprop->totitem + 1), "RNA_def_property_store"); - memcpy(earray, eprop->item, sizeof(EnumPropertyItem) * (eprop->totitem + 1)); - eprop->item = earray; + EnumPropertyItem *array = MEM_mallocN(sizeof(EnumPropertyItem) * (eprop->totitem + 1), "RNA_def_property_store"); + memcpy(array, eprop->item, sizeof(EnumPropertyItem) * (eprop->totitem + 1)); + eprop->item = array; for (a = 0; a < eprop->totitem; a++) { - if (earray[a].identifier) - earray[a].identifier = BLI_strdup(earray[a].identifier); - if (earray[a].name) - earray[a].name = BLI_strdup(earray[a].name); - if (earray[a].description) - earray[a].description = BLI_strdup(earray[a].description); + if (array[a].identifier) { + array[a].identifier = BLI_strdup(array[a].identifier); + } + if (array[a].name) { + array[a].name = BLI_strdup(array[a].name); + } + if (array[a].description) { + array[a].description = BLI_strdup(array[a].description); + } } } break; @@ -3457,9 +3463,9 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA FloatPropertyRNA *fprop = (FloatPropertyRNA *)prop; if (fprop->defaultarray) { - farray = MEM_callocN(sizeof(float) * prop->totarraylength, "RNA_def_property_store"); - memcpy(farray, fprop->defaultarray, sizeof(float) * prop->totarraylength); - fprop->defaultarray = farray; + float *array = MEM_mallocN(sizeof(float) * prop->totarraylength, "RNA_def_property_store"); + memcpy(array, fprop->defaultarray, sizeof(float) * prop->totarraylength); + fprop->defaultarray = array; } break; } diff --git a/source/blender/makesrna/intern/rna_dynamicpaint.c b/source/blender/makesrna/intern/rna_dynamicpaint.c index 99090d9d1845..d16ef3db296f 100644 --- a/source/blender/makesrna/intern/rna_dynamicpaint.c +++ b/source/blender/makesrna/intern/rna_dynamicpaint.c @@ -223,7 +223,7 @@ static void rna_DynamicPaint_uvlayer_set(PointerRNA *ptr, const char *value) } /* is point cache used */ -static int rna_DynamicPaint_is_cache_user_get(PointerRNA *ptr) +static bool rna_DynamicPaint_is_cache_user_get(PointerRNA *ptr) { DynamicPaintSurface *surface = (DynamicPaintSurface *)ptr->data; @@ -231,7 +231,7 @@ static int rna_DynamicPaint_is_cache_user_get(PointerRNA *ptr) } /* is some 3D view preview available */ -static int rna_DynamicPaint_use_color_preview_get(PointerRNA *ptr) +static bool rna_DynamicPaint_use_color_preview_get(PointerRNA *ptr) { DynamicPaintSurface *surface = (DynamicPaintSurface *)ptr->data; @@ -239,7 +239,7 @@ static int rna_DynamicPaint_use_color_preview_get(PointerRNA *ptr) } /* does output layer exist*/ -static int rna_DynamicPaint_is_output_exists(DynamicPaintSurface *surface, Object *ob, int index) +static bool rna_DynamicPaint_is_output_exists(DynamicPaintSurface *surface, Object *ob, int index) { return dynamicPaint_outputLayerExists(surface, ob, index); } diff --git a/source/blender/makesrna/intern/rna_fcurve.c b/source/blender/makesrna/intern/rna_fcurve.c index 6c1d67b404c9..9dbc9a62aa42 100644 --- a/source/blender/makesrna/intern/rna_fcurve.c +++ b/source/blender/makesrna/intern/rna_fcurve.c @@ -510,7 +510,7 @@ static void rna_FCurve_modifiers_remove(FCurve *fcu, ReportList *reports, Pointe RNA_POINTER_INVALIDATE(fcm_ptr); } -static void rna_FModifier_active_set(PointerRNA *ptr, int UNUSED(value)) +static void rna_FModifier_active_set(PointerRNA *ptr, bool UNUSED(value)) { FModifier *fcm = (FModifier *)ptr->data; @@ -827,7 +827,7 @@ static void rna_FKeyframe_points_add(FCurve *fcu, int tot) } } -static void rna_FKeyframe_points_remove(FCurve *fcu, ReportList *reports, PointerRNA *bezt_ptr, int do_fast) +static void rna_FKeyframe_points_remove(FCurve *fcu, ReportList *reports, PointerRNA *bezt_ptr, bool do_fast) { BezTriple *bezt = bezt_ptr->data; int index = (int)(bezt - fcu->bezt); diff --git a/source/blender/makesrna/intern/rna_gpencil.c b/source/blender/makesrna/intern/rna_gpencil.c index 51aed1ff2969..90af65497a4b 100644 --- a/source/blender/makesrna/intern/rna_gpencil.c +++ b/source/blender/makesrna/intern/rna_gpencil.c @@ -275,7 +275,7 @@ static const EnumPropertyItem *rna_Object_parent_type_itemf( return item; } -static int rna_GPencilLayer_is_parented_get(PointerRNA *ptr) +static bool rna_GPencilLayer_is_parented_get(PointerRNA *ptr) { bGPDlayer *gpl = (bGPDlayer *)ptr->data; return (gpl->parent != NULL); @@ -366,7 +366,7 @@ static void rna_GPencilLayer_info_set(PointerRNA *ptr, const char *value) BKE_animdata_fix_paths_rename_all(&gpd->id, "layers", oldname, gpl->info); } -static void rna_GPencil_use_onion_skinning_set(PointerRNA *ptr, const int value) +static void rna_GPencil_use_onion_skinning_set(PointerRNA *ptr, const bool value) { bGPdata *gpd = ptr->id.data; bGPDlayer *gpl; @@ -423,7 +423,7 @@ static bGPDstroke *rna_GPencil_stroke_point_find_stroke(const bGPdata *gpd, cons return NULL; } -static void rna_GPencil_stroke_point_select_set(PointerRNA *ptr, const int value) +static void rna_GPencil_stroke_point_select_set(PointerRNA *ptr, const bool value) { bGPdata *gpd = ptr->id.data; bGPDspoint *pt = ptr->data; @@ -525,7 +525,7 @@ static void rna_GPencil_stroke_remove(bGPDframe *frame, ReportList *reports, Poi WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL); } -static void rna_GPencil_stroke_select_set(PointerRNA *ptr, const int value) +static void rna_GPencil_stroke_select_set(PointerRNA *ptr, const bool value) { bGPDstroke *gps = ptr->data; bGPDspoint *pt; @@ -591,7 +591,7 @@ static bGPDframe *rna_GPencil_frame_copy(bGPDlayer *layer, bGPDframe *src) return frame; } -static bGPDlayer *rna_GPencil_layer_new(bGPdata *gpd, const char *name, int setactive) +static bGPDlayer *rna_GPencil_layer_new(bGPdata *gpd, const char *name, bool setactive) { bGPDlayer *gpl = BKE_gpencil_layer_addnew(gpd, name, setactive != 0); @@ -636,7 +636,7 @@ static void rna_GPencil_clear(bGPdata *gpd) } /* Palettes */ -static bGPDpalette *rna_GPencil_palette_new(bGPdata *gpd, const char *name, int setactive) +static bGPDpalette *rna_GPencil_palette_new(bGPdata *gpd, const char *name, bool setactive) { bGPDpalette *palette = BKE_gpencil_palette_addnew(gpd, name, setactive != 0); @@ -851,13 +851,13 @@ static void rna_GPencilStrokeColor_info_set(PointerRNA *ptr, const char *value) } -static int rna_GPencilPaletteColor_is_stroke_visible_get(PointerRNA *ptr) +static bool rna_GPencilPaletteColor_is_stroke_visible_get(PointerRNA *ptr) { bGPDpalettecolor *pcolor = (bGPDpalettecolor *)ptr->data; return (pcolor->color[3] > GPENCIL_ALPHA_OPACITY_THRESH); } -static int rna_GPencilPaletteColor_is_fill_visible_get(PointerRNA *ptr) +static bool rna_GPencilPaletteColor_is_fill_visible_get(PointerRNA *ptr) { bGPDpalettecolor *pcolor = (bGPDpalettecolor *)ptr->data; return (pcolor->fill[3] > GPENCIL_ALPHA_OPACITY_THRESH); diff --git a/source/blender/makesrna/intern/rna_image.c b/source/blender/makesrna/intern/rna_image.c index bab8c18439f7..018a4765cd01 100644 --- a/source/blender/makesrna/intern/rna_image.c +++ b/source/blender/makesrna/intern/rna_image.c @@ -83,17 +83,17 @@ static void rna_Image_animated_update(Main *UNUSED(bmain), Scene *UNUSED(scene), } } -static int rna_Image_is_stereo_3d_get(PointerRNA *ptr) +static bool rna_Image_is_stereo_3d_get(PointerRNA *ptr) { return BKE_image_is_stereo((Image *)ptr->data); } -static int rna_Image_is_multiview_get(PointerRNA *ptr) +static bool rna_Image_is_multiview_get(PointerRNA *ptr) { return BKE_image_is_multiview((Image *)ptr->data); } -static int rna_Image_dirty_get(PointerRNA *ptr) +static bool rna_Image_dirty_get(PointerRNA *ptr) { return BKE_image_is_dirty((Image *)ptr->data); } @@ -104,7 +104,8 @@ static void rna_Image_source_set(PointerRNA *ptr, int value) if (value != ima->source) { ima->source = value; - BKE_image_signal(G.main, ima, NULL, IMA_SIGNAL_SRC_CHANGE); + BLI_assert(BKE_id_is_in_gobal_main(&ima->id)); + BKE_image_signal(G_MAIN, ima, NULL, IMA_SIGNAL_SRC_CHANGE); DAG_id_tag_update(&ima->id, 0); } } @@ -250,7 +251,7 @@ static void rna_Image_file_format_set(PointerRNA *ptr, int value) } } -static int rna_Image_has_data_get(PointerRNA *ptr) +static bool rna_Image_has_data_get(PointerRNA *ptr) { Image *image = (Image *)ptr->data; @@ -437,7 +438,7 @@ static int rna_Image_channels_get(PointerRNA *ptr) return channels; } -static int rna_Image_is_float_get(PointerRNA *ptr) +static bool rna_Image_is_float_get(PointerRNA *ptr) { Image *im = (Image *)ptr->data; ImBuf *ibuf; diff --git a/source/blender/makesrna/intern/rna_image_api.c b/source/blender/makesrna/intern/rna_image_api.c index cb8fa6c6c85f..dc625ca8d9a6 100644 --- a/source/blender/makesrna/intern/rna_image_api.c +++ b/source/blender/makesrna/intern/rna_image_api.c @@ -118,7 +118,9 @@ static void rna_Image_save_render(Image *image, bContext *C, ReportList *reports static void rna_Image_save(Image *image, Main *bmain, bContext *C, ReportList *reports) { - ImBuf *ibuf = BKE_image_acquire_ibuf(image, NULL, NULL); + void *lock; + + ImBuf *ibuf = BKE_image_acquire_ibuf(image, NULL, &lock); if (ibuf) { char filename[FILE_MAX]; BLI_strncpy(filename, image->name, sizeof(filename)); @@ -145,13 +147,13 @@ static void rna_Image_save(Image *image, Main *bmain, bContext *C, ReportList *r BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2); } - BKE_image_release_ibuf(image, ibuf, NULL); + BKE_image_release_ibuf(image, ibuf, lock); WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, image); } static void rna_Image_pack( Image *image, Main *bmain, bContext *C, ReportList *reports, - int as_png, const char *data, int data_len) + bool as_png, const char *data, int data_len) { ImBuf *ibuf = BKE_image_acquire_ibuf(image, NULL, NULL); @@ -241,7 +243,7 @@ static int rna_Image_gl_load(Image *image, ReportList *reports, int frame, int f if (ibuf == NULL || ibuf->rect == NULL) { BKE_reportf(reports, RPT_ERROR, "Image '%s' does not have any image data", image->id.name + 2); - BKE_image_release_ibuf(image, ibuf, NULL); + BKE_image_release_ibuf(image, ibuf, lock); return (int)GL_INVALID_OPERATION; } @@ -258,7 +260,7 @@ static int rna_Image_gl_load(Image *image, ReportList *reports, int frame, int f image->bindcode[TEXTARGET_TEXTURE_2D] = 0; } - BKE_image_release_ibuf(image, ibuf, NULL); + BKE_image_release_ibuf(image, ibuf, lock); return error; } @@ -396,4 +398,3 @@ void RNA_api_image(StructRNA *srna) } #endif - diff --git a/source/blender/makesrna/intern/rna_internal.h b/source/blender/makesrna/intern/rna_internal.h index 473b03a73f90..e640800ec5ba 100644 --- a/source/blender/makesrna/intern/rna_internal.h +++ b/source/blender/makesrna/intern/rna_internal.h @@ -210,14 +210,14 @@ void rna_def_render_layer_common(struct StructRNA *srna, int scene); void rna_def_actionbone_group_common(struct StructRNA *srna, int update_flag, const char *update_cb); void rna_ActionGroup_colorset_set(struct PointerRNA *ptr, int value); -int rna_ActionGroup_is_custom_colorset_get(struct PointerRNA *ptr); +bool rna_ActionGroup_is_custom_colorset_get(struct PointerRNA *ptr); void rna_ID_name_get(struct PointerRNA *ptr, char *value); int rna_ID_name_length(struct PointerRNA *ptr); void rna_ID_name_set(struct PointerRNA *ptr, const char *value); struct StructRNA *rna_ID_refine(struct PointerRNA *ptr); struct IDProperty *rna_ID_idprops(struct PointerRNA *ptr, bool create); -void rna_ID_fake_user_set(struct PointerRNA *ptr, int value); +void rna_ID_fake_user_set(struct PointerRNA *ptr, bool value); void **rna_ID_instance(PointerRNA *ptr); struct IDProperty *rna_PropertyGroup_idprops(struct PointerRNA *ptr, bool create); void rna_PropertyGroup_unregister(struct Main *bmain, struct StructRNA *type); @@ -241,16 +241,16 @@ void rna_Mesh_update_draw(struct Main *bmain, struct Scene *scene, struct Pointe void rna_TextureSlot_update(struct Main *bmain, struct Scene *scene, struct PointerRNA *ptr); /* basic poll functions for object types */ -int rna_Armature_object_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Camera_object_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Curve_object_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Lamp_object_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Lattice_object_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Mesh_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Armature_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Camera_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Curve_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Lamp_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Lattice_object_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Mesh_object_poll(struct PointerRNA *ptr, struct PointerRNA value); /* basic poll functions for actions (to prevent actions getting set in wrong places) */ -int rna_Action_id_poll(struct PointerRNA *ptr, struct PointerRNA value); -int rna_Action_actedit_assign_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Action_id_poll(struct PointerRNA *ptr, struct PointerRNA value); +bool rna_Action_actedit_assign_poll(struct PointerRNA *ptr, struct PointerRNA value); char *rna_TextureSlot_path(struct PointerRNA *ptr); char *rna_Node_ImageUser_path(struct PointerRNA *ptr); @@ -262,6 +262,7 @@ void RNA_api_armature_edit_bone(StructRNA *srna); void RNA_api_bone(StructRNA *srna); void RNA_api_camera(StructRNA *srna); void RNA_api_curve(StructRNA *srna); +void RNA_api_curve_nurb(StructRNA *srna); void RNA_api_fcurves(StructRNA *srna); void RNA_api_drivers(StructRNA *srna); void RNA_api_image_packed_file(struct StructRNA *srna); @@ -405,7 +406,7 @@ int rna_parameter_size(struct PropertyRNA *parm); struct Mesh *rna_Main_meshes_new_from_object( struct Main *bmain, struct ReportList *reports, struct Scene *sce, - struct Object *ob, int apply_modifiers, int settings, int calc_tessface, int calc_undeformed); + struct Object *ob, bool apply_modifiers, int settings, bool calc_tessface, bool calc_undeformed); /* XXX, these should not need to be defined here~! */ struct MTex *rna_mtex_texture_slots_add(struct ID *self, struct bContext *C, struct ReportList *reports); @@ -416,7 +417,7 @@ void rna_mtex_texture_slots_clear(struct ID *self, struct bContext *C, struct Re int rna_IDMaterials_assign_int(struct PointerRNA *ptr, int key, const struct PointerRNA *assign_ptr); const char *rna_translate_ui_text( - const char *text, const char *text_ctxt, struct StructRNA *type, struct PropertyRNA *prop, int translate); + const char *text, const char *text_ctxt, struct StructRNA *type, struct PropertyRNA *prop, bool translate); /* Internal functions that cycles uses so we need to declare (tsk tsk) */ void rna_RenderLayer_rect_set(PointerRNA *ptr, const float *values); diff --git a/source/blender/makesrna/intern/rna_internal_types.h b/source/blender/makesrna/intern/rna_internal_types.h index d93f3308b2ad..f9929cec7b19 100644 --- a/source/blender/makesrna/intern/rna_internal_types.h +++ b/source/blender/makesrna/intern/rna_internal_types.h @@ -69,10 +69,10 @@ typedef struct StructRNA *(*StructRefineFunc)(struct PointerRNA *ptr); typedef char *(*StructPathFunc)(struct PointerRNA *ptr); typedef int (*PropArrayLengthGetFunc)(struct PointerRNA *ptr, int length[RNA_MAX_ARRAY_DIMENSION]); -typedef int (*PropBooleanGetFunc)(struct PointerRNA *ptr); -typedef void (*PropBooleanSetFunc)(struct PointerRNA *ptr, int value); -typedef void (*PropBooleanArrayGetFunc)(struct PointerRNA *ptr, int *values); -typedef void (*PropBooleanArraySetFunc)(struct PointerRNA *ptr, const int *values); +typedef bool (*PropBooleanGetFunc)(struct PointerRNA *ptr); +typedef void (*PropBooleanSetFunc)(struct PointerRNA *ptr, bool value); +typedef void (*PropBooleanArrayGetFunc)(struct PointerRNA *ptr, bool *values); +typedef void (*PropBooleanArraySetFunc)(struct PointerRNA *ptr, const bool *values); typedef int (*PropIntGetFunc)(struct PointerRNA *ptr); typedef void (*PropIntSetFunc)(struct PointerRNA *ptr, int value); typedef void (*PropIntArrayGetFunc)(struct PointerRNA *ptr, int *values); @@ -94,8 +94,8 @@ typedef const EnumPropertyItem *(*PropEnumItemFunc)( typedef PointerRNA (*PropPointerGetFunc)(struct PointerRNA *ptr); typedef StructRNA *(*PropPointerTypeFunc)(struct PointerRNA *ptr); typedef void (*PropPointerSetFunc)(struct PointerRNA *ptr, const PointerRNA value); -typedef int (*PropPointerPollFunc)(struct PointerRNA *ptr, const PointerRNA value); -typedef int (*PropPointerPollFuncPy)(struct PointerRNA *ptr, const PointerRNA value, const PropertyRNA *prop); +typedef bool (*PropPointerPollFunc)(struct PointerRNA *ptr, const PointerRNA value); +typedef bool (*PropPointerPollFuncPy)(struct PointerRNA *ptr, const PointerRNA value, const PropertyRNA *prop); typedef void (*PropCollectionBeginFunc)(struct CollectionPropertyIterator *iter, struct PointerRNA *ptr); typedef void (*PropCollectionNextFunc)(struct CollectionPropertyIterator *iter); typedef void (*PropCollectionEndFunc)(struct CollectionPropertyIterator *iter); @@ -106,10 +106,10 @@ typedef int (*PropCollectionLookupStringFunc)(struct PointerRNA *ptr, const char typedef int (*PropCollectionAssignIntFunc)(struct PointerRNA *ptr, int key, const struct PointerRNA *assign_ptr); /* extended versions with PropertyRNA argument */ -typedef int (*PropBooleanGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop); -typedef void (*PropBooleanSetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, int value); -typedef void (*PropBooleanArrayGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values); -typedef void (*PropBooleanArraySetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values); +typedef bool (*PropBooleanGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop); +typedef void (*PropBooleanSetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, bool value); +typedef void (*PropBooleanArrayGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, bool *values); +typedef void (*PropBooleanArraySetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, const bool *values); typedef int (*PropIntGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop); typedef void (*PropIntSetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, int value); typedef void (*PropIntArrayGetFuncEx)(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values); @@ -241,8 +241,8 @@ typedef struct BoolPropertyRNA { PropBooleanArrayGetFuncEx getarray_ex; PropBooleanArraySetFuncEx setarray_ex; - int defaultvalue; - const int *defaultarray; + bool defaultvalue; + const bool *defaultarray; } BoolPropertyRNA; typedef struct IntPropertyRNA { diff --git a/source/blender/makesrna/intern/rna_lamp.c b/source/blender/makesrna/intern/rna_lamp.c index 68e8ddc5e8ee..b4a68fe778be 100644 --- a/source/blender/makesrna/intern/rna_lamp.c +++ b/source/blender/makesrna/intern/rna_lamp.c @@ -89,7 +89,7 @@ static void rna_Lamp_active_texture_set(PointerRNA *ptr, PointerRNA value) set_current_lamp_texture(la, value.data); } -static int rna_use_shadow_get(PointerRNA *ptr) +static bool rna_use_shadow_get(PointerRNA *ptr) { Lamp *la = (Lamp *)ptr->data; @@ -101,7 +101,7 @@ static int rna_use_shadow_get(PointerRNA *ptr) } } -static void rna_use_shadow_set(PointerRNA *ptr, int value) +static void rna_use_shadow_set(PointerRNA *ptr, bool value) { Lamp *la = (Lamp *)ptr->data; la->mode &= ~(LA_SHAD_BUF | LA_SHAD_RAY); diff --git a/source/blender/makesrna/intern/rna_lattice.c b/source/blender/makesrna/intern/rna_lattice.c index 424c6f93f75c..bbc0c251897a 100644 --- a/source/blender/makesrna/intern/rna_lattice.c +++ b/source/blender/makesrna/intern/rna_lattice.c @@ -154,7 +154,7 @@ static void rna_Lattice_update_size(Main *bmain, Scene *scene, PointerRNA *ptr) rna_Lattice_update_data(bmain, scene, ptr); } -static void rna_Lattice_use_outside_set(PointerRNA *ptr, int value) +static void rna_Lattice_use_outside_set(PointerRNA *ptr, bool value) { Lattice *lt = ptr->data; @@ -235,7 +235,7 @@ static char *rna_LatticePoint_path(PointerRNA *ptr) return BLI_strdup(""); } -static int rna_Lattice_is_editmode_get(PointerRNA *ptr) +static bool rna_Lattice_is_editmode_get(PointerRNA *ptr) { Lattice *lt = (Lattice *)ptr->id.data; return (lt->editlatt != NULL); diff --git a/source/blender/makesrna/intern/rna_lattice_api.c b/source/blender/makesrna/intern/rna_lattice_api.c index 2ea59d31262d..ee1a94f2ecb2 100644 --- a/source/blender/makesrna/intern/rna_lattice_api.c +++ b/source/blender/makesrna/intern/rna_lattice_api.c @@ -41,7 +41,7 @@ #include "rna_internal.h" /* own include */ #ifdef RNA_RUNTIME -static void rna_Lattice_transform(Lattice *lt, float *mat, int shape_keys) +static void rna_Lattice_transform(Lattice *lt, float *mat, bool shape_keys) { BKE_lattice_transform(lt, (float (*)[4])mat, shape_keys); diff --git a/source/blender/makesrna/intern/rna_main.c b/source/blender/makesrna/intern/rna_main.c index 89e1ee474756..5d7088c952ba 100644 --- a/source/blender/makesrna/intern/rna_main.c +++ b/source/blender/makesrna/intern/rna_main.c @@ -42,7 +42,7 @@ /* all the list begin functions are added manually here, Main is not in SDNA */ -static int rna_Main_use_autopack_get(PointerRNA *UNUSED(ptr)) +static bool rna_Main_use_autopack_get(PointerRNA *UNUSED(ptr)) { if (G.fileflags & G_AUTOPACK) return 1; @@ -50,7 +50,7 @@ static int rna_Main_use_autopack_get(PointerRNA *UNUSED(ptr)) return 0; } -static void rna_Main_use_autopack_set(PointerRNA *UNUSED(ptr), int value) +static void rna_Main_use_autopack_set(PointerRNA *UNUSED(ptr), bool value) { if (value) G.fileflags |= G_AUTOPACK; @@ -58,12 +58,12 @@ static void rna_Main_use_autopack_set(PointerRNA *UNUSED(ptr), int value) G.fileflags &= ~G_AUTOPACK; } -static int rna_Main_is_saved_get(PointerRNA *UNUSED(ptr)) +static bool rna_Main_is_saved_get(PointerRNA *UNUSED(ptr)) { return G.relbase_valid; } -static int rna_Main_is_dirty_get(PointerRNA *ptr) +static bool rna_Main_is_dirty_get(PointerRNA *ptr) { /* XXX, not totally nice to do it this way, should store in main ? */ Main *bmain = (Main *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_main_api.c b/source/blender/makesrna/intern/rna_main_api.c index f00b308e36b7..7d619254e078 100644 --- a/source/blender/makesrna/intern/rna_main_api.c +++ b/source/blender/makesrna/intern/rna_main_api.c @@ -123,8 +123,9 @@ static void rna_idname_validate(const char *name, char *r_name) } -static void rna_Main_ID_remove(Main *bmain, ReportList *reports, PointerRNA *id_ptr, - int do_unlink, int do_id_user, int do_ui_user) +static void rna_Main_ID_remove( + Main *bmain, ReportList *reports, PointerRNA *id_ptr, + bool do_unlink, bool do_id_user, bool do_ui_user) { ID *id = id_ptr->data; if (do_unlink) { @@ -160,7 +161,7 @@ static Scene *rna_Main_scenes_new(Main *bmain, const char *name) return BKE_scene_add(bmain, safe_name); } -static void rna_Main_scenes_remove(Main *bmain, bContext *C, ReportList *reports, PointerRNA *scene_ptr, int do_unlink) +static void rna_Main_scenes_remove(Main *bmain, bContext *C, ReportList *reports, PointerRNA *scene_ptr, bool do_unlink) { /* don't call BKE_libblock_free(...) directly */ Scene *scene = scene_ptr->data; @@ -294,7 +295,7 @@ static Mesh *rna_Main_meshes_new(Main *bmain, const char *name) /* settings: 1 - preview, 2 - render */ Mesh *rna_Main_meshes_new_from_object( Main *bmain, ReportList *reports, Scene *sce, - Object *ob, int apply_modifiers, int settings, int calc_tessface, int calc_undeformed) + Object *ob, bool apply_modifiers, int settings, bool calc_tessface, bool calc_undeformed) { switch (ob->type) { case OB_FONT: @@ -322,7 +323,7 @@ static Lamp *rna_Main_lamps_new(Main *bmain, const char *name, int type) return lamp; } -static Image *rna_Main_images_new(Main *bmain, const char *name, int width, int height, int alpha, int float_buffer, int stereo3d) +static Image *rna_Main_images_new(Main *bmain, const char *name, int width, int height, bool alpha, bool float_buffer, bool stereo3d) { char safe_name[MAX_ID_NAME - 2]; rna_idname_validate(name, safe_name); @@ -332,7 +333,7 @@ static Image *rna_Main_images_new(Main *bmain, const char *name, int width, int id_us_min(&image->id); return image; } -static Image *rna_Main_images_load(Main *bmain, ReportList *reports, const char *filepath, int check_existing) +static Image *rna_Main_images_load(Main *bmain, ReportList *reports, const char *filepath, bool check_existing) { Image *ima; @@ -383,7 +384,7 @@ static MetaBall *rna_Main_metaballs_new(Main *bmain, const char *name) return mb; } -static VFont *rna_Main_fonts_load(Main *bmain, ReportList *reports, const char *filepath, int check_existing) +static VFont *rna_Main_fonts_load(Main *bmain, ReportList *reports, const char *filepath, bool check_existing) { VFont *font; errno = 0; @@ -453,7 +454,7 @@ static Speaker *rna_Main_speakers_new(Main *bmain, const char *name) return speaker; } -static bSound *rna_Main_sounds_load(Main *bmain, const char *name, int check_existing) +static bSound *rna_Main_sounds_load(Main *bmain, const char *name, bool check_existing) { bSound *sound; @@ -476,7 +477,7 @@ static Text *rna_Main_texts_new(Main *bmain, const char *name) return BKE_text_add(bmain, safe_name); } -static Text *rna_Main_texts_load(Main *bmain, ReportList *reports, const char *filepath, int is_internal) +static Text *rna_Main_texts_load(Main *bmain, ReportList *reports, const char *filepath, bool is_internal) { Text *txt; @@ -530,7 +531,7 @@ static Palette *rna_Main_palettes_new(Main *bmain, const char *name) return (Palette *)palette; } -static MovieClip *rna_Main_movieclip_load(Main *bmain, ReportList *reports, const char *filepath, int check_existing) +static MovieClip *rna_Main_movieclip_load(Main *bmain, ReportList *reports, const char *filepath, bool check_existing) { MovieClip *clip; @@ -575,10 +576,10 @@ static FreestyleLineStyle *rna_Main_linestyles_new(Main *bmain, const char *name /* tag and is_updated functions, all the same */ #define RNA_MAIN_ID_TAG_FUNCS_DEF(_func_name, _listbase_name, _id_type) \ - static void rna_Main_##_func_name##_tag(Main *bmain, int value) { \ + static void rna_Main_##_func_name##_tag(Main *bmain, bool value) { \ BKE_main_id_tag_listbase(&bmain->_listbase_name, LIB_TAG_DOIT, value); \ } \ - static int rna_Main_##_func_name##_is_updated_get(PointerRNA *ptr) { \ + static bool rna_Main_##_func_name##_is_updated_get(PointerRNA *ptr) { \ return DAG_id_type_tagged(ptr->data, _id_type) != 0; \ } diff --git a/source/blender/makesrna/intern/rna_material.c b/source/blender/makesrna/intern/rna_material.c index 444d2f281bb7..8a81f73dd57c 100644 --- a/source/blender/makesrna/intern/rna_material.c +++ b/source/blender/makesrna/intern/rna_material.c @@ -280,7 +280,7 @@ static void rna_MaterialStrand_end_size_range(PointerRNA *ptr, float *min, float } } -static int rna_MaterialTextureSlot_use_get(PointerRNA *ptr) +static bool rna_MaterialTextureSlot_use_get(PointerRNA *ptr) { Material *ma = (Material *)ptr->id.data; MTex *mtex = (MTex *)ptr->data; @@ -293,7 +293,7 @@ static int rna_MaterialTextureSlot_use_get(PointerRNA *ptr) return 0; } -static void rna_MaterialTextureSlot_use_set(PointerRNA *ptr, int value) +static void rna_MaterialTextureSlot_use_set(PointerRNA *ptr, bool value) { Material *ma = (Material *)ptr->id.data; MTex *mtex = (MTex *)ptr->data; @@ -309,7 +309,7 @@ static void rna_MaterialTextureSlot_use_set(PointerRNA *ptr, int value) } } -static void rna_Material_use_diffuse_ramp_set(PointerRNA *ptr, int value) +static void rna_Material_use_diffuse_ramp_set(PointerRNA *ptr, bool value) { Material *ma = (Material *)ptr->data; @@ -320,7 +320,7 @@ static void rna_Material_use_diffuse_ramp_set(PointerRNA *ptr, int value) ma->ramp_col = BKE_colorband_add(false); } -static void rna_Material_use_specular_ramp_set(PointerRNA *ptr, int value) +static void rna_Material_use_specular_ramp_set(PointerRNA *ptr, bool value) { Material *ma = (Material *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_material_api.c b/source/blender/makesrna/intern/rna_material_api.c index c7441f92c33c..268655d77bf9 100644 --- a/source/blender/makesrna/intern/rna_material_api.c +++ b/source/blender/makesrna/intern/rna_material_api.c @@ -50,4 +50,3 @@ void RNA_api_material(StructRNA *UNUSED(srna)) } #endif - diff --git a/source/blender/makesrna/intern/rna_mesh.c b/source/blender/makesrna/intern/rna_mesh.c index f09fd29889ab..c97cf2923f2e 100644 --- a/source/blender/makesrna/intern/rna_mesh.c +++ b/source/blender/makesrna/intern/rna_mesh.c @@ -209,10 +209,10 @@ static void rna_MeshAnyLayer_name_set(PointerRNA *ptr, const char *value) rna_cd_layer_name_set(cd, (CustomDataLayer *)ptr->data, value); } -static int rna_Mesh_has_custom_normals_get(PointerRNA *ptr) +static bool rna_Mesh_has_custom_normals_get(PointerRNA *ptr) { Mesh *me = ptr->data; - return (int)BKE_mesh_has_custom_loop_normals(me); + return BKE_mesh_has_custom_loop_normals(me); } /* -------------------------------------------------------------------- */ @@ -778,7 +778,7 @@ static void rna_CustomDataLayer_clone_set(PointerRNA *ptr, CustomData *data, int CustomData_set_layer_clone_index(data, type, n); } -static int rna_MEdge_freestyle_edge_mark_get(PointerRNA *ptr) +static bool rna_MEdge_freestyle_edge_mark_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MEdge *medge = (MEdge *)ptr->data; @@ -787,7 +787,7 @@ static int rna_MEdge_freestyle_edge_mark_get(PointerRNA *ptr) return fed && (fed->flag & FREESTYLE_EDGE_MARK) != 0; } -static void rna_MEdge_freestyle_edge_mark_set(PointerRNA *ptr, int value) +static void rna_MEdge_freestyle_edge_mark_set(PointerRNA *ptr, bool value) { Mesh *me = rna_mesh(ptr); MEdge *medge = (MEdge *)ptr->data; @@ -804,7 +804,7 @@ static void rna_MEdge_freestyle_edge_mark_set(PointerRNA *ptr, int value) } } -static int rna_MPoly_freestyle_face_mark_get(PointerRNA *ptr) +static bool rna_MPoly_freestyle_face_mark_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MPoly *mpoly = (MPoly *)ptr->data; @@ -890,22 +890,22 @@ static int rna_MeshTextureFaceLayer_data_length(PointerRNA *ptr) return (me->edit_btmesh) ? 0 : me->totface; } -static int rna_MeshTextureFaceLayer_active_render_get(PointerRNA *ptr) +static bool rna_MeshTextureFaceLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_fdata(ptr), CD_MTFACE, 1); } -static int rna_MeshTextureFaceLayer_active_get(PointerRNA *ptr) +static bool rna_MeshTextureFaceLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_fdata(ptr), CD_MTFACE, 0); } -static int rna_MeshTextureFaceLayer_clone_get(PointerRNA *ptr) +static bool rna_MeshTextureFaceLayer_clone_get(PointerRNA *ptr) { return rna_CustomDataLayer_clone_get(ptr, rna_mesh_fdata(ptr), CD_MTFACE); } -static void rna_MeshTextureFaceLayer_active_render_set(PointerRNA *ptr, int value) +static void rna_MeshTextureFaceLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_fdata(ptr), value, CD_MTFACE, 1); } @@ -941,22 +941,22 @@ static int rna_MeshTexturePolyLayer_data_length(PointerRNA *ptr) return (me->edit_btmesh) ? 0 : me->totpoly; } -static int rna_MeshTexturePolyLayer_active_render_get(PointerRNA *ptr) +static bool rna_MeshTexturePolyLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_pdata(ptr), CD_MTEXPOLY, 1); } -static int rna_MeshTexturePolyLayer_active_get(PointerRNA *ptr) +static bool rna_MeshTexturePolyLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_pdata(ptr), CD_MTEXPOLY, 0); } -static int rna_MeshTexturePolyLayer_clone_get(PointerRNA *ptr) +static bool rna_MeshTexturePolyLayer_clone_get(PointerRNA *ptr) { return rna_CustomDataLayer_clone_get(ptr, rna_mesh_pdata(ptr), CD_MTEXPOLY); } -static void rna_MeshTexturePolyLayer_active_render_set(PointerRNA *ptr, int value) +static void rna_MeshTexturePolyLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_pdata(ptr), value, CD_MTEXPOLY, 1); } @@ -966,7 +966,7 @@ static void rna_MeshTexturePolyLayer_active_set(PointerRNA *ptr, int value) rna_CustomDataLayer_active_set(ptr, rna_mesh_pdata(ptr), value, CD_MTEXPOLY, 0); } -static void rna_MeshTexturePolyLayer_clone_set(PointerRNA *ptr, int value) +static void rna_MeshTexturePolyLayer_clone_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_clone_set(ptr, rna_mesh_pdata(ptr), value, CD_MTEXPOLY); } @@ -990,17 +990,17 @@ static int rna_MeshColorLayer_data_length(PointerRNA *ptr) return me->totface; } -static int rna_MeshColorLayer_active_render_get(PointerRNA *ptr) +static bool rna_MeshColorLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_fdata(ptr), CD_MCOL, 1); } -static int rna_MeshColorLayer_active_get(PointerRNA *ptr) +static bool rna_MeshColorLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_fdata(ptr), CD_MCOL, 0); } -static void rna_MeshColorLayer_active_render_set(PointerRNA *ptr, int value) +static void rna_MeshColorLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_fdata(ptr), value, CD_MCOL, 1); } @@ -1027,22 +1027,22 @@ static int rna_MeshLoopColorLayer_data_length(PointerRNA *ptr) return (me->edit_btmesh) ? 0 : me->totloop; } -static int rna_MeshLoopColorLayer_active_render_get(PointerRNA *ptr) +static bool rna_MeshLoopColorLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPCOL, 1); } -static int rna_MeshLoopColorLayer_active_get(PointerRNA *ptr) +static bool rna_MeshLoopColorLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPCOL, 0); } -static void rna_MeshLoopColorLayer_active_render_set(PointerRNA *ptr, int value) +static void rna_MeshLoopColorLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPCOL, 1); } -static void rna_MeshLoopColorLayer_active_set(PointerRNA *ptr, int value) +static void rna_MeshLoopColorLayer_active_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPCOL, 0); } @@ -1823,7 +1823,7 @@ static PointerRNA rna_Mesh_tessface_uv_texture_new(struct Mesh *me, ReportList * } -static int rna_Mesh_is_editmode_get(PointerRNA *ptr) +static bool rna_Mesh_is_editmode_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return (me->edit_btmesh != NULL); @@ -3220,7 +3220,9 @@ static void rna_def_skin_vertices(BlenderRNA *brna, PropertyRNA *UNUSED(cprop)) prop = RNA_def_property(srna, "use_root", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MVERT_SKIN_ROOT); - RNA_def_property_ui_text(prop, "Root", "Vertex is a root for rotation calculations and armature generation"); + RNA_def_property_ui_text(prop, "Root", + "Vertex is a root for rotation calculations and armature generation, " + "setting this flag does not clear other roots in the same mesh island"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "use_loose", PROP_BOOLEAN, PROP_NONE); diff --git a/source/blender/makesrna/intern/rna_mesh_api.c b/source/blender/makesrna/intern/rna_mesh_api.c index 51cb96e5d42c..579898cce442 100644 --- a/source/blender/makesrna/intern/rna_mesh_api.c +++ b/source/blender/makesrna/intern/rna_mesh_api.c @@ -100,12 +100,12 @@ static void rna_Mesh_free_tangents(Mesh *mesh) CustomData_free_layers(&mesh->ldata, CD_MLOOPTANGENT, mesh->totloop); } -static void rna_Mesh_calc_tessface(Mesh *mesh, int free_mpoly) +static void rna_Mesh_calc_tessface(Mesh *mesh, bool free_mpoly) { ED_mesh_calc_tessface(mesh, free_mpoly != 0); } -static void rna_Mesh_calc_smooth_groups(Mesh *mesh, int use_bitflags, int *r_poly_group_len, +static void rna_Mesh_calc_smooth_groups(Mesh *mesh, bool use_bitflags, int *r_poly_group_len, int **r_poly_group, int *r_group_total) { *r_poly_group_len = mesh->totpoly; @@ -193,7 +193,7 @@ static void rna_Mesh_normals_split_custom_set_from_vertices( DAG_id_tag_update(&mesh->id, 0); } -static void rna_Mesh_transform(Mesh *mesh, float *mat, int shape_keys) +static void rna_Mesh_transform(Mesh *mesh, float *mat, bool shape_keys) { BKE_mesh_transform(mesh, (float (*)[4])mat, shape_keys); @@ -209,7 +209,7 @@ static void rna_Mesh_flip_normals(Mesh *mesh) DAG_id_tag_update(&mesh->id, 0); } -static void rna_Mesh_split_faces(Mesh *mesh, int free_loop_normals) +static void rna_Mesh_split_faces(Mesh *mesh, bool free_loop_normals) { BKE_mesh_split_faces(mesh, free_loop_normals != 0); } diff --git a/source/blender/makesrna/intern/rna_meta.c b/source/blender/makesrna/intern/rna_meta.c index 07f36b3efffe..7025e05d56cc 100644 --- a/source/blender/makesrna/intern/rna_meta.c +++ b/source/blender/makesrna/intern/rna_meta.c @@ -158,7 +158,7 @@ static void rna_MetaBall_elements_clear(MetaBall *mb) } } -static int rna_Meta_is_editmode_get(PointerRNA *ptr) +static bool rna_Meta_is_editmode_get(PointerRNA *ptr) { MetaBall *mb = ptr->id.data; return (mb->editelems != NULL); diff --git a/source/blender/makesrna/intern/rna_modifier.c b/source/blender/makesrna/intern/rna_modifier.c index a29f10684bbd..1a05b6e5e003 100644 --- a/source/blender/makesrna/intern/rna_modifier.c +++ b/source/blender/makesrna/intern/rna_modifier.c @@ -651,7 +651,7 @@ static void rna_MultiresModifier_level_range(PointerRNA *ptr, int *min, int *max *max = max_ii(0, mmd->totlvl); /* intentionally _not_ -1 */ } -static int rna_MultiresModifier_external_get(PointerRNA *ptr) +static bool rna_MultiresModifier_external_get(PointerRNA *ptr) { Object *ob = (Object *)ptr->id.data; Mesh *me = ob->data; @@ -700,7 +700,7 @@ static void rna_ShrinkwrapModifier_face_cull_set(struct PointerRNA *ptr, int val (swm->shrinkOpts & ~(MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE | MOD_SHRINKWRAP_CULL_TARGET_BACKFACE)) | value; } -static int rna_MeshDeformModifier_is_bound_get(PointerRNA *ptr) +static bool rna_MeshDeformModifier_is_bound_get(PointerRNA *ptr) { return (((MeshDeformModifierData *)ptr->data)->bindcagecos != NULL); } @@ -737,25 +737,7 @@ static void rna_OceanModifier_init_update(Main *bmain, Scene *scene, PointerRNA { OceanModifierData *omd = (OceanModifierData *)ptr->data; - omd->refresh |= (MOD_OCEAN_REFRESH_RESET | MOD_OCEAN_REFRESH_SIM | MOD_OCEAN_REFRESH_CLEAR_CACHE); - - rna_Modifier_update(bmain, scene, ptr); -} - -static void rna_OceanModifier_sim_update(Main *bmain, Scene *scene, PointerRNA *ptr) -{ - OceanModifierData *omd = (OceanModifierData *)ptr->data; - - omd->refresh |= MOD_OCEAN_REFRESH_SIM; - - rna_Modifier_update(bmain, scene, ptr); -} - -static void rna_OceanModifier_topology_update(Main *bmain, Scene *scene, PointerRNA *ptr) -{ - OceanModifierData *omd = (OceanModifierData *)ptr->data; - - omd->refresh |= MOD_OCEAN_REFRESH_TOPOLOGY; + omd->refresh |= MOD_OCEAN_REFRESH_RESET | MOD_OCEAN_REFRESH_CLEAR_CACHE; rna_Modifier_update(bmain, scene, ptr); } @@ -775,7 +757,7 @@ static void rna_OceanModifier_ocean_chop_set(PointerRNA *ptr, float value) } } -static int rna_LaplacianDeformModifier_is_bind_get(PointerRNA *ptr) +static bool rna_LaplacianDeformModifier_is_bind_get(PointerRNA *ptr) { LaplacianDeformModifierData *lmd = (LaplacianDeformModifierData *)ptr->data; return ((lmd->flag & MOD_LAPLACIANDEFORM_BIND) && (lmd->cache_system != NULL)); @@ -1129,13 +1111,13 @@ static void rna_CorrectiveSmoothModifier_rest_source_update(Main *bmain, Scene * rna_CorrectiveSmoothModifier_update(bmain, scene, ptr); } -static int rna_CorrectiveSmoothModifier_is_bind_get(PointerRNA *ptr) +static bool rna_CorrectiveSmoothModifier_is_bind_get(PointerRNA *ptr) { CorrectiveSmoothModifierData *csmd = (CorrectiveSmoothModifierData *)ptr->data; return (csmd->bind_coords != NULL); } -static int rna_SurfaceDeformModifier_is_bound_get(PointerRNA *ptr) +static bool rna_SurfaceDeformModifier_is_bound_get(PointerRNA *ptr) { return (((SurfaceDeformModifierData *)ptr->data)->verts != NULL); } @@ -1155,7 +1137,7 @@ static void rna_MeshSequenceCache_object_path_update(Main *bmain, Scene *scene, rna_Modifier_update(bmain, scene, ptr); } -static int rna_ParticleInstanceModifier_particle_system_poll(PointerRNA *ptr, const PointerRNA value) +static bool rna_ParticleInstanceModifier_particle_system_poll(PointerRNA *ptr, const PointerRNA value) { ParticleInstanceModifierData *psmd = ptr->data; ParticleSystem *psys = value.data; @@ -1164,7 +1146,7 @@ static int rna_ParticleInstanceModifier_particle_system_poll(PointerRNA *ptr, co return false; /* make sure psys is in the object */ - return BLI_findindex(&psmd->ob->particlesystem, psys) >= 0; + return BLI_findindex(&psmd->ob->particlesystem, psys) != -1; } static PointerRNA rna_ParticleInstanceModifier_particle_system_get(PointerRNA *ptr) @@ -4070,7 +4052,7 @@ static void rna_def_modifier_ocean(BlenderRNA *brna) RNA_def_property_float_sdna(prop, NULL, "size"); RNA_def_property_ui_text(prop, "Size", "Surface scale factor (does not affect the height of the waves)"); RNA_def_property_ui_range(prop, -FLT_MAX, FLT_MAX, 1, -1); - RNA_def_property_update(prop, 0, "rna_OceanModifier_topology_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "repeat_x", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "repeat_x"); @@ -4078,7 +4060,7 @@ static void rna_def_modifier_ocean(BlenderRNA *brna) RNA_def_property_range(prop, 1, 1024); RNA_def_property_ui_range(prop, 1, 100, 1, -1); RNA_def_property_ui_text(prop, "Repeat X", "Repetitions of the generated surface in X"); - RNA_def_property_update(prop, 0, "rna_OceanModifier_topology_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "repeat_y", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "repeat_y"); @@ -4086,7 +4068,7 @@ static void rna_def_modifier_ocean(BlenderRNA *brna) RNA_def_property_range(prop, 1, 1024); RNA_def_property_ui_range(prop, 1, 100, 1, -1); RNA_def_property_ui_text(prop, "Repeat Y", "Repetitions of the generated surface in Y"); - RNA_def_property_update(prop, 0, "rna_OceanModifier_topology_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "use_normals", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_OCEAN_GENERATE_NORMALS); @@ -4150,7 +4132,7 @@ static void rna_def_modifier_ocean(BlenderRNA *brna) prop = RNA_def_property(srna, "wave_scale", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_float_sdna(prop, NULL, "wave_scale"); RNA_def_property_ui_text(prop, "Wave Scale", "Scale of the displacement effect"); - RNA_def_property_update(prop, 0, "rna_OceanModifier_sim_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "depth", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_sdna(prop, NULL, "depth"); @@ -4182,13 +4164,13 @@ static void rna_def_modifier_ocean(BlenderRNA *brna) "Choppiness of the wave's crest (adds some horizontal component to the displacement)"); RNA_def_property_ui_range(prop, 0.0, 4.0, 3, -1); RNA_def_property_float_funcs(prop, NULL, "rna_OceanModifier_ocean_chop_set", NULL); - RNA_def_property_update(prop, 0, "rna_OceanModifier_sim_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "time", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_float_sdna(prop, NULL, "time"); RNA_def_property_ui_text(prop, "Time", "Current time of the simulation"); RNA_def_property_ui_range(prop, -FLT_MAX, FLT_MAX, 1, -1); - RNA_def_property_update(prop, 0, "rna_OceanModifier_sim_update"); + RNA_def_property_update(prop, 0, "rna_Modifier_update"); prop = RNA_def_property(srna, "random_seed", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "seed"); diff --git a/source/blender/makesrna/intern/rna_nla.c b/source/blender/makesrna/intern/rna_nla.c index d76f2ccf4437..09b194d0e1b6 100644 --- a/source/blender/makesrna/intern/rna_nla.c +++ b/source/blender/makesrna/intern/rna_nla.c @@ -254,7 +254,7 @@ static void rna_NlaStrip_blend_out_set(PointerRNA *ptr, float value) data->blendout = value; } -static void rna_NlaStrip_use_auto_blend_set(PointerRNA *ptr, int value) +static void rna_NlaStrip_use_auto_blend_set(PointerRNA *ptr, bool value) { NlaStrip *data = (NlaStrip *)ptr->data; @@ -330,7 +330,7 @@ static void rna_NlaStrip_action_end_frame_set(PointerRNA *ptr, float value) BKE_nlastrip_recalculate_bounds(data); } -static void rna_NlaStrip_animated_influence_set(PointerRNA *ptr, int value) +static void rna_NlaStrip_animated_influence_set(PointerRNA *ptr, bool value) { NlaStrip *data = (NlaStrip *)ptr->data; @@ -343,7 +343,7 @@ static void rna_NlaStrip_animated_influence_set(PointerRNA *ptr, int value) data->flag &= ~NLASTRIP_FLAG_USR_INFLUENCE; } -static void rna_NlaStrip_animated_time_set(PointerRNA *ptr, int value) +static void rna_NlaStrip_animated_time_set(PointerRNA *ptr, bool value) { NlaStrip *data = (NlaStrip *)ptr->data; @@ -434,7 +434,7 @@ static void rna_NlaStrip_remove(NlaTrack *track, bContext *C, ReportList *report /* Set the 'solo' setting for the given NLA-track, making sure that it is the only one * that has this status in its AnimData block. */ -static void rna_NlaTrack_solo_set(PointerRNA *ptr, int value) +static void rna_NlaTrack_solo_set(PointerRNA *ptr, bool value) { NlaTrack *data = (NlaTrack *)ptr->data; AnimData *adt = BKE_animdata_from_id(ptr->id.data); diff --git a/source/blender/makesrna/intern/rna_nodetree.c b/source/blender/makesrna/intern/rna_nodetree.c index eb6459eb8492..e0895cfa20bc 100644 --- a/source/blender/makesrna/intern/rna_nodetree.c +++ b/source/blender/makesrna/intern/rna_nodetree.c @@ -143,6 +143,10 @@ const EnumPropertyItem rna_enum_node_math_items[] = { {NODE_MATH_MOD, "MODULO", 0, "Modulo", ""}, {NODE_MATH_ABS, "ABSOLUTE", 0, "Absolute", ""}, {NODE_MATH_ATAN2, "ARCTAN2", 0, "Arctan2", ""}, + {NODE_MATH_FLOOR, "FLOOR", 0, "Floor", ""}, + {NODE_MATH_CEIL, "CEIL", 0, "Ceil", ""}, + {NODE_MATH_FRACT, "FRACT", 0, "Fract", ""}, + {NODE_MATH_SQRT, "SQRT", 0, "Square Root", ""}, {0, NULL, 0, NULL, NULL} }; @@ -256,7 +260,7 @@ bNodeTreeType *rna_node_tree_type_from_enum(int value) return result; } -const EnumPropertyItem *rna_node_tree_type_itemf(void *data, int (*poll)(void *data, bNodeTreeType *), bool *r_free) +const EnumPropertyItem *rna_node_tree_type_itemf(void *data, bool (*poll)(void *data, bNodeTreeType *), bool *r_free) { EnumPropertyItem tmp = {0}; EnumPropertyItem *item = NULL; @@ -332,7 +336,7 @@ bNodeType *rna_node_type_from_enum(int value) return result; } -const EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, bNodeType *), bool *r_free) +const EnumPropertyItem *rna_node_type_itemf(void *data, bool (*poll)(void *data, bNodeType *), bool *r_free) { EnumPropertyItem *item = NULL; EnumPropertyItem tmp = {0}; @@ -407,7 +411,7 @@ bNodeSocketType *rna_node_socket_type_from_enum(int value) } const EnumPropertyItem *rna_node_socket_type_itemf( - void *data, int (*poll)(void *data, bNodeSocketType *), bool *r_free) + void *data, bool (*poll)(void *data, bNodeSocketType *), bool *r_free) { EnumPropertyItem *item = NULL; EnumPropertyItem tmp = {0}; @@ -539,7 +543,7 @@ static StructRNA *rna_NodeTree_refine(struct PointerRNA *ptr) return &RNA_NodeTree; } -static int rna_NodeTree_poll(const bContext *C, bNodeTreeType *ntreetype) +static bool rna_NodeTree_poll(const bContext *C, bNodeTreeType *ntreetype) { extern FunctionRNA rna_NodeTree_poll_func; @@ -557,7 +561,7 @@ static int rna_NodeTree_poll(const bContext *C, bNodeTreeType *ntreetype) ntreetype->ext.call((bContext *)C, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); @@ -801,7 +805,7 @@ static void rna_NodeTree_active_node_set(PointerRNA *ptr, const PointerRNA value static bNodeLink *rna_NodeTree_link_new(bNodeTree *ntree, Main *bmain, ReportList *reports, bNodeSocket *fromsock, bNodeSocket *tosock, - int verify_limits) + bool verify_limits) { bNodeLink *ret; bNode *fromnode = NULL, *tonode = NULL; @@ -1098,7 +1102,7 @@ static void rna_NodeTree_interface_update(bNodeTree *ntree, bContext *C) /* ******** NodeLink ******** */ -static int rna_NodeLink_is_hidden_get(PointerRNA *ptr) +static bool rna_NodeLink_is_hidden_get(PointerRNA *ptr) { bNodeLink *link = ptr->data; return nodeLinkIsHidden(link); @@ -1153,7 +1157,7 @@ char *rna_Node_ImageUser_path(PointerRNA *ptr) return NULL; } -static int rna_Node_poll(bNodeType *ntype, bNodeTree *ntree) +static bool rna_Node_poll(bNodeType *ntype, bNodeTree *ntree) { extern FunctionRNA rna_Node_poll_func; @@ -1161,7 +1165,7 @@ static int rna_Node_poll(bNodeType *ntype, bNodeTree *ntree) ParameterList list; FunctionRNA *func; void *ret; - int visible; + bool visible; RNA_pointer_create(NULL, ntype->ext.srna, NULL, &ptr); /* dummy */ func = &rna_Node_poll_func; /* RNA_struct_find_function(&ptr, "poll"); */ @@ -1171,14 +1175,14 @@ static int rna_Node_poll(bNodeType *ntype, bNodeTree *ntree) ntype->ext.call(NULL, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); return visible; } -static int rna_Node_poll_instance(bNode *node, bNodeTree *ntree) +static bool rna_Node_poll_instance(bNode *node, bNodeTree *ntree) { extern FunctionRNA rna_Node_poll_instance_func; @@ -1186,7 +1190,7 @@ static int rna_Node_poll_instance(bNode *node, bNodeTree *ntree) ParameterList list; FunctionRNA *func; void *ret; - int visible; + bool visible; RNA_pointer_create(NULL, node->typeinfo->ext.srna, node, &ptr); /* dummy */ func = &rna_Node_poll_instance_func; /* RNA_struct_find_function(&ptr, "poll_instance"); */ @@ -1196,14 +1200,14 @@ static int rna_Node_poll_instance(bNode *node, bNodeTree *ntree) node->typeinfo->ext.call(NULL, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); return visible; } -static int rna_Node_poll_instance_default(bNode *node, bNodeTree *ntree) +static bool rna_Node_poll_instance_default(bNode *node, bNodeTree *ntree) { /* use the basic poll function */ return rna_Node_poll(node->typeinfo, ntree); @@ -1352,7 +1356,7 @@ static void rna_Node_draw_label(bNodeTree *ntree, bNode *node, char *label, int RNA_parameter_list_free(&list); } -static int rna_Node_is_registered_node_type(StructRNA *type) +static bool rna_Node_is_registered_node_type(StructRNA *type) { return (RNA_struct_blender_type_get(type) != NULL); } @@ -1569,7 +1573,7 @@ static void rna_Node_parent_set(PointerRNA *ptr, PointerRNA value) } } -static int rna_Node_parent_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_Node_parent_poll(PointerRNA *ptr, PointerRNA value) { bNode *node = ptr->data; bNode *parent = value.data; @@ -1599,7 +1603,7 @@ static void rna_Node_socket_value_update(ID *id, bNode *node, bContext *C) ED_node_tag_update_nodetree(CTX_data_main(C), (bNodeTree *)id, node); } -static void rna_Node_select_set(PointerRNA *ptr, int value) +static void rna_Node_select_set(PointerRNA *ptr, bool value) { bNode *node = (bNode *)ptr->data; nodeSetSelected(node, value); @@ -1969,7 +1973,7 @@ static void rna_NodeSocket_update(Main *bmain, Scene *UNUSED(scene), PointerRNA } } -static int rna_NodeSocket_is_output_get(PointerRNA *ptr) +static bool rna_NodeSocket_is_output_get(PointerRNA *ptr) { bNodeSocket *sock = ptr->data; return sock->in_out == SOCK_OUT; @@ -1981,7 +1985,7 @@ static void rna_NodeSocket_link_limit_set(PointerRNA *ptr, int value) sock->limit = (value == 0 ? 0xFFF : value); } -static void rna_NodeSocket_hide_set(PointerRNA *ptr, int value) +static void rna_NodeSocket_hide_set(PointerRNA *ptr, bool value) { bNodeSocket *sock = (bNodeSocket *)ptr->data; @@ -2412,13 +2416,13 @@ static PointerRNA rna_NodeInternal_output_template(StructRNA *srna, int index) return PointerRNA_NULL; } -static int rna_NodeInternal_poll(StructRNA *srna, bNodeTree *ntree) +static bool rna_NodeInternal_poll(StructRNA *srna, bNodeTree *ntree) { bNodeType *ntype = RNA_struct_blender_type_get(srna); return ntype && (!ntype->poll || ntype->poll(ntype, ntree)); } -static int rna_NodeInternal_poll_instance(bNode *node, bNodeTree *ntree) +static bool rna_NodeInternal_poll_instance(bNode *node, bNodeTree *ntree) { bNodeType *ntype = node->typeinfo; if (ntype->poll_instance) { @@ -2532,7 +2536,7 @@ static void rna_NodeGroup_node_tree_set(PointerRNA *ptr, const PointerRNA value) } } -static int rna_NodeGroup_node_tree_poll(PointerRNA *ptr, const PointerRNA value) +static bool rna_NodeGroup_node_tree_poll(PointerRNA *ptr, const PointerRNA value) { bNodeTree *ntree = ptr->id.data; bNodeTree *ngroup = value.data; @@ -2699,7 +2703,7 @@ static const EnumPropertyItem *rna_Node_image_layer_itemf(bContext *UNUSED(C), P return item; } -static int rna_Node_image_has_layers_get(PointerRNA *ptr) +static bool rna_Node_image_has_layers_get(PointerRNA *ptr) { bNode *node = (bNode *)ptr->data; Image *ima = (Image *)node->id; @@ -2709,7 +2713,7 @@ static int rna_Node_image_has_layers_get(PointerRNA *ptr) return RE_layers_have_name(ima->rr); } -static int rna_Node_image_has_views_get(PointerRNA *ptr) +static bool rna_Node_image_has_views_get(PointerRNA *ptr) { bNode *node = (bNode *)ptr->data; Image *ima = (Image *)node->id; @@ -2888,6 +2892,48 @@ static void rna_NodeColorBalance_update_cdl(Main *bmain, Scene *scene, PointerRN rna_Node_update(bmain, scene, ptr); } +static void rna_NodeCryptomatte_matte_get(PointerRNA *ptr, char *value) +{ + bNode *node = (bNode *)ptr->data; + NodeCryptomatte *nc = node->storage; + + strcpy(value, (nc->matte_id) ? nc->matte_id : ""); +} + +static int rna_NodeCryptomatte_matte_length(PointerRNA *ptr) +{ + bNode *node = (bNode *)ptr->data; + NodeCryptomatte *nc = node->storage; + + return (nc->matte_id) ? strlen(nc->matte_id) : 0; +} + +static void rna_NodeCryptomatte_matte_set(PointerRNA *ptr, const char *value) +{ + bNode *node = (bNode *)ptr->data; + NodeCryptomatte *nc = node->storage; + + if (nc->matte_id) + MEM_freeN(nc->matte_id); + + if (value && value[0]) + nc->matte_id = BLI_strdup(value); + else + nc->matte_id = NULL; +} + +static void rna_NodeCryptomatte_update_add(Main *bmain, Scene *scene, PointerRNA *ptr) +{ + ntreeCompositCryptomatteSyncFromAdd(ptr->id.data, ptr->data); + rna_Node_update(bmain, scene, ptr); +} + +static void rna_NodeCryptomatte_update_remove(Main *bmain, Scene *scene, PointerRNA *ptr) +{ + ntreeCompositCryptomatteSyncFromRemove(ptr->id.data, ptr->data); + rna_Node_update(bmain, scene, ptr); +} + /* ******** Node Socket Types ******** */ static PointerRNA rna_NodeOutputFile_slot_layer_get(CollectionPropertyIterator *iter) @@ -3063,16 +3109,7 @@ static void rna_ShaderNodeScript_update(Main *bmain, Scene *scene, PointerRNA *p ED_node_tag_update_nodetree(bmain, ntree, node); } -static void rna_ShaderNodePrincipled_update(Main *bmain, Scene *scene, PointerRNA *ptr) -{ - bNodeTree *ntree = (bNodeTree *)ptr->id.data; - bNode *node = (bNode *)ptr->data; - - nodeUpdate(ntree, node); - rna_Node_update(bmain, scene, ptr); -} - -static void rna_ShaderNodeSubsurface_update(Main *bmain, Scene *scene, PointerRNA *ptr) +static void rna_ShaderNode_socket_update(Main *bmain, Scene *scene, PointerRNA *ptr) { bNodeTree *ntree = (bNodeTree *)ptr->id.data; bNode *node = (bNode *)ptr->data; @@ -3325,6 +3362,13 @@ static const EnumPropertyItem node_hair_items[] = { {0, NULL, 0, NULL, NULL} }; +static const EnumPropertyItem node_principled_hair_items[] = { + {SHD_PRINCIPLED_HAIR_DIRECT_ABSORPTION, "ABSORPTION", 0, "Absorption coefficient", "Directly set the absorption coefficient sigma_a. This is not the most intuitive way to color hair."}, + {SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION, "MELANIN", 0, "Melanin concentration", "Define the melanin concentrations below to get the most realistic-looking hair. You can get the concentrations for different types of hair online."}, + {SHD_PRINCIPLED_HAIR_REFLECTANCE, "COLOR", 0, "Direct coloring", "Choose the color of your preference, and the shader will approximate the absorption coefficient to render lookalike hair."}, + {0, NULL, 0, NULL, NULL} +}; + static const EnumPropertyItem node_script_mode_items[] = { {NODE_SCRIPT_INTERNAL, "INTERNAL", 0, "Internal", "Use internal text data-block"}, {NODE_SCRIPT_EXTERNAL, "EXTERNAL", 0, "External", "Use external .osl or .oso file"}, @@ -4035,6 +4079,23 @@ static void def_sh_tex_voronoi(StructRNA *srna) {0, NULL, 0, NULL, NULL} }; + static EnumPropertyItem prop_distance_items[] = { + { SHD_VORONOI_DISTANCE, "DISTANCE", 0, "Distance", "Distance" }, + { SHD_VORONOI_MANHATTAN, "MANHATTAN", 0, "Manhattan", "Manhattan (city block) distance" }, + { SHD_VORONOI_CHEBYCHEV, "CHEBYCHEV", 0, "Chebychev", "Chebychev distance" }, + { SHD_VORONOI_MINKOWSKI, "MINKOWSKI", 0, "Minkowski", "Minkowski distance" }, + { 0, NULL, 0, NULL, NULL } + }; + + static EnumPropertyItem prop_feature_items[] = { + { SHD_VORONOI_F1, "F1", 0, "Closest", "Closest point" }, + { SHD_VORONOI_F2, "F2", 0, "2nd Closest", "2nd closest point" }, + { SHD_VORONOI_F3, "F3", 0, "3rd Closest", "3rd closest point" }, + { SHD_VORONOI_F4, "F4", 0, "4th Closest", "4th closest point" }, + { SHD_VORONOI_F2F1, "F2F1", 0, "Crackle", "Difference between 2nd and 1st closest point" }, + { 0, NULL, 0, NULL, NULL } + }; + PropertyRNA *prop; RNA_def_struct_sdna_from(srna, "NodeTexVoronoi", "storage"); @@ -4045,6 +4106,18 @@ static void def_sh_tex_voronoi(StructRNA *srna) RNA_def_property_enum_items(prop, prop_coloring_items); RNA_def_property_ui_text(prop, "Coloring", ""); RNA_def_property_update(prop, 0, "rna_Node_update"); + + prop = RNA_def_property(srna, "distance", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_sdna(prop, NULL, "distance"); + RNA_def_property_enum_items(prop, prop_distance_items); + RNA_def_property_ui_text(prop, "Distance metric", ""); + RNA_def_property_update(prop, 0, "rna_ShaderNode_socket_update"); + + prop = RNA_def_property(srna, "feature", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_sdna(prop, NULL, "feature"); + RNA_def_property_enum_items(prop, prop_feature_items); + RNA_def_property_ui_text(prop, "Feature Output", ""); + RNA_def_property_update(prop, 0, "rna_Node_update"); } static void def_sh_tex_wave(StructRNA *srna) @@ -4316,13 +4389,13 @@ static void def_principled(StructRNA *srna) RNA_def_property_enum_sdna(prop, NULL, "custom1"); RNA_def_property_enum_items(prop, node_principled_distribution_items); RNA_def_property_ui_text(prop, "Distribution", ""); - RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNodePrincipled_update"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNode_socket_update"); prop = RNA_def_property(srna, "subsurface_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "custom2"); RNA_def_property_enum_items(prop, node_subsurface_method_items); RNA_def_property_ui_text(prop, "Subsurface Method", "Method for rendering subsurface scattering"); - RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNodePrincipled_update"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNode_socket_update"); } static void def_refraction(StructRNA *srna) @@ -4379,6 +4452,21 @@ static void def_hair(StructRNA *srna) RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update"); } +/* RNA initialization for the custom property. */ +static void def_hair_principled(StructRNA *srna) +{ + PropertyRNA *prop; + + prop = RNA_def_property(srna, "parametrization", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_sdna(prop, NULL, "custom1"); + RNA_def_property_ui_text(prop, "Color parametrization", "Select the shader's color parametrization"); + RNA_def_property_enum_items(prop, node_principled_hair_items); + RNA_def_property_enum_default(prop, SHD_PRINCIPLED_HAIR_REFLECTANCE); + /* Upon editing, update both the node data AND the UI representation */ + /* (This effectively shows/hides the relevant sockets) */ + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNode_socket_update"); +} + static void def_sh_uvmap(StructRNA *srna) { PropertyRNA *prop; @@ -4557,7 +4645,7 @@ static void def_sh_subsurface(StructRNA *srna) RNA_def_property_enum_sdna(prop, NULL, "custom1"); RNA_def_property_enum_items(prop, prop_subsurface_falloff_items); RNA_def_property_ui_text(prop, "Falloff", "Function to determine how much light nearby points contribute based on their distance to the shading point"); - RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNodeSubsurface_update"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNode_socket_update"); } static void def_sh_tex_ies(StructRNA *srna) @@ -6989,6 +7077,32 @@ static void def_cmp_sunbeams(StructRNA *srna) RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update"); } +static void def_cmp_cryptomatte(StructRNA *srna) +{ + PropertyRNA *prop; + static float default_1[3] = {1.f, 1.f, 1.f}; + + RNA_def_struct_sdna_from(srna, "NodeCryptomatte", "storage"); + prop = RNA_def_property(srna, "matte_id", PROP_STRING, PROP_NONE); + RNA_def_property_string_funcs(prop, "rna_NodeCryptomatte_matte_get", "rna_NodeCryptomatte_matte_length", + "rna_NodeCryptomatte_matte_set"); + RNA_def_property_ui_text(prop, "Matte Objects", "List of object and material crypto IDs to include in matte"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update"); + + + prop = RNA_def_property(srna, "add", PROP_FLOAT, PROP_COLOR); + RNA_def_property_float_array_default(prop, default_1); + RNA_def_property_range(prop, -FLT_MAX, FLT_MAX); + RNA_def_property_ui_text(prop, "Add", "Add object or material to matte, by picking a color from the Pick output"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeCryptomatte_update_add"); + + prop = RNA_def_property(srna, "remove", PROP_FLOAT, PROP_COLOR); + RNA_def_property_float_array_default(prop, default_1); + RNA_def_property_range(prop, -FLT_MAX, FLT_MAX); + RNA_def_property_ui_text(prop, "Remove", "Remove object or material from matte, by picking a color from the Pick output"); + RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeCryptomatte_update_remove"); +} + /* -- Texture Nodes --------------------------------------------------------- */ static void def_tex_output(StructRNA *srna) diff --git a/source/blender/makesrna/intern/rna_object.c b/source/blender/makesrna/intern/rna_object.c index 5fc0ed19f11e..fc634bf56160 100644 --- a/source/blender/makesrna/intern/rna_object.c +++ b/source/blender/makesrna/intern/rna_object.c @@ -383,6 +383,9 @@ static void rna_Object_data_set(PointerRNA *ptr, PointerRNA value) return; } + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BLI_assert(BKE_id_is_in_gobal_main(id)); + if (ob->type == OB_EMPTY) { if (ob->data) { id_us_min((ID *)ob->data); @@ -395,7 +398,7 @@ static void rna_Object_data_set(PointerRNA *ptr, PointerRNA value) } } else if (ob->type == OB_MESH) { - BKE_mesh_assign_object(G.main, ob, (Mesh *)id); + BKE_mesh_assign_object(G_MAIN, ob, (Mesh *)id); } else { if (ob->data) { @@ -407,7 +410,7 @@ static void rna_Object_data_set(PointerRNA *ptr, PointerRNA value) id_us_plus(id); ob->data = id; - test_object_materials(G.main, ob, id); + test_object_materials(G_MAIN, ob, id); if (GS(id->name) == ID_CU) BKE_curve_type_test(ob); @@ -716,7 +719,9 @@ static void rna_Object_active_material_set(PointerRNA *ptr, PointerRNA value) Object *ob = (Object *)ptr->id.data; DAG_id_tag_update(value.data, 0); - assign_material(G.main, ob, value.data, ob->actcol, BKE_MAT_ASSIGN_EXISTING); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BLI_assert(BKE_id_is_in_gobal_main(value.data)); + assign_material(G_MAIN, ob, value.data, ob->actcol, BKE_MAT_ASSIGN_EXISTING); } static int rna_Object_active_material_editable(PointerRNA *ptr, const char **UNUSED(r_info)) @@ -888,7 +893,9 @@ static void rna_MaterialSlot_material_set(PointerRNA *ptr, PointerRNA value) Object *ob = (Object *)ptr->id.data; int index = (Material **)ptr->data - ob->mat; - assign_material(G.main, ob, value.data, index + 1, BKE_MAT_ASSIGN_EXISTING); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BLI_assert(BKE_id_is_in_gobal_main(value.data)); + assign_material(G_MAIN, ob, value.data, index + 1, BKE_MAT_ASSIGN_EXISTING); } static int rna_MaterialSlot_link_get(PointerRNA *ptr) @@ -1095,7 +1102,7 @@ static PointerRNA rna_Object_game_settings_get(PointerRNA *ptr) } -static unsigned int rna_Object_layer_validate__internal(const int *values, unsigned int lay) +static unsigned int rna_Object_layer_validate__internal(const bool *values, unsigned int lay) { int i, tot = 0; @@ -1115,7 +1122,7 @@ static unsigned int rna_Object_layer_validate__internal(const int *values, unsig return lay; } -static void rna_Object_layer_set(PointerRNA *ptr, const int *values) +static void rna_Object_layer_set(PointerRNA *ptr, const bool *values) { Object *ob = (Object *)ptr->data; unsigned int lay; @@ -1125,7 +1132,7 @@ static void rna_Object_layer_set(PointerRNA *ptr, const int *values) ob->lay = lay; } -static void rna_Base_layer_set(PointerRNA *ptr, const int *values) +static void rna_Base_layer_set(PointerRNA *ptr, const bool *values) { Base *base = (Base *)ptr->data; @@ -1137,7 +1144,7 @@ static void rna_Base_layer_set(PointerRNA *ptr, const int *values) /* rna_Base_layer_update updates the objects layer */ } -static void rna_GameObjectSettings_state_get(PointerRNA *ptr, int *values) +static void rna_GameObjectSettings_state_get(PointerRNA *ptr, bool *values) { Object *ob = (Object *)ptr->data; int i; @@ -1149,7 +1156,7 @@ static void rna_GameObjectSettings_state_get(PointerRNA *ptr, int *values) } } -static void rna_GameObjectSettings_state_set(PointerRNA *ptr, const int *values) +static void rna_GameObjectSettings_state_set(PointerRNA *ptr, const bool *values) { Object *ob = (Object *)ptr->data; int i, tot = 0; @@ -1168,7 +1175,7 @@ static void rna_GameObjectSettings_state_set(PointerRNA *ptr, const int *values) } } -static void rna_GameObjectSettings_used_state_get(PointerRNA *ptr, int *values) +static void rna_GameObjectSettings_used_state_get(PointerRNA *ptr, bool *values) { Object *ob = (Object *)ptr->data; bController *cont; @@ -1184,7 +1191,7 @@ static void rna_GameObjectSettings_used_state_get(PointerRNA *ptr, int *values) } } -static void rna_GameObjectSettings_col_group_get(PointerRNA *ptr, int *values) +static void rna_GameObjectSettings_col_group_get(PointerRNA *ptr, bool *values) { Object *ob = (Object *)ptr->data; int i; @@ -1194,7 +1201,7 @@ static void rna_GameObjectSettings_col_group_get(PointerRNA *ptr, int *values) } } -static void rna_GameObjectSettings_col_group_set(PointerRNA *ptr, const int *values) +static void rna_GameObjectSettings_col_group_set(PointerRNA *ptr, const bool *values) { Object *ob = (Object *)ptr->data; int i, tot = 0; @@ -1213,7 +1220,7 @@ static void rna_GameObjectSettings_col_group_set(PointerRNA *ptr, const int *val } } -static void rna_GameObjectSettings_col_mask_get(PointerRNA *ptr, int *values) +static void rna_GameObjectSettings_col_mask_get(PointerRNA *ptr, bool *values) { Object *ob = (Object *)ptr->data; int i; @@ -1223,7 +1230,7 @@ static void rna_GameObjectSettings_col_mask_get(PointerRNA *ptr, int *values) } } -static void rna_GameObjectSettings_col_mask_set(PointerRNA *ptr, const int *values) +static void rna_GameObjectSettings_col_mask_set(PointerRNA *ptr, const bool *values) { Object *ob = (Object *)ptr->data; int i, tot = 0; @@ -1473,32 +1480,32 @@ static float rna_VertexGroup_weight(ID *id, bDeformGroup *dg, ReportList *report } /* generic poll functions */ -int rna_Lattice_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Lattice_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_LATTICE; } -int rna_Curve_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Curve_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_CURVE; } -int rna_Armature_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Armature_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_ARMATURE; } -int rna_Mesh_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Mesh_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_MESH; } -int rna_Camera_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Camera_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_CAMERA; } -int rna_Lamp_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +bool rna_Lamp_object_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { return ((Object *)value.id.data)->type == OB_LAMP; } @@ -1509,7 +1516,7 @@ int rna_DupliObject_index_get(PointerRNA *ptr) return dob->persistent_id[0]; } -int rna_Object_use_dynamic_topology_sculpting_get(PointerRNA *ptr) +bool rna_Object_use_dynamic_topology_sculpting_get(PointerRNA *ptr) { SculptSession *ss = ((Object *)ptr->id.data)->sculpt; return (ss && ss->bm); diff --git a/source/blender/makesrna/intern/rna_object_api.c b/source/blender/makesrna/intern/rna_object_api.c index 6131b7adac8a..376a89c65d14 100644 --- a/source/blender/makesrna/intern/rna_object_api.c +++ b/source/blender/makesrna/intern/rna_object_api.c @@ -141,7 +141,7 @@ static void rna_Object_camera_fit_coords( /* settings: 0 - preview, 1 - render */ static Mesh *rna_Object_to_mesh( Object *ob, Main *bmain, ReportList *reports, Scene *sce, - int apply_modifiers, int settings, int calc_tessface, int calc_undeformed) + bool apply_modifiers, int settings, bool calc_tessface, bool calc_undeformed) { return rna_Main_meshes_new_from_object(bmain, reports, sce, ob, apply_modifiers, settings, calc_tessface, calc_undeformed); } @@ -226,7 +226,7 @@ static void rna_Object_free_duplilist(Object *ob) } static PointerRNA rna_Object_shape_key_add(Object *ob, bContext *C, ReportList *reports, - const char *name, int from_mix) + const char *name, bool from_mix) { Main *bmain = CTX_data_main(C); KeyBlock *kb = NULL; @@ -268,7 +268,7 @@ static void rna_Object_shape_key_remove( RNA_POINTER_INVALIDATE(kb_ptr); } -static int rna_Object_is_visible(Object *ob, Scene *sce) +static bool rna_Object_is_visible(Object *ob, Scene *sce) { return !(ob->restrictflag & OB_RESTRICT_VIEW) && (ob->lay & sce->lay); } @@ -320,7 +320,7 @@ static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt) static void rna_Object_ray_cast( Object *ob, ReportList *reports, float origin[3], float direction[3], float distance, - int *r_success, float r_location[3], float r_normal[3], int *r_index) + bool *r_success, float r_location[3], float r_normal[3], int *r_index) { bool success = false; @@ -332,8 +332,10 @@ static void rna_Object_ray_cast( /* Test BoundBox first (efficiency) */ BoundBox *bb = BKE_object_boundbox_get(ob); float distmin; - if (!bb || (isect_ray_aabb_v3_simple(origin, direction, bb->vec[0], bb->vec[6], &distmin, NULL) && distmin <= distance)) { - + normalize_v3(direction); /* Needed for valid distance check from isect_ray_aabb_v3_simple() call. */ + if (!bb || + (isect_ray_aabb_v3_simple(origin, direction, bb->vec[0], bb->vec[6], &distmin, NULL) && distmin <= distance)) + { BVHTreeFromMesh treeData = {NULL}; /* no need to managing allocation or freeing of the BVH data. this is generated and freed as needed */ @@ -346,9 +348,6 @@ static void rna_Object_ray_cast( hit.index = -1; hit.dist = distance; - normalize_v3(direction); - - if (BLI_bvhtree_ray_cast(treeData.tree, origin, direction, 0.0f, &hit, treeData.raycast_callback, &treeData) != -1) { @@ -375,7 +374,7 @@ static void rna_Object_ray_cast( static void rna_Object_closest_point_on_mesh( Object *ob, ReportList *reports, float origin[3], float distance, - int *r_success, float r_location[3], float r_normal[3], int *r_index) + bool *r_success, float r_location[3], float r_normal[3], int *r_index) { BVHTreeFromMesh treeData = {NULL}; @@ -427,12 +426,12 @@ static void rna_ObjectBase_layers_from_view(Base *base, View3D *v3d) base->lay = base->object->lay = v3d->lay; } -static int rna_Object_is_modified(Object *ob, Scene *scene, int settings) +static bool rna_Object_is_modified(Object *ob, Scene *scene, int settings) { return BKE_object_is_modified(scene, ob) & settings; } -static int rna_Object_is_deform_modified(Object *ob, Scene *scene, int settings) +static bool rna_Object_is_deform_modified(Object *ob, Scene *scene, int settings) { return BKE_object_is_deform_modified(scene, ob) & settings; } @@ -475,7 +474,7 @@ void rna_Object_dm_info(struct Object *ob, int type, char *result) } #endif /* NDEBUG */ -static int rna_Object_update_from_editmode(Object *ob, Main *bmain) +static bool rna_Object_update_from_editmode(Object *ob, Main *bmain) { return ED_object_editmode_load(bmain, ob); } diff --git a/source/blender/makesrna/intern/rna_object_force.c b/source/blender/makesrna/intern/rna_object_force.c index 7e1105f5e35f..56b1c224a538 100644 --- a/source/blender/makesrna/intern/rna_object_force.c +++ b/source/blender/makesrna/intern/rna_object_force.c @@ -97,6 +97,7 @@ static const EnumPropertyItem empty_vortex_shape_items[] = { #include "BKE_context.h" #include "BKE_depsgraph.h" #include "BKE_global.h" +#include "BKE_library.h" #include "BKE_modifier.h" #include "BKE_pointcache.h" @@ -240,7 +241,8 @@ static void rna_Cache_active_point_cache_index_range(PointerRNA *ptr, int *min, PTCacheID *pid; ListBase pidlist; - BKE_ptcache_ids_from_object(G.main, &pidlist, ob, NULL, 0); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BKE_ptcache_ids_from_object(G_MAIN, &pidlist, ob, NULL, 0); *min = 0; *max = 0; @@ -263,7 +265,8 @@ static int rna_Cache_active_point_cache_index_get(PointerRNA *ptr) ListBase pidlist; int num = 0; - BKE_ptcache_ids_from_object(G.main, &pidlist, ob, NULL, 0); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BKE_ptcache_ids_from_object(G_MAIN, &pidlist, ob, NULL, 0); for (pid = pidlist.first; pid; pid = pid->next) { if (pid->cache == cache) { @@ -284,7 +287,8 @@ static void rna_Cache_active_point_cache_index_set(struct PointerRNA *ptr, int v PTCacheID *pid; ListBase pidlist; - BKE_ptcache_ids_from_object(G.main, &pidlist, ob, NULL, 0); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BKE_ptcache_ids_from_object(G_MAIN, &pidlist, ob, NULL, 0); for (pid = pidlist.first; pid; pid = pid->next) { if (pid->cache == cache) { @@ -307,7 +311,8 @@ static void rna_PointCache_frame_step_range(PointerRNA *ptr, int *min, int *max, *min = 1; *max = 20; - BKE_ptcache_ids_from_object(G.main, &pidlist, ob, NULL, 0); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BKE_ptcache_ids_from_object(G_MAIN, &pidlist, ob, NULL, 0); for (pid = pidlist.first; pid; pid = pid->next) { if (pid->cache == cache) { @@ -341,52 +346,52 @@ static char *rna_CollisionSettings_path(PointerRNA *UNUSED(ptr)) #endif } -static int rna_SoftBodySettings_use_edges_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_use_edges_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_EDGES) != 0); } -static void rna_SoftBodySettings_use_edges_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_use_edges_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_EDGES; else data->softflag &= ~OB_SB_EDGES; } -static int rna_SoftBodySettings_use_goal_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_use_goal_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_GOAL) != 0); } -static void rna_SoftBodySettings_use_goal_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_use_goal_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_GOAL; else data->softflag &= ~OB_SB_GOAL; } -static int rna_SoftBodySettings_stiff_quads_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_stiff_quads_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_QUADS) != 0); } -static void rna_SoftBodySettings_stiff_quads_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_stiff_quads_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_QUADS; else data->softflag &= ~OB_SB_QUADS; } -static int rna_SoftBodySettings_self_collision_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_self_collision_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_SELF) != 0); } -static void rna_SoftBodySettings_self_collision_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_self_collision_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_SELF; @@ -411,26 +416,26 @@ static void rna_SoftBodySettings_new_aero_set(PointerRNA *ptr, int value) data->softflag &= ~OB_SB_AERO_ANGLE; } -static int rna_SoftBodySettings_face_collision_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_face_collision_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_FACECOLL) != 0); } -static void rna_SoftBodySettings_face_collision_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_face_collision_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_FACECOLL; else data->softflag &= ~OB_SB_FACECOLL; } -static int rna_SoftBodySettings_edge_collision_get(PointerRNA *ptr) +static bool rna_SoftBodySettings_edge_collision_get(PointerRNA *ptr) { Object *data = (Object *)(ptr->id.data); return (((data->softflag) & OB_SB_EDGECOLL) != 0); } -static void rna_SoftBodySettings_edge_collision_set(PointerRNA *ptr, int value) +static void rna_SoftBodySettings_edge_collision_set(PointerRNA *ptr, bool value) { Object *data = (Object *)(ptr->id.data); if (value) data->softflag |= OB_SB_EDGECOLL; diff --git a/source/blender/makesrna/intern/rna_packedfile.c b/source/blender/makesrna/intern/rna_packedfile.c index c7891680adb6..51199af011b0 100644 --- a/source/blender/makesrna/intern/rna_packedfile.c +++ b/source/blender/makesrna/intern/rna_packedfile.c @@ -79,4 +79,3 @@ void RNA_def_packedfile(BlenderRNA *brna) } #endif - diff --git a/source/blender/makesrna/intern/rna_particle.c b/source/blender/makesrna/intern/rna_particle.c index 5d35342d7ed7..a2286f0b92a0 100644 --- a/source/blender/makesrna/intern/rna_particle.c +++ b/source/blender/makesrna/intern/rna_particle.c @@ -696,7 +696,7 @@ static void rna_Particle_change_physics_type(Main *bmain, Scene *scene, PointerR BLI_addtail(&state->rules, boid_new_rule(eBoidRuleType_Separate)); BLI_addtail(&state->rules, boid_new_rule(eBoidRuleType_Flock)); - ((BoidRule*)state->rules.first)->flag |= BOIDRULE_CURRENT; + ((BoidRule *)state->rules.first)->flag |= BOIDRULE_CURRENT; state->flag |= BOIDSTATE_CURRENT; BLI_addtail(&part->boids->states, state); @@ -935,7 +935,7 @@ static float rna_PartSetting_linelenhead_get(struct PointerRNA *ptr) } -static int rna_PartSettings_is_fluid_get(PointerRNA *ptr) +static bool rna_PartSettings_is_fluid_get(PointerRNA *ptr) { ParticleSettings *part = (ParticleSettings *)ptr->data; @@ -1095,19 +1095,19 @@ static char *rna_SPHFluidSettings_path(PointerRNA *ptr) return NULL; } -static int rna_ParticleSystem_multiple_caches_get(PointerRNA *ptr) +static bool rna_ParticleSystem_multiple_caches_get(PointerRNA *ptr) { ParticleSystem *psys = (ParticleSystem *)ptr->data; return (psys->ptcaches.first != psys->ptcaches.last); } -static int rna_ParticleSystem_editable_get(PointerRNA *ptr) +static bool rna_ParticleSystem_editable_get(PointerRNA *ptr) { ParticleSystem *psys = (ParticleSystem *)ptr->data; return psys_check_edited(psys); } -static int rna_ParticleSystem_edited_get(PointerRNA *ptr) +static bool rna_ParticleSystem_edited_get(PointerRNA *ptr) { ParticleSystem *psys = (ParticleSystem *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_pose.c b/source/blender/makesrna/intern/rna_pose.c index 746bb0ceacd5..e06aab8c4cc3 100644 --- a/source/blender/makesrna/intern/rna_pose.c +++ b/source/blender/makesrna/intern/rna_pose.c @@ -181,7 +181,7 @@ void rna_ActionGroup_colorset_set(PointerRNA *ptr, int value) } } -int rna_ActionGroup_is_custom_colorset_get(PointerRNA *ptr) +bool rna_ActionGroup_is_custom_colorset_get(PointerRNA *ptr) { bActionGroup *grp = ptr->data; @@ -287,10 +287,12 @@ static void rna_PoseChannel_name_set(PointerRNA *ptr, const char *value) BLI_strncpy_utf8(newname, value, sizeof(pchan->name)); BLI_strncpy(oldname, pchan->name, sizeof(pchan->name)); - ED_armature_bone_rename(G.main, ob->data, oldname, newname); + BLI_assert(BKE_id_is_in_gobal_main(&ob->id)); + BLI_assert(BKE_id_is_in_gobal_main(ob->data)); + ED_armature_bone_rename(G_MAIN, ob->data, oldname, newname); } -static int rna_PoseChannel_has_ik_get(PointerRNA *ptr) +static bool rna_PoseChannel_has_ik_get(PointerRNA *ptr) { Object *ob = (Object *)ptr->id.data; bPoseChannel *pchan = (bPoseChannel *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_pose_api.c b/source/blender/makesrna/intern/rna_pose_api.c index f523b725b188..04ecdd497f6b 100644 --- a/source/blender/makesrna/intern/rna_pose_api.c +++ b/source/blender/makesrna/intern/rna_pose_api.c @@ -84,4 +84,3 @@ void RNA_api_pose_channel(StructRNA *srna) #endif - diff --git a/source/blender/makesrna/intern/rna_property.c b/source/blender/makesrna/intern/rna_property.c index df4683b0ee4d..6084b21d8b12 100644 --- a/source/blender/makesrna/intern/rna_property.c +++ b/source/blender/makesrna/intern/rna_property.c @@ -200,4 +200,3 @@ void RNA_def_gameproperty(BlenderRNA *brna) } #endif - diff --git a/source/blender/makesrna/intern/rna_render.c b/source/blender/makesrna/intern/rna_render.c index 010bdb4a6faf..513717a9e461 100644 --- a/source/blender/makesrna/intern/rna_render.c +++ b/source/blender/makesrna/intern/rna_render.c @@ -123,7 +123,7 @@ static void engine_tag_update(RenderEngine *engine) engine->flag |= RE_ENGINE_DO_UPDATE; } -static int engine_support_display_space_shader(RenderEngine *UNUSED(engine), Scene *scene) +static bool engine_support_display_space_shader(RenderEngine *UNUSED(engine), Scene *scene) { return IMB_colormanagement_support_glsl_draw(&scene->view_settings); } @@ -613,6 +613,7 @@ static void rna_def_render_engine(BlenderRNA *brna) RNA_def_boolean(func, "use_spherical_stereo", 0, "Spherical Stereo", ""); parm = RNA_def_float_matrix(func, "r_model_matrix", 4, 4, NULL, 0.0f, 0.0f, "Model Matrix", "Normalized camera model matrix", 0.0f, 0.0f); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); + RNA_def_function_output(func, parm); func = RNA_def_function(srna, "use_spherical_stereo", "RE_engine_get_spherical_stereo"); parm = RNA_def_pointer(func, "camera", "Object", "", ""); diff --git a/source/blender/makesrna/intern/rna_rigidbody.c b/source/blender/makesrna/intern/rna_rigidbody.c index 25aac09efda4..5b86ec6b10db 100644 --- a/source/blender/makesrna/intern/rna_rigidbody.c +++ b/source/blender/makesrna/intern/rna_rigidbody.c @@ -76,6 +76,12 @@ const EnumPropertyItem rna_enum_rigidbody_constraint_type_items[] = { {RBC_TYPE_MOTOR, "MOTOR", ICON_NONE, "Motor", "Drive rigid body around or along an axis"}, {0, NULL, 0, NULL, NULL}}; +/* bullet spring type */ +static const EnumPropertyItem rna_enum_rigidbody_constraint_spring_type_items[] = { + {RBC_SPRING_TYPE1, "SPRING1", ICON_NONE, "Blender 2.7", "Spring implementation used in blender 2.7. Damping is capped at 1.0"}, + {RBC_SPRING_TYPE2, "SPRING2", ICON_NONE, "Blender 2.8", "New implementation available since 2.8"}, + {0, NULL, 0, NULL, NULL}}; + #ifndef RNA_RUNTIME /* mesh source for collision shape creation */ static const EnumPropertyItem rigidbody_mesh_source_items[] = { @@ -131,7 +137,7 @@ static void rna_RigidBodyWorld_num_solver_iterations_set(PointerRNA *ptr, int va #endif } -static void rna_RigidBodyWorld_split_impulse_set(PointerRNA *ptr, int value) +static void rna_RigidBodyWorld_split_impulse_set(PointerRNA *ptr, bool value) { RigidBodyWorld *rbw = (RigidBodyWorld *)ptr->data; @@ -194,7 +200,7 @@ static void rna_RigidBodyOb_shape_set(PointerRNA *ptr, int value) rbo->flag |= RBO_FLAG_NEEDS_VALIDATE; } -static void rna_RigidBodyOb_disabled_set(PointerRNA *ptr, int value) +static void rna_RigidBodyOb_disabled_set(PointerRNA *ptr, bool value) { RigidBodyOb *rbo = (RigidBodyOb *)ptr->data; @@ -262,7 +268,7 @@ static void rna_RigidBodyOb_collision_margin_set(PointerRNA *ptr, float value) #endif } -static void rna_RigidBodyOb_collision_groups_set(PointerRNA *ptr, const int *values) +static void rna_RigidBodyOb_collision_groups_set(PointerRNA *ptr, const bool *values) { RigidBodyOb *rbo = (RigidBodyOb *)ptr->data; int i; @@ -276,7 +282,7 @@ static void rna_RigidBodyOb_collision_groups_set(PointerRNA *ptr, const int *val rbo->flag |= RBO_FLAG_NEEDS_VALIDATE; } -static void rna_RigidBodyOb_kinematic_state_set(PointerRNA *ptr, int value) +static void rna_RigidBodyOb_kinematic_state_set(PointerRNA *ptr, bool value) { RigidBodyOb *rbo = (RigidBodyOb *)ptr->data; @@ -292,7 +298,7 @@ static void rna_RigidBodyOb_kinematic_state_set(PointerRNA *ptr, int value) #endif } -static void rna_RigidBodyOb_activation_state_set(PointerRNA *ptr, int value) +static void rna_RigidBodyOb_activation_state_set(PointerRNA *ptr, bool value) { RigidBodyOb *rbo = (RigidBodyOb *)ptr->data; @@ -376,7 +382,15 @@ static void rna_RigidBodyCon_type_set(PointerRNA *ptr, int value) rbc->flag |= RBC_FLAG_NEEDS_VALIDATE; } -static void rna_RigidBodyCon_enabled_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_spring_type_set(PointerRNA *ptr, int value) +{ + RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; + + rbc->spring_type = value; + rbc->flag |= RBC_FLAG_NEEDS_VALIDATE; +} + +static void rna_RigidBodyCon_enabled_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -389,7 +403,7 @@ static void rna_RigidBodyCon_enabled_set(PointerRNA *ptr, int value) #endif } -static void rna_RigidBodyCon_disable_collisions_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_disable_collisions_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -398,7 +412,7 @@ static void rna_RigidBodyCon_disable_collisions_set(PointerRNA *ptr, int value) rbc->flag |= RBC_FLAG_NEEDS_VALIDATE; } -static void rna_RigidBodyCon_use_breaking_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_use_breaking_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -433,7 +447,7 @@ static void rna_RigidBodyCon_breaking_threshold_set(PointerRNA *ptr, float value #endif } -static void rna_RigidBodyCon_override_solver_iterations_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_override_solver_iterations_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -468,6 +482,22 @@ static void rna_RigidBodyCon_num_solver_iterations_set(PointerRNA *ptr, int valu #endif } +#ifdef WITH_BULLET +static void rna_RigidBodyCon_do_set_spring_stiffness(RigidBodyCon *rbc, float value, int flag, int axis) +{ + if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & flag)) { + switch (rbc->spring_type) { + case RBC_SPRING_TYPE1: + RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, axis, value); + break; + case RBC_SPRING_TYPE2: + RB_constraint_set_stiffness_6dof_spring2(rbc->physics_constraint, axis, value); + break; + } + } +} +#endif + static void rna_RigidBodyCon_spring_stiffness_x_set(PointerRNA *ptr, float value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -475,9 +505,7 @@ static void rna_RigidBodyCon_spring_stiffness_x_set(PointerRNA *ptr, float value rbc->spring_stiffness_x = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_X)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_X, RB_LIMIT_LIN_X); #endif } @@ -488,9 +516,7 @@ static void rna_RigidBodyCon_spring_stiffness_y_set(PointerRNA *ptr, float value rbc->spring_stiffness_y = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_Y)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_Y, RB_LIMIT_LIN_Y); #endif } @@ -501,9 +527,7 @@ static void rna_RigidBodyCon_spring_stiffness_z_set(PointerRNA *ptr, float value rbc->spring_stiffness_z = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_Z)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_Z, RB_LIMIT_LIN_Z); #endif } @@ -514,9 +538,7 @@ static void rna_RigidBodyCon_spring_stiffness_ang_x_set(PointerRNA *ptr, float v rbc->spring_stiffness_ang_x = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_X)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_ANG_X, RB_LIMIT_ANG_X); #endif } @@ -527,9 +549,7 @@ static void rna_RigidBodyCon_spring_stiffness_ang_y_set(PointerRNA *ptr, float v rbc->spring_stiffness_ang_y = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_ANG_Y, RB_LIMIT_ANG_Y); #endif } @@ -540,12 +560,26 @@ static void rna_RigidBodyCon_spring_stiffness_ang_z_set(PointerRNA *ptr, float v rbc->spring_stiffness_ang_z = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z)) { - RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, value); - } + rna_RigidBodyCon_do_set_spring_stiffness(rbc, value, RBC_FLAG_USE_SPRING_ANG_Z, RB_LIMIT_ANG_Z); #endif } +#ifdef WITH_BULLET +static void rna_RigidBodyCon_do_set_spring_damping(RigidBodyCon *rbc, float value, int flag, int axis) +{ + if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & flag)) { + switch (rbc->spring_type) { + case RBC_SPRING_TYPE1: + RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, axis, value); + break; + case RBC_SPRING_TYPE2: + RB_constraint_set_damping_6dof_spring2(rbc->physics_constraint, axis, value); + break; + } + } +} +#endif + static void rna_RigidBodyCon_spring_damping_x_set(PointerRNA *ptr, float value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -553,9 +587,7 @@ static void rna_RigidBodyCon_spring_damping_x_set(PointerRNA *ptr, float value) rbc->spring_damping_x = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_X)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_X, RB_LIMIT_LIN_X); #endif } @@ -565,9 +597,7 @@ static void rna_RigidBodyCon_spring_damping_y_set(PointerRNA *ptr, float value) rbc->spring_damping_y = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_Y)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_Y, RB_LIMIT_LIN_Y); #endif } @@ -577,9 +607,7 @@ static void rna_RigidBodyCon_spring_damping_z_set(PointerRNA *ptr, float value) rbc->spring_damping_z = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_Z)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_Z, RB_LIMIT_LIN_Z); #endif } @@ -590,9 +618,7 @@ static void rna_RigidBodyCon_spring_damping_ang_x_set(PointerRNA *ptr, float val rbc->spring_damping_ang_x = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_X)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_ANG_X, RB_LIMIT_ANG_X); #endif } @@ -602,9 +628,7 @@ static void rna_RigidBodyCon_spring_damping_ang_y_set(PointerRNA *ptr, float val rbc->spring_damping_ang_y = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_ANG_Y, RB_LIMIT_ANG_Y); #endif } @@ -614,9 +638,7 @@ static void rna_RigidBodyCon_spring_damping_ang_z_set(PointerRNA *ptr, float val rbc->spring_damping_ang_z = value; #ifdef WITH_BULLET - if (rbc->physics_constraint && rbc->type == RBC_TYPE_6DOF_SPRING && (rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z)) { - RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, value); - } + rna_RigidBodyCon_do_set_spring_damping(rbc, value, RBC_FLAG_USE_SPRING_ANG_Z, RB_LIMIT_ANG_Z); #endif } @@ -633,7 +655,7 @@ static void rna_RigidBodyCon_motor_lin_max_impulse_set(PointerRNA *ptr, float va #endif } -static void rna_RigidBodyCon_use_motor_lin_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_use_motor_lin_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -646,7 +668,7 @@ static void rna_RigidBodyCon_use_motor_lin_set(PointerRNA *ptr, int value) #endif } -static void rna_RigidBodyCon_use_motor_ang_set(PointerRNA *ptr, int value) +static void rna_RigidBodyCon_use_motor_ang_set(PointerRNA *ptr, bool value) { RigidBodyCon *rbc = (RigidBodyCon *)ptr->data; @@ -1025,6 +1047,14 @@ static void rna_def_rigidbody_constraint(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_update(prop, NC_OBJECT | ND_POINTCACHE, "rna_RigidBodyOb_reset"); + prop = RNA_def_property(srna, "spring_type", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_sdna(prop, NULL, "spring_type"); + RNA_def_property_enum_items(prop, rna_enum_rigidbody_constraint_spring_type_items); + RNA_def_property_enum_funcs(prop, NULL, "rna_RigidBodyCon_spring_type_set", NULL); + RNA_def_property_ui_text(prop, "Spring Type", "Which implementation of spring to use"); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); + RNA_def_property_update(prop, NC_OBJECT | ND_POINTCACHE, "rna_RigidBodyOb_reset"); + prop = RNA_def_property(srna, "enabled", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", RBC_FLAG_ENABLED); RNA_def_property_boolean_funcs(prop, NULL, "rna_RigidBodyCon_enabled_set"); diff --git a/source/blender/makesrna/intern/rna_rna.c b/source/blender/makesrna/intern/rna_rna.c index 80aa5eff44a0..b8a9e9f92cdc 100644 --- a/source/blender/makesrna/intern/rna_rna.c +++ b/source/blender/makesrna/intern/rna_rna.c @@ -121,6 +121,7 @@ const EnumPropertyItem rna_enum_property_unit_items[] = { {PROP_UNIT_TIME, "TIME", 0, "Time", ""}, {PROP_UNIT_VELOCITY, "VELOCITY", 0, "Velocity", ""}, {PROP_UNIT_ACCELERATION, "ACCELERATION", 0, "Acceleration", ""}, + {PROP_UNIT_MASS, "MASS", 0, "Mass", ""}, {PROP_UNIT_CAMERA, "CAMERA", 0, "Camera", ""}, {0, NULL, 0, NULL, NULL} }; @@ -570,7 +571,7 @@ static int rna_Property_icon_get(PointerRNA *ptr) return prop->icon; } -static int rna_Property_readonly_get(PointerRNA *ptr) +static bool rna_Property_readonly_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; @@ -581,57 +582,57 @@ static int rna_Property_readonly_get(PointerRNA *ptr) return (prop->flag & PROP_EDITABLE) == 0; } -static int rna_Property_animatable_get(PointerRNA *ptr) +static bool rna_Property_animatable_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_ANIMATABLE) != 0; } -static int rna_Property_use_output_get(PointerRNA *ptr) +static bool rna_Property_use_output_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag_parameter & PARM_OUTPUT) != 0; } -static int rna_Property_is_required_get(PointerRNA *ptr) +static bool rna_Property_is_required_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag_parameter & PARM_REQUIRED) != 0; } -static int rna_Property_is_argument_optional_get(PointerRNA *ptr) +static bool rna_Property_is_argument_optional_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag_parameter & PARM_PYFUNC_OPTIONAL) != 0; } -static int rna_Property_is_never_none_get(PointerRNA *ptr) +static bool rna_Property_is_never_none_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_NEVER_NULL) != 0; } -static int rna_Property_is_hidden_get(PointerRNA *ptr) +static bool rna_Property_is_hidden_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_HIDDEN) != 0; } -static int rna_Property_is_skip_save_get(PointerRNA *ptr) +static bool rna_Property_is_skip_save_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_SKIP_SAVE) != 0; } -static int rna_Property_is_enum_flag_get(PointerRNA *ptr) +static bool rna_Property_is_enum_flag_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_ENUM_FLAG) != 0; } -static int rna_Property_is_library_editable_flag_get(PointerRNA *ptr) +static bool rna_Property_is_library_editable_flag_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_LIB_EXCEPTION) != 0; @@ -688,26 +689,26 @@ static void rna_Property_array_dimensions_get(PointerRNA *ptr, int dimensions[RN } } -static int rna_Property_is_registered_get(PointerRNA *ptr) +static bool rna_Property_is_registered_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_REGISTER) != 0; } -static int rna_Property_is_registered_optional_get(PointerRNA *ptr) +static bool rna_Property_is_registered_optional_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag & PROP_REGISTER_OPTIONAL) != 0; } -static int rna_Property_is_runtime_get(PointerRNA *ptr) +static bool rna_Property_is_runtime_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; return (prop->flag_internal & PROP_INTERN_RUNTIME) != 0; } -static int rna_BoolProperty_default_get(PointerRNA *ptr) +static bool rna_BoolProperty_default_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; rna_idproperty_check(&prop, ptr); @@ -730,7 +731,7 @@ static int rna_NumberProperty_default_array_get_length(PointerRNA *ptr, int leng return length[0]; } -static int rna_NumberProperty_is_array_get(PointerRNA *ptr) +static bool rna_NumberProperty_is_array_get(PointerRNA *ptr) { PropertyRNA *prop = (PropertyRNA *)ptr->data; @@ -752,14 +753,14 @@ static void rna_IntProperty_default_array_get(PointerRNA *ptr, int *values) values[i] = nprop->defaultvalue; } } -static void rna_BoolProperty_default_array_get(PointerRNA *ptr, int *values) +static void rna_BoolProperty_default_array_get(PointerRNA *ptr, bool *values) { PropertyRNA *prop = (PropertyRNA *)ptr->data; BoolPropertyRNA *nprop = (BoolPropertyRNA *)prop; rna_idproperty_check(&prop, ptr); if (nprop->defaultarray) { - memcpy(values, nprop->defaultarray, prop->totarraylength * sizeof(int)); + memcpy(values, nprop->defaultarray, prop->totarraylength * sizeof(bool)); } else { int i; @@ -1035,19 +1036,19 @@ static void rna_Function_parameters_begin(CollectionPropertyIterator *iter, Poin rna_iterator_listbase_begin(iter, &((FunctionRNA *)ptr->data)->cont.properties, rna_property_builtin); } -static int rna_Function_registered_get(PointerRNA *ptr) +static bool rna_Function_registered_get(PointerRNA *ptr) { FunctionRNA *func = (FunctionRNA *)ptr->data; return 0 != (func->flag & FUNC_REGISTER); } -static int rna_Function_registered_optional_get(PointerRNA *ptr) +static bool rna_Function_registered_optional_get(PointerRNA *ptr) { FunctionRNA *func = (FunctionRNA *)ptr->data; return 0 != (func->flag & (FUNC_REGISTER_OPTIONAL & ~FUNC_REGISTER)); } -static int rna_Function_no_self_get(PointerRNA *ptr) +static bool rna_Function_no_self_get(PointerRNA *ptr) { FunctionRNA *func = (FunctionRNA *)ptr->data; return !(func->flag & FUNC_NO_SELF); diff --git a/source/blender/makesrna/intern/rna_scene.c b/source/blender/makesrna/intern/rna_scene.c index c2cb47d417f8..d9bc4d35265a 100644 --- a/source/blender/makesrna/intern/rna_scene.c +++ b/source/blender/makesrna/intern/rna_scene.c @@ -500,7 +500,7 @@ static void rna_GPencilInterpolateSettings_type_set(PointerRNA *ptr, int value) } /* Grease pencil Drawing Brushes */ -static bGPDbrush *rna_GPencil_brush_new(ToolSettings *ts, const char *name, int setactive) +static bGPDbrush *rna_GPencil_brush_new(ToolSettings *ts, const char *name, bool setactive) { bGPDbrush *brush = BKE_gpencil_brush_addnew(ts, name, setactive != 0); @@ -729,7 +729,7 @@ static void rna_Scene_set_set(PointerRNA *ptr, PointerRNA value) scene->set = set; } -static void rna_Scene_layer_set(PointerRNA *ptr, const int *values) +static void rna_Scene_layer_set(PointerRNA *ptr, const bool *values) { Scene *scene = (Scene *)ptr->data; @@ -840,7 +840,7 @@ static void rna_Scene_end_frame_set(PointerRNA *ptr, int value) } } -static void rna_Scene_use_preview_range_set(PointerRNA *ptr, int value) +static void rna_Scene_use_preview_range_set(PointerRNA *ptr, bool value) { Scene *data = (Scene *)ptr->data; @@ -1060,13 +1060,13 @@ static int rna_RenderSettings_threads_mode_get(PointerRNA *ptr) return (rd->mode & R_FIXED_THREADS); } -static int rna_RenderSettings_is_movie_format_get(PointerRNA *ptr) +static bool rna_RenderSettings_is_movie_format_get(PointerRNA *ptr) { RenderData *rd = (RenderData *)ptr->data; return BKE_imtype_is_movie(rd->im_format.imtype); } -static int rna_RenderSettings_save_buffers_get(PointerRNA *ptr) +static bool rna_RenderSettings_save_buffers_get(PointerRNA *ptr) { RenderData *rd = (RenderData *)ptr->data; Scene *scene = (Scene *)ptr->id.data; @@ -1313,7 +1313,7 @@ static void rna_SceneRender_file_ext_get(PointerRNA *ptr, char *str) } #ifdef WITH_FFMPEG -static void rna_FFmpegSettings_lossless_output_set(PointerRNA *ptr, int value) +static void rna_FFmpegSettings_lossless_output_set(PointerRNA *ptr, bool value) { Scene *scene = (Scene *) ptr->id.data; RenderData *rd = &scene->r; @@ -1611,24 +1611,24 @@ static void rna_RenderSettings_views_format_set(PointerRNA *ptr, int value) rd->views_format = value; } -static int rna_RenderSettings_multiple_engines_get(PointerRNA *UNUSED(ptr)) +static bool rna_RenderSettings_multiple_engines_get(PointerRNA *UNUSED(ptr)) { return (BLI_listbase_count(&R_engines) > 1); } -static int rna_RenderSettings_use_shading_nodes_get(PointerRNA *ptr) +static bool rna_RenderSettings_use_shading_nodes_get(PointerRNA *ptr) { Scene *scene = (Scene *)ptr->id.data; return BKE_scene_use_new_shading_nodes(scene); } -static int rna_RenderSettings_use_spherical_stereo_get(PointerRNA *ptr) +static bool rna_RenderSettings_use_spherical_stereo_get(PointerRNA *ptr) { Scene *scene = (Scene *)ptr->id.data; return BKE_scene_use_spherical_stereo(scene); } -static int rna_RenderSettings_use_game_engine_get(PointerRNA *ptr) +static bool rna_RenderSettings_use_game_engine_get(PointerRNA *ptr) { RenderData *rd = (RenderData *)ptr->data; RenderEngineType *type; @@ -1640,7 +1640,7 @@ static int rna_RenderSettings_use_game_engine_get(PointerRNA *ptr) return 0; } -static void rna_SceneRenderLayer_layer_set(PointerRNA *ptr, const int *values) +static void rna_SceneRenderLayer_layer_set(PointerRNA *ptr, const bool *values) { SceneRenderLayer *rl = (SceneRenderLayer *)ptr->data; rl->lay = ED_view3d_scene_layer_set(rl->lay, values, NULL); @@ -1680,7 +1680,7 @@ static void rna_Physics_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Pointe BKE_ptcache_object_reset(scene, base->object, PTCACHE_RESET_DEPSGRAPH); } -static void rna_Scene_editmesh_select_mode_set(PointerRNA *ptr, const int *value) +static void rna_Scene_editmesh_select_mode_set(PointerRNA *ptr, const bool *value) { Scene *scene = (Scene *)ptr->id.data; ToolSettings *ts = (ToolSettings *)ptr->data; @@ -1778,13 +1778,13 @@ static void rna_Scene_use_persistent_data_update(Main *UNUSED(bmain), Scene *UNU RE_FreePersistentData(); } -static int rna_Scene_use_audio_get(PointerRNA *ptr) +static bool rna_Scene_use_audio_get(PointerRNA *ptr) { Scene *scene = (Scene *)ptr->data; return (scene->audio.flag & AUDIO_MUTE) != 0; } -static void rna_Scene_use_audio_set(PointerRNA *ptr, int value) +static void rna_Scene_use_audio_set(PointerRNA *ptr, bool value) { Scene *scene = (Scene *)ptr->data; @@ -1821,12 +1821,12 @@ static void rna_Scene_sync_mode_set(PointerRNA *ptr, int value) } } -static int rna_GameSettings_auto_start_get(PointerRNA *UNUSED(ptr)) +static bool rna_GameSettings_auto_start_get(PointerRNA *UNUSED(ptr)) { return (G.fileflags & G_FILE_AUTOPLAY) != 0; } -static void rna_GameSettings_auto_start_set(PointerRNA *UNUSED(ptr), int value) +static void rna_GameSettings_auto_start_set(PointerRNA *UNUSED(ptr), bool value) { if (value) G.fileflags |= G_FILE_AUTOPLAY; @@ -2211,7 +2211,7 @@ static void rna_Stereo3dFormat_update(Main *bmain, Scene *UNUSED(scene), Pointer } } -static int rna_gpu_is_hq_supported_get(PointerRNA *UNUSED(ptr)) +static bool rna_gpu_is_hq_supported_get(PointerRNA *UNUSED(ptr)) { return GPU_instanced_drawing_support() && GPU_geometry_shader_support(); } @@ -6193,12 +6193,14 @@ static void rna_def_scene_render_data(BlenderRNA *brna) prop = RNA_def_property(srna, "use_placeholder", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "mode", R_TOUCH); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_ui_text(prop, "Placeholders", "Create empty placeholder files while rendering frames (similar to Unix 'touch')"); RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL); prop = RNA_def_property(srna, "use_overwrite", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "mode", R_NO_OVERWRITE); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_ui_text(prop, "Overwrite", "Overwrite existing files while rendering"); RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL); @@ -6220,6 +6222,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna) prop = RNA_def_property(srna, "use_file_extension", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "scemode", R_EXTENSION); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_ui_text(prop, "File Extensions", "Add the file format extensions to the rendered file name (eg: filename + .jpg)"); RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL); @@ -6251,6 +6254,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna) prop = RNA_def_property(srna, "use_save_buffers", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "scemode", R_EXR_TILE_FILE); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_boolean_funcs(prop, "rna_RenderSettings_save_buffers_get", NULL); RNA_def_property_ui_text(prop, "Save Buffers", "Save tiles for all RenderLayers and SceneNodes to files in the temp directory " @@ -6266,12 +6270,14 @@ static void rna_def_scene_render_data(BlenderRNA *brna) prop = RNA_def_property(srna, "display_mode", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "displaymode"); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_enum_items(prop, display_mode_items); RNA_def_property_ui_text(prop, "Display", "Select where rendered images will be displayed"); RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL); prop = RNA_def_property(srna, "use_lock_interface", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_lock_interface", 1); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_ui_icon(prop, ICON_UNLOCKED, true); RNA_def_property_ui_text(prop, "Lock Interface", "Lock interface during rendering in favor of giving more memory to the renderer"); RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL); @@ -6286,6 +6292,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna) /* Render result EXR cache. */ prop = RNA_def_property(srna, "use_render_cache", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "scemode", R_EXR_CACHE_FILE); + RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); RNA_def_property_ui_text(prop, "Cache Result", "Save render cache to EXR files (useful for heavy compositing, " "Note: affects indirectly rendered scenes)"); diff --git a/source/blender/makesrna/intern/rna_scene_api.c b/source/blender/makesrna/intern/rna_scene_api.c index fe2f4fe0dca8..eff9576248cc 100644 --- a/source/blender/makesrna/intern/rna_scene_api.c +++ b/source/blender/makesrna/intern/rna_scene_api.c @@ -135,7 +135,7 @@ static void rna_Scene_update_tagged(Scene *scene, Main *bmain) } static void rna_SceneRender_get_frame_path( - RenderData *rd, Main *bmain, int frame, int preview, const char *view, char *name) + RenderData *rd, Main *bmain, int frame, bool preview, const char *view, char *name) { const char *suffix = BKE_scene_multiview_view_suffix_get(rd, view); @@ -156,7 +156,7 @@ static void rna_SceneRender_get_frame_path( static void rna_Scene_ray_cast( Scene *scene, Main *bmain, float origin[3], float direction[3], float ray_dist, - int *r_success, float r_location[3], float r_normal[3], int *r_index, + bool *r_success, float r_location[3], float r_normal[3], int *r_index, Object **r_ob, float r_obmat[16]) { normalize_v3(direction); @@ -203,22 +203,22 @@ static void rna_Scene_alembic_export( int geom_samples, float shutter_open, float shutter_close, - int selected_only, - int uvs, - int normals, - int vcolors, - int apply_subdiv, - int flatten_hierarchy, - int visible_layers_only, - int renderable_only, - int face_sets, - int use_subdiv_schema, - int export_hair, - int export_particles, + bool selected_only, + bool uvs, + bool normals, + bool vcolors, + bool apply_subdiv, + bool flatten_hierarchy, + bool visible_layers_only, + bool renderable_only, + bool face_sets, + bool use_subdiv_schema, + bool export_hair, + bool export_particles, int compression_type, - int packuv, + bool packuv, float scale, - int triangulate, + bool triangulate, int quad_method, int ngon_method) { diff --git a/source/blender/makesrna/intern/rna_screen.c b/source/blender/makesrna/intern/rna_screen.c index 2e86ceb2617c..7ca26ab1c9fe 100644 --- a/source/blender/makesrna/intern/rna_screen.c +++ b/source/blender/makesrna/intern/rna_screen.c @@ -108,14 +108,14 @@ static void rna_Screen_redraw_update(Main *UNUSED(bmain), Scene *UNUSED(scene), } -static int rna_Screen_is_animation_playing_get(PointerRNA *UNUSED(ptr)) +static bool rna_Screen_is_animation_playing_get(PointerRNA *UNUSED(ptr)) { /* can be NULL on file load, T42619 */ - wmWindowManager *wm = G.main->wm.first; + wmWindowManager *wm = G_MAIN->wm.first; return wm ? (ED_screen_animation_playing(wm) != NULL) : 0; } -static int rna_Screen_fullscreen_get(PointerRNA *ptr) +static bool rna_Screen_fullscreen_get(PointerRNA *ptr) { bScreen *sc = (bScreen *)ptr->data; return (sc->state == SCREENMAXIMIZED); @@ -182,7 +182,7 @@ static void rna_View2D_region_to_view(struct View2D *v2d, int x, int y, float re UI_view2d_region_to_view(v2d, x, y, &result[0], &result[1]); } -static void rna_View2D_view_to_region(struct View2D *v2d, float x, float y, int clip, int result[2]) +static void rna_View2D_view_to_region(struct View2D *v2d, float x, float y, bool clip, int result[2]) { if (clip) UI_view2d_view_to_region_clip(v2d, x, y, &result[0], &result[1]); @@ -458,4 +458,3 @@ void RNA_def_screen(BlenderRNA *brna) } #endif - diff --git a/source/blender/makesrna/intern/rna_sculpt_paint.c b/source/blender/makesrna/intern/rna_sculpt_paint.c index 11610c35b34e..92f05bf366f1 100644 --- a/source/blender/makesrna/intern/rna_sculpt_paint.c +++ b/source/blender/makesrna/intern/rna_sculpt_paint.c @@ -51,7 +51,7 @@ #include "bmesh.h" -static const EnumPropertyItem particle_edit_hair_brush_items[] = { +const EnumPropertyItem rna_enum_particle_edit_hair_brush_items[] = { {PE_BRUSH_NONE, "NONE", 0, "None", "Don't use any brush"}, {PE_BRUSH_COMB, "COMB", 0, "Comb", "Comb hairs"}, {PE_BRUSH_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth hairs"}, @@ -120,7 +120,7 @@ static void rna_GPencil_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Pointe WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL); } -static const EnumPropertyItem particle_edit_disconnected_hair_brush_items[] = { +const EnumPropertyItem rna_enum_particle_edit_disconnected_hair_brush_items[] = { {PE_BRUSH_NONE, "NONE", 0, "None", "Don't use any brush"}, {PE_BRUSH_COMB, "COMB", 0, "Comb", "Comb hairs"}, {PE_BRUSH_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth hairs"}, @@ -186,8 +186,9 @@ static void rna_ParticleEdit_tool_set(PointerRNA *ptr, int value) pset->brushtype = value; } -static const EnumPropertyItem *rna_ParticleEdit_tool_itemf(bContext *C, PointerRNA *UNUSED(ptr), - PropertyRNA *UNUSED(prop), bool *UNUSED(r_free)) +static const EnumPropertyItem *rna_ParticleEdit_tool_itemf( + bContext *C, PointerRNA *UNUSED(ptr), + PropertyRNA *UNUSED(prop), bool *UNUSED(r_free)) { Scene *scene = CTX_data_scene(C); Object *ob = (scene->basact) ? scene->basact->object : NULL; @@ -204,28 +205,34 @@ static const EnumPropertyItem *rna_ParticleEdit_tool_itemf(bContext *C, PointerR if (psys) { if (psys->flag & PSYS_GLOBAL_HAIR) { - return particle_edit_disconnected_hair_brush_items; + return rna_enum_particle_edit_disconnected_hair_brush_items; } else { - return particle_edit_hair_brush_items; + return rna_enum_particle_edit_hair_brush_items; } } return particle_edit_cache_brush_items; } -static int rna_ParticleEdit_editable_get(PointerRNA *ptr) +static bool rna_ParticleEdit_editable_get(PointerRNA *ptr) { ParticleEditSettings *pset = (ParticleEditSettings *)ptr->data; - return (pset->object && pset->scene && PE_get_current(G.main, pset->scene, pset->object)); + if (pset->object != NULL && pset->scene != NULL) { + BLI_assert(BKE_id_is_in_gobal_main(&pset->object->id)); + BLI_assert(BKE_id_is_in_gobal_main(&pset->scene->id)); + } + return (pset->object && pset->scene && PE_get_current(G_MAIN, pset->scene, pset->object)); } -static int rna_ParticleEdit_hair_get(PointerRNA *ptr) +static bool rna_ParticleEdit_hair_get(PointerRNA *ptr) { ParticleEditSettings *pset = (ParticleEditSettings *)ptr->data; if (pset->scene) { - PTCacheEdit *edit = PE_get_current(G.main, pset->scene, pset->object); + BLI_assert(BKE_id_is_in_gobal_main(&pset->scene->id)); + BLI_assert(BKE_id_is_in_gobal_main(&pset->object->id)); + PTCacheEdit *edit = PE_get_current(G_MAIN, pset->scene, pset->object); return (edit && edit->psys); } @@ -238,7 +245,7 @@ static char *rna_ParticleEdit_path(PointerRNA *UNUSED(ptr)) return BLI_strdup("tool_settings.particle_edit"); } -static int rna_Brush_mode_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_Brush_mode_poll(PointerRNA *ptr, PointerRNA value) { Scene *scene = (Scene *)ptr->id.data; ToolSettings *ts = scene->toolsettings; @@ -404,7 +411,7 @@ static void rna_ImaPaint_canvas_update(Main *bmain, Scene *scene, PointerRNA *UN } } -static int rna_ImaPaint_detect_data(ImagePaintSettings *imapaint) +static bool rna_ImaPaint_detect_data(ImagePaintSettings *imapaint) { return imapaint->missing_data == 0; } @@ -882,7 +889,7 @@ static void rna_def_particle_edit(BlenderRNA *brna) prop = RNA_def_property(srna, "tool", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "brushtype"); - RNA_def_property_enum_items(prop, particle_edit_hair_brush_items); + RNA_def_property_enum_items(prop, rna_enum_particle_edit_hair_brush_items); RNA_def_property_enum_funcs(prop, NULL, "rna_ParticleEdit_tool_set", "rna_ParticleEdit_tool_itemf"); RNA_def_property_ui_text(prop, "Tool", ""); diff --git a/source/blender/makesrna/intern/rna_sensor.c b/source/blender/makesrna/intern/rna_sensor.c index a77709dbf41c..0cfdfa54ef22 100644 --- a/source/blender/makesrna/intern/rna_sensor.c +++ b/source/blender/makesrna/intern/rna_sensor.c @@ -215,7 +215,7 @@ static void rna_Sensor_keyboard_modifier2_set(struct PointerRNA *ptr, int value) ks->qual2 = 0; } -static void rna_Sensor_tap_set(struct PointerRNA *ptr, int value) +static void rna_Sensor_tap_set(struct PointerRNA *ptr, bool value) { bSensor *sens = (bSensor *)ptr->data; @@ -224,7 +224,7 @@ static void rna_Sensor_tap_set(struct PointerRNA *ptr, int value) sens->level = 0; } -static void rna_Sensor_level_set(struct PointerRNA *ptr, int value) +static void rna_Sensor_level_set(struct PointerRNA *ptr, bool value) { bSensor *sens = (bSensor *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_sensor_api.c b/source/blender/makesrna/intern/rna_sensor_api.c index b0c4109b1df7..9db5c3f9f921 100644 --- a/source/blender/makesrna/intern/rna_sensor_api.c +++ b/source/blender/makesrna/intern/rna_sensor_api.c @@ -76,4 +76,3 @@ void RNA_api_sensor(StructRNA *srna) } #endif - diff --git a/source/blender/makesrna/intern/rna_sequencer.c b/source/blender/makesrna/intern/rna_sequencer.c index fb6953904b3c..e78bce9170de 100644 --- a/source/blender/makesrna/intern/rna_sequencer.c +++ b/source/blender/makesrna/intern/rna_sequencer.c @@ -327,13 +327,13 @@ static void rna_Sequence_frame_offset_range(PointerRNA *ptr, int *min, int *max, *max = INT_MAX; } -static void rna_Sequence_use_proxy_set(PointerRNA *ptr, int value) +static void rna_Sequence_use_proxy_set(PointerRNA *ptr, bool value) { Sequence *seq = (Sequence *)ptr->data; BKE_sequencer_proxy_set(seq, value != 0); } -static void rna_Sequence_use_translation_set(PointerRNA *ptr, int value) +static void rna_Sequence_use_translation_set(PointerRNA *ptr, bool value) { Sequence *seq = (Sequence *)ptr->data; if (value) { @@ -347,7 +347,7 @@ static void rna_Sequence_use_translation_set(PointerRNA *ptr, int value) } } -static void rna_Sequence_use_crop_set(PointerRNA *ptr, int value) +static void rna_Sequence_use_crop_set(PointerRNA *ptr, bool value) { Sequence *seq = (Sequence *)ptr->data; if (value) { @@ -891,7 +891,7 @@ static void rna_SequenceColorBalance_update(Main *UNUSED(bmain), Scene *UNUSED(s BKE_sequence_invalidate_cache_for_modifier(scene, seq); } -static void rna_SequenceEditor_overlay_lock_set(PointerRNA *ptr, int value) +static void rna_SequenceEditor_overlay_lock_set(PointerRNA *ptr, bool value) { Scene *scene = ptr->id.data; Editing *ed = BKE_sequencer_editing_get(scene, false); @@ -1046,7 +1046,7 @@ static void rna_SequenceModifier_update(Main *UNUSED(bmain), Scene *UNUSED(scene BKE_sequence_invalidate_cache_for_modifier(scene, seq); } -static int rna_SequenceModifier_otherSequence_poll(PointerRNA *ptr, PointerRNA value) +static bool rna_SequenceModifier_otherSequence_poll(PointerRNA *ptr, PointerRNA value) { Scene *scene = (Scene *) ptr->id.data; Editing *ed = BKE_sequencer_editing_get(scene, false); diff --git a/source/blender/makesrna/intern/rna_sequencer_api.c b/source/blender/makesrna/intern/rna_sequencer_api.c index da8b19a1ff6a..509b6da2048c 100644 --- a/source/blender/makesrna/intern/rna_sequencer_api.c +++ b/source/blender/makesrna/intern/rna_sequencer_api.c @@ -61,7 +61,7 @@ #include "WM_api.h" -static void rna_Sequence_update_rnafunc(ID *id, Sequence *self, int do_data) +static void rna_Sequence_update_rnafunc(ID *id, Sequence *self, bool do_data) { if (do_data) { BKE_sequencer_update_changed_seq_and_deps((Scene *)id, self, true, true); diff --git a/source/blender/makesrna/intern/rna_smoke.c b/source/blender/makesrna/intern/rna_smoke.c index 52550a9b8ccf..65e56ddb487e 100644 --- a/source/blender/makesrna/intern/rna_smoke.c +++ b/source/blender/makesrna/intern/rna_smoke.c @@ -429,7 +429,7 @@ static void rna_SmokeFlow_uvlayer_set(PointerRNA *ptr, const char *value) rna_object_uvlayer_name_set(ptr, value, flow->uvlayer_name, sizeof(flow->uvlayer_name)); } -static void rna_Smoke_use_color_ramp_set(PointerRNA *ptr, int value) +static void rna_Smoke_use_color_ramp_set(PointerRNA *ptr, bool value) { SmokeDomainSettings *sds = (SmokeDomainSettings *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_sound.c b/source/blender/makesrna/intern/rna_sound.c index 6aacede58162..3339c5ec4053 100644 --- a/source/blender/makesrna/intern/rna_sound.c +++ b/source/blender/makesrna/intern/rna_sound.c @@ -45,13 +45,13 @@ static void rna_Sound_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr) BKE_sound_load(bmain, (bSound *)ptr->data); } -static int rna_Sound_caching_get(PointerRNA *ptr) +static bool rna_Sound_caching_get(PointerRNA *ptr) { bSound *sound = (bSound *)(ptr->data); return (sound->flags & SOUND_FLAGS_CACHING) != 0; } -static void rna_Sound_caching_set(PointerRNA *ptr, const int value) +static void rna_Sound_caching_set(PointerRNA *ptr, const bool value) { bSound *sound = (bSound *)(ptr->data); if (value) diff --git a/source/blender/makesrna/intern/rna_space.c b/source/blender/makesrna/intern/rna_space.c index 3b6298801c8e..e569c8958bfb 100644 --- a/source/blender/makesrna/intern/rna_space.c +++ b/source/blender/makesrna/intern/rna_space.c @@ -258,6 +258,8 @@ const EnumPropertyItem rna_enum_file_sort_items[] = { #include "DNA_userdef_types.h" #include "BLI_math.h" +#include "BLI_path_util.h" +#include "BLI_string.h" #include "BKE_animsys.h" #include "BKE_brush.h" @@ -365,7 +367,7 @@ static void rna_area_region_from_regiondata(PointerRNA *ptr, ScrArea **r_sa, ARe area_region_from_regiondata(sc, regiondata, r_sa, r_ar); } -static int rna_Space_view2d_sync_get(PointerRNA *ptr) +static bool rna_Space_view2d_sync_get(PointerRNA *ptr) { ScrArea *sa; ARegion *ar; @@ -380,7 +382,7 @@ static int rna_Space_view2d_sync_get(PointerRNA *ptr) return false; } -static void rna_Space_view2d_sync_set(PointerRNA *ptr, int value) +static void rna_Space_view2d_sync_set(PointerRNA *ptr, bool value) { ScrArea *sa; ARegion *ar; @@ -475,7 +477,7 @@ static void rna_SpaceView3D_camera_update(Main *bmain, Scene *scene, PointerRNA } } -static void rna_SpaceView3D_lock_camera_and_layers_set(PointerRNA *ptr, int value) +static void rna_SpaceView3D_lock_camera_and_layers_set(PointerRNA *ptr, bool value) { View3D *v3d = (View3D *)(ptr->data); bScreen *sc = (bScreen *)ptr->id.data; @@ -535,7 +537,7 @@ static float rna_View3D_GridScaleUnit_get(PointerRNA *ptr) return ED_view3d_grid_scale(scene, v3d, NULL); } -static void rna_SpaceView3D_layer_set(PointerRNA *ptr, const int *values) +static void rna_SpaceView3D_layer_set(PointerRNA *ptr, const bool *values) { View3D *v3d = (View3D *)(ptr->data); @@ -792,7 +794,7 @@ static void rna_SpaceImageEditor_show_stereo_set(PointerRNA *ptr, int value) sima->iuser.flag &= ~IMA_SHOW_STEREO; } -static int rna_SpaceImageEditor_show_stereo_get(PointerRNA *ptr) +static bool rna_SpaceImageEditor_show_stereo_get(PointerRNA *ptr) { SpaceImage *sima = (SpaceImage *)(ptr->data); return (sima->iuser.flag & IMA_SHOW_STEREO) != 0; @@ -813,26 +815,26 @@ static void rna_SpaceImageEditor_show_stereo_update(Main *UNUSED(bmain), Scene * } } -static int rna_SpaceImageEditor_show_render_get(PointerRNA *ptr) +static bool rna_SpaceImageEditor_show_render_get(PointerRNA *ptr) { SpaceImage *sima = (SpaceImage *)(ptr->data); return ED_space_image_show_render(sima); } -static int rna_SpaceImageEditor_show_paint_get(PointerRNA *ptr) +static bool rna_SpaceImageEditor_show_paint_get(PointerRNA *ptr) { SpaceImage *sima = (SpaceImage *)(ptr->data); return ED_space_image_show_paint(sima); } -static int rna_SpaceImageEditor_show_uvedit_get(PointerRNA *ptr) +static bool rna_SpaceImageEditor_show_uvedit_get(PointerRNA *ptr) { SpaceImage *sima = (SpaceImage *)(ptr->data); bScreen *sc = (bScreen *)ptr->id.data; return ED_space_image_show_uvedit(sima, sc->scene->obedit); } -static int rna_SpaceImageEditor_show_maskedit_get(PointerRNA *ptr) +static bool rna_SpaceImageEditor_show_maskedit_get(PointerRNA *ptr) { SpaceImage *sima = (SpaceImage *)(ptr->data); bScreen *sc = (bScreen *)ptr->id.data; @@ -844,7 +846,8 @@ static void rna_SpaceImageEditor_image_set(PointerRNA *ptr, PointerRNA value) SpaceImage *sima = (SpaceImage *)(ptr->data); bScreen *sc = (bScreen *)ptr->id.data; - ED_space_image_set(G.main, sima, sc->scene, sc->scene->obedit, (Image *)value.data); + BLI_assert(BKE_id_is_in_gobal_main(value.data)); + ED_space_image_set(G_MAIN, sima, sc->scene, sc->scene->obedit, (Image *)value.data); } static void rna_SpaceImageEditor_mask_set(PointerRNA *ptr, PointerRNA value) @@ -998,7 +1001,7 @@ static const EnumPropertyItem *rna_SpaceImageEditor_pivot_itemf(bContext *UNUSED /* Space Text Editor */ -static void rna_SpaceTextEditor_word_wrap_set(PointerRNA *ptr, int value) +static void rna_SpaceTextEditor_word_wrap_set(PointerRNA *ptr, bool value) { SpaceText *st = (SpaceText *)(ptr->data); @@ -1405,7 +1408,7 @@ static void rna_SpaceGraphEditor_display_mode_update(Main *UNUSED(bmain), Scene ED_area_tag_refresh(sa); } -static int rna_SpaceGraphEditor_has_ghost_curves_get(PointerRNA *ptr) +static bool rna_SpaceGraphEditor_has_ghost_curves_get(PointerRNA *ptr) { SpaceIpo *sipo = (SpaceIpo *)(ptr->data); return (BLI_listbase_is_empty(&sipo->ghostCurves) == false); @@ -1484,7 +1487,7 @@ static void rna_SpaceNodeEditor_node_tree_set(PointerRNA *ptr, const PointerRNA ED_node_tree_start(snode, (bNodeTree *)value.data, NULL, NULL); } -static int rna_SpaceNodeEditor_node_tree_poll(PointerRNA *ptr, const PointerRNA value) +static bool rna_SpaceNodeEditor_node_tree_poll(PointerRNA *ptr, const PointerRNA value) { SpaceNode *snode = (SpaceNode *)ptr->data; bNodeTree *ntree = (bNodeTree *)value.data; @@ -1508,7 +1511,7 @@ static void rna_SpaceNodeEditor_tree_type_set(PointerRNA *ptr, int value) SpaceNode *snode = (SpaceNode *)ptr->data; ED_node_set_tree_type(snode, rna_node_tree_type_from_enum(value)); } -static int rna_SpaceNodeEditor_tree_type_poll(void *Cv, bNodeTreeType *type) +static bool rna_SpaceNodeEditor_tree_type_poll(void *Cv, bNodeTreeType *type) { bContext *C = (bContext *)Cv; if (type->poll) @@ -1611,7 +1614,7 @@ static void rna_SpaceClipEditor_view_type_update(Main *UNUSED(bmain), Scene *UNU /* File browser. */ -static int rna_FileSelectParams_use_lib_get(PointerRNA *ptr) +static bool rna_FileSelectParams_use_lib_get(PointerRNA *ptr) { FileSelectParams *params = ptr->data; @@ -1642,6 +1645,16 @@ static const EnumPropertyItem *rna_FileSelectParams_recursion_level_itemf( return fileselectparams_recursion_level_items; } +static void rna_FileSelectPrams_filter_glob_set(PointerRNA *ptr, const char *value) +{ + FileSelectParams *params = ptr->data; + + BLI_strncpy(params->filter_glob, value, sizeof(params->filter_glob)); + + /* Remove stupi things like last group being a wildcard-only one... */ + BLI_path_extension_glob_validate(params->filter_glob); +} + static void rna_FileBrowser_FSMenuEntry_path_get(PointerRNA *ptr, char *value) { char *path = ED_fsmenu_entry_get_path(ptr->data); @@ -2616,12 +2629,12 @@ static void rna_def_space_view3d(BlenderRNA *brna) RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL); prop = RNA_def_property(srna, "show_world", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag3", V3D_SHOW_WORLD); + RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_SHOW_WORLD); RNA_def_property_ui_text(prop, "World Background", "Display world colors in the background"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL); prop = RNA_def_property(srna, "show_mist", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag3", V3D_SHOW_MIST); + RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_SHOW_MIST); RNA_def_property_ui_text(prop, "World Mist", "Display world mist"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_SpaceView3D_material_update"); @@ -4051,7 +4064,10 @@ static void rna_def_fileselect_params(BlenderRNA *brna) prop = RNA_def_property(srna, "filter_glob", PROP_STRING, PROP_NONE); RNA_def_property_string_sdna(prop, NULL, "filter_glob"); - RNA_def_property_ui_text(prop, "Extension Filter", ""); + RNA_def_property_ui_text(prop, "Extension Filter", + "UNIX shell-like filename patterns matching, supports wildcards ('*') " + "and list of patterns separated by ';'"); + RNA_def_property_string_funcs(prop, NULL, NULL, "rna_FileSelectPrams_filter_glob_set"); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_FILE_LIST, NULL); prop = RNA_def_property(srna, "filter_search", PROP_STRING, PROP_NONE); diff --git a/source/blender/makesrna/intern/rna_speaker.c b/source/blender/makesrna/intern/rna_speaker.c index f47b54c2d957..3a4bc3860d43 100644 --- a/source/blender/makesrna/intern/rna_speaker.c +++ b/source/blender/makesrna/intern/rna_speaker.c @@ -164,4 +164,3 @@ void RNA_def_speaker(BlenderRNA *brna) } #endif - diff --git a/source/blender/makesrna/intern/rna_text.c b/source/blender/makesrna/intern/rna_text.c index 1035a3f7f559..191c33551764 100644 --- a/source/blender/makesrna/intern/rna_text.c +++ b/source/blender/makesrna/intern/rna_text.c @@ -73,7 +73,7 @@ static void rna_Text_filename_set(PointerRNA *ptr, const char *value) text->name = NULL; } -static int rna_Text_modified_get(PointerRNA *ptr) +static bool rna_Text_modified_get(PointerRNA *ptr) { Text *text = (Text *)ptr->data; return BKE_text_file_modified_check(text) != 0; diff --git a/source/blender/makesrna/intern/rna_texture.c b/source/blender/makesrna/intern/rna_texture.c index ae5ccc3ce564..aaefa3fd2a99 100644 --- a/source/blender/makesrna/intern/rna_texture.c +++ b/source/blender/makesrna/intern/rna_texture.c @@ -397,7 +397,7 @@ static const EnumPropertyItem *rna_TextureSlot_output_node_itemf( return item; } -static void rna_Texture_use_color_ramp_set(PointerRNA *ptr, int value) +static void rna_Texture_use_color_ramp_set(PointerRNA *ptr, bool value) { Tex *tex = (Tex *)ptr->data; @@ -422,7 +422,7 @@ static void rna_Texture_use_nodes_update(bContext *C, PointerRNA *ptr) rna_Texture_nodes_update(CTX_data_main(C), CTX_data_scene(C), ptr); } -static void rna_ImageTexture_mipmap_set(PointerRNA *ptr, int value) +static void rna_ImageTexture_mipmap_set(PointerRNA *ptr, bool value) { Tex *tex = (Tex *)ptr->data; diff --git a/source/blender/makesrna/intern/rna_tracking.c b/source/blender/makesrna/intern/rna_tracking.c index f44f7336cdf5..deb40070fe93 100644 --- a/source/blender/makesrna/intern/rna_tracking.c +++ b/source/blender/makesrna/intern/rna_tracking.c @@ -208,14 +208,14 @@ static void rna_trackingTrack_name_set(PointerRNA *ptr, const char *value) } } -static int rna_trackingTrack_select_get(PointerRNA *ptr) +static bool rna_trackingTrack_select_get(PointerRNA *ptr) { MovieTrackingTrack *track = (MovieTrackingTrack *)ptr->data; return TRACK_SELECTED(track); } -static void rna_trackingTrack_select_set(PointerRNA *ptr, int value) +static void rna_trackingTrack_select_set(PointerRNA *ptr, bool value) { MovieTrackingTrack *track = (MovieTrackingTrack *)ptr->data; @@ -664,7 +664,7 @@ static void rna_trackingObject_remove(MovieTracking *tracking, ReportList *repor WM_main_add_notifier(NC_MOVIECLIP | NA_EDITED, NULL); } -static MovieTrackingMarker *rna_trackingMarkers_find_frame(MovieTrackingTrack *track, int framenr, int exact) +static MovieTrackingMarker *rna_trackingMarkers_find_frame(MovieTrackingTrack *track, int framenr, bool exact) { if (exact) return BKE_tracking_marker_get_exact(track, framenr); @@ -706,7 +706,7 @@ static void rna_trackingMarkers_delete_frame(MovieTrackingTrack *track, int fram } static MovieTrackingPlaneMarker *rna_trackingPlaneMarkers_find_frame(MovieTrackingPlaneTrack *plane_track, - int framenr, int exact) + int framenr, bool exact) { if (exact) return BKE_tracking_plane_marker_get_exact(plane_track, framenr); diff --git a/source/blender/makesrna/intern/rna_ui.c b/source/blender/makesrna/intern/rna_ui.c index 7f9a63cc6d19..782d39bcb7e9 100644 --- a/source/blender/makesrna/intern/rna_ui.c +++ b/source/blender/makesrna/intern/rna_ui.c @@ -105,7 +105,7 @@ static ARegionType *region_type_find(ReportList *reports, int space_type, int re /* Panel */ -static int panel_poll(const bContext *C, PanelType *pt) +static bool panel_poll(const bContext *C, PanelType *pt) { extern FunctionRNA rna_Panel_poll_func; @@ -123,7 +123,7 @@ static int panel_poll(const bContext *C, PanelType *pt) pt->ext.call((bContext *)C, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); @@ -643,7 +643,7 @@ static StructRNA *rna_Header_refine(PointerRNA *htr) /* Menu */ -static int menu_poll(const bContext *C, MenuType *pt) +static bool menu_poll(const bContext *C, MenuType *pt) { extern FunctionRNA rna_Menu_poll_func; @@ -651,7 +651,7 @@ static int menu_poll(const bContext *C, MenuType *pt) ParameterList list; FunctionRNA *func; void *ret; - int visible; + bool visible; RNA_pointer_create(NULL, pt->ext.srna, NULL, &ptr); /* dummy */ func = &rna_Menu_poll_func; /* RNA_struct_find_function(&ptr, "poll"); */ @@ -661,7 +661,7 @@ static int menu_poll(const bContext *C, MenuType *pt) pt->ext.call((bContext *)C, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); @@ -797,22 +797,22 @@ static void rna_Menu_bl_description_set(PointerRNA *ptr, const char *value) /* UILayout */ -static int rna_UILayout_active_get(PointerRNA *ptr) +static bool rna_UILayout_active_get(PointerRNA *ptr) { return uiLayoutGetActive(ptr->data); } -static void rna_UILayout_active_set(PointerRNA *ptr, int value) +static void rna_UILayout_active_set(PointerRNA *ptr, bool value) { uiLayoutSetActive(ptr->data, value); } -static int rna_UILayout_alert_get(PointerRNA *ptr) +static bool rna_UILayout_alert_get(PointerRNA *ptr) { return uiLayoutGetRedAlert(ptr->data); } -static void rna_UILayout_alert_set(PointerRNA *ptr, int value) +static void rna_UILayout_alert_set(PointerRNA *ptr, bool value) { uiLayoutSetRedAlert(ptr->data, value); } @@ -827,12 +827,12 @@ static int rna_UILayout_op_context_get(PointerRNA *ptr) return uiLayoutGetOperatorContext(ptr->data); } -static int rna_UILayout_enabled_get(PointerRNA *ptr) +static bool rna_UILayout_enabled_get(PointerRNA *ptr) { return uiLayoutGetEnabled(ptr->data); } -static void rna_UILayout_enabled_set(PointerRNA *ptr, int value) +static void rna_UILayout_enabled_set(PointerRNA *ptr, bool value) { uiLayoutSetEnabled(ptr->data, value); } @@ -843,12 +843,12 @@ static int rna_UILayout_red_alert_get(PointerRNA *ptr) return uiLayoutGetRedAlert(ptr->data); } -static void rna_UILayout_red_alert_set(PointerRNA *ptr, int value) +static void rna_UILayout_red_alert_set(PointerRNA *ptr, bool value) { uiLayoutSetRedAlert(ptr->data, value); } -static int rna_UILayout_keep_aspect_get(PointerRNA *ptr) +static bool rna_UILayout_keep_aspect_get(PointerRNA *ptr) { return uiLayoutGetKeepAspect(ptr->data); } @@ -1303,4 +1303,3 @@ void RNA_def_ui(BlenderRNA *brna) } #endif /* RNA_RUNTIME */ - diff --git a/source/blender/makesrna/intern/rna_ui_api.c b/source/blender/makesrna/intern/rna_ui_api.c index 04e2d6d25ee5..36714eda2f52 100644 --- a/source/blender/makesrna/intern/rna_ui_api.c +++ b/source/blender/makesrna/intern/rna_ui_api.c @@ -61,7 +61,7 @@ const EnumPropertyItem rna_enum_icon_items[] = { #ifdef RNA_RUNTIME const char *rna_translate_ui_text( - const char *text, const char *text_ctxt, StructRNA *type, PropertyRNA *prop, int translate) + const char *text, const char *text_ctxt, StructRNA *type, PropertyRNA *prop, bool translate) { /* Also return text if UI labels translation is disabled. */ if (!text || !text[0] || !translate || !BLT_translate_iface()) { @@ -97,8 +97,8 @@ const char *rna_translate_ui_text( static void rna_uiItemR( uiLayout *layout, PointerRNA *ptr, const char *propname, const char *name, const char *text_ctxt, - int translate, int icon, int expand, int slider, int toggle, int icon_only, int event, - int full_event, int emboss, int index, int icon_value) + bool translate, int icon, bool expand, bool slider, bool toggle, bool icon_only, bool event, + bool full_event, bool emboss, int index, int icon_value) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); int flag = 0; @@ -128,7 +128,7 @@ static void rna_uiItemR( static void rna_uiItemMenuEnumR( uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name, - const char *text_ctxt, int translate, int icon) + const char *text_ctxt, bool translate, int icon) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); @@ -144,7 +144,7 @@ static void rna_uiItemMenuEnumR( static void rna_uiItemEnumR_string( uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, - const char *name, const char *text_ctxt, int translate, int icon) + const char *name, const char *text_ctxt, bool translate, int icon) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); @@ -156,32 +156,34 @@ static void rna_uiItemEnumR_string( /* Get translated name (label). */ name = rna_translate_ui_text(name, text_ctxt, NULL, prop, translate); - /* XXX This will search property again :( */ - uiItemEnumR_string(layout, ptr, propname, value, name, icon); + uiItemEnumR_string_prop(layout, ptr, prop, value, name, icon); } static void rna_uiItemPointerR( uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, - const char *name, const char *text_ctxt, int translate, int icon) + const char *name, const char *text_ctxt, bool translate, int icon) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); - if (!prop) { RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname); return; } + PropertyRNA *searchprop = RNA_struct_find_property(searchptr, searchpropname); + if (!searchprop) { + RNA_warning("property not found: %s.%s", RNA_struct_identifier(searchptr->type), searchpropname); + return; + } /* Get translated name (label). */ name = rna_translate_ui_text(name, text_ctxt, NULL, prop, translate); - /* XXX This will search property again :( */ - uiItemPointerR(layout, ptr, propname, searchptr, searchpropname, name, icon); + uiItemPointerR_prop(layout, ptr, prop, searchptr, searchprop, name, icon); } static PointerRNA rna_uiItemO( uiLayout *layout, const char *opname, const char *name, const char *text_ctxt, - int translate, int icon, int emboss, int depress, int icon_value) + bool translate, int icon, bool emboss, bool depress, int icon_value) { wmOperatorType *ot; @@ -207,7 +209,7 @@ static PointerRNA rna_uiItemO( static PointerRNA rna_uiItemOMenuHold( uiLayout *layout, const char *opname, const char *name, const char *text_ctxt, - int translate, int icon, int emboss, int depress, int icon_value, + bool translate, int icon, bool emboss, bool depress, int icon_value, const char *menu) { wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */ @@ -232,7 +234,7 @@ static PointerRNA rna_uiItemOMenuHold( static void rna_uiItemMenuEnumO( uiLayout *layout, bContext *C, const char *opname, const char *propname, const char *name, - const char *text_ctxt, int translate, int icon) + const char *text_ctxt, bool translate, int icon) { wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */ @@ -248,7 +250,7 @@ static void rna_uiItemMenuEnumO( } static void rna_uiItemL( - uiLayout *layout, const char *name, const char *text_ctxt, int translate, + uiLayout *layout, const char *name, const char *text_ctxt, bool translate, int icon, int icon_value) { /* Get translated name (label). */ @@ -262,8 +264,8 @@ static void rna_uiItemL( } static void rna_uiItemM( - uiLayout *layout, bContext *C, const char *menuname, const char *name, const char *text_ctxt, - int translate, int icon, int icon_value) + uiLayout *layout, const char *menuname, const char *name, const char *text_ctxt, + bool translate, int icon, int icon_value) { /* Get translated name (label). */ name = rna_translate_ui_text(name, text_ctxt, NULL, NULL, translate); @@ -272,12 +274,12 @@ static void rna_uiItemM( icon = icon_value; } - uiItemM(layout, C, menuname, name, icon); + uiItemM(layout, menuname, name, icon); } static void rna_uiTemplateAnyID( uiLayout *layout, PointerRNA *ptr, const char *propname, const char *proptypename, - const char *name, const char *text_ctxt, int translate) + const char *name, const char *text_ctxt, bool translate) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); @@ -295,7 +297,7 @@ static void rna_uiTemplateAnyID( static void rna_uiTemplatePathBuilder( uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *root_ptr, - const char *name, const char *text_ctxt, int translate) + const char *name, const char *text_ctxt, bool translate) { PropertyRNA *prop = RNA_struct_find_property(ptr, propname); @@ -673,7 +675,6 @@ void RNA_api_ui_layout(StructRNA *srna) RNA_def_property_ui_text(parm, "Icon Value", "Override automatic icon of the item"); func = RNA_def_function(srna, "menu", "rna_uiItemM"); - RNA_def_function_flag(func, FUNC_USE_CONTEXT); parm = RNA_def_string(func, "menu", NULL, 0, "", "Identifier of the menu"); api_ui_item_common(func); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); diff --git a/source/blender/makesrna/intern/rna_userdef.c b/source/blender/makesrna/intern/rna_userdef.c index 99d4db4cb70e..8b49776f7e35 100644 --- a/source/blender/makesrna/intern/rna_userdef.c +++ b/source/blender/makesrna/intern/rna_userdef.c @@ -212,31 +212,31 @@ static void rna_userdef_load_ui_update(Main *UNUSED(bmain), Scene *UNUSED(scene) static void rna_userdef_mipmap_update(Main *bmain, Scene *scene, PointerRNA *ptr) { - GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + GPU_set_mipmap(bmain, !(U.gameflags & USER_DISABLE_MIPMAP)); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_anisotropic_update(Main *bmain, Scene *scene, PointerRNA *ptr) { - GPU_set_anisotropic(U.anisotropic_filter); + GPU_set_anisotropic(bmain, U.anisotropic_filter); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_gl_gpu_mipmaps(Main *bmain, Scene *scene, PointerRNA *ptr) { - GPU_set_gpu_mipmapping(U.use_gpu_mipmap); + GPU_set_gpu_mipmapping(bmain, U.use_gpu_mipmap); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_gl_texture_limit_update(Main *bmain, Scene *scene, PointerRNA *ptr) { - GPU_free_images(); + GPU_free_images(bmain); rna_userdef_update(bmain, scene, ptr); } static void rna_userdef_gl_use_16bit_textures(Main *bmain, Scene *scene, PointerRNA *ptr) { - GPU_free_images(); + GPU_free_images(bmain); rna_userdef_update(bmain, scene, ptr); } @@ -447,15 +447,10 @@ static void rna_userdef_temp_update(Main *UNUSED(bmain), Scene *UNUSED(scene), P static void rna_userdef_text_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr)) { BLF_cache_clear(); + UI_reinit_font(); WM_main_add_notifier(NC_WINDOW, NULL); } -static void rna_userdef_text_antialiasing_update(Main *bmain, Scene *scene, PointerRNA *ptr) -{ - BLF_antialias_set((U.text_render & USER_TEXT_DISABLE_AA) == 0); - rna_userdef_text_update(bmain, scene, ptr); -} - static PointerRNA rna_Theme_space_generic_get(PointerRNA *ptr) { return rna_pointer_inherit_refine(ptr, &RNA_ThemeSpaceGeneric, ptr->data); @@ -3374,6 +3369,12 @@ static void rna_def_userdef_view(BlenderRNA *brna) RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", USER_TOOLTIPS_PYTHON); RNA_def_property_ui_text(prop, "Python Tooltips", "Show Python references in tooltips"); + prop = RNA_def_property(srna, "show_developer_ui", PROP_BOOLEAN, PROP_NONE); + RNA_def_property_boolean_sdna(prop, NULL, "flag", USER_DEVELOPER_UI); + RNA_def_property_ui_text( + prop, "Developer Extras", + "Show options for developers (edit source in context menu, geometry indices)"); + prop = RNA_def_property(srna, "show_object_info", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DRAWVIEWINFO); RNA_def_property_ui_text(prop, "Display Object Info", "Display objects name and frame number in 3D view"); @@ -3972,6 +3973,14 @@ static void rna_def_userdef_system(BlenderRNA *brna) {0, NULL, 0, NULL, NULL} }; + static const EnumPropertyItem text_hinting_items[] = { + {0, "AUTO", 0, "Auto", ""}, + {USER_TEXT_HINTING_NONE, "NONE", 0, "None", ""}, + {USER_TEXT_HINTING_SLIGHT, "SLIGHT", 0, "Slight", ""}, + {USER_TEXT_HINTING_FULL, "FULL", 0, "Full", ""}, + {0, NULL, 0, NULL, NULL} + }; + srna = RNA_def_struct(brna, "UserPreferencesSystem", NULL); RNA_def_struct_sdna(srna, "UserDef"); RNA_def_struct_nested(brna, srna, "UserPreferences"); @@ -4201,21 +4210,16 @@ static void rna_def_userdef_system(BlenderRNA *brna) RNA_def_property_ui_text(prop, "Audio Channels", "Audio channel count"); RNA_def_property_update(prop, 0, "rna_UserDef_audio_update"); - prop = RNA_def_property(srna, "screencast_fps", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "scrcastfps"); - RNA_def_property_range(prop, 10, 100); - RNA_def_property_ui_text(prop, "FPS", "Frame rate for the screencast to be played back"); - - prop = RNA_def_property(srna, "screencast_wait_time", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "scrcastwait"); - RNA_def_property_range(prop, 10, 1000); - RNA_def_property_ui_text(prop, "Wait Timer (ms)", - "Time in milliseconds between each frame recorded for screencast"); - prop = RNA_def_property(srna, "use_text_antialiasing", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "text_render", USER_TEXT_DISABLE_AA); RNA_def_property_ui_text(prop, "Text Anti-aliasing", "Draw user interface text anti-aliased"); - RNA_def_property_update(prop, 0, "rna_userdef_text_antialiasing_update"); + RNA_def_property_update(prop, 0, "rna_userdef_text_update"); + + prop = RNA_def_property(srna, "text_hinting", PROP_ENUM, PROP_NONE); + RNA_def_property_enum_bitflag_sdna(prop, NULL, "text_render"); + RNA_def_property_enum_items(prop, text_hinting_items); + RNA_def_property_ui_text(prop, "Text Hinting", "Method for making user interface text render sharp"); + RNA_def_property_update(prop, 0, "rna_userdef_text_update"); prop = RNA_def_property(srna, "select_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "gpu_select_method"); diff --git a/source/blender/makesrna/intern/rna_wm.c b/source/blender/makesrna/intern/rna_wm.c index 7c3674c8343d..d0d01b9e43e9 100644 --- a/source/blender/makesrna/intern/rna_wm.c +++ b/source/blender/makesrna/intern/rna_wm.c @@ -380,6 +380,10 @@ const EnumPropertyItem rna_enum_event_type_items[] = { {NDOF_BUTTON_A, "NDOF_BUTTON_A", 0, "NDOF Button A", "NdofBA"}, {NDOF_BUTTON_B, "NDOF_BUTTON_B", 0, "NDOF Button B", "NdofBB"}, {NDOF_BUTTON_C, "NDOF_BUTTON_C", 0, "NDOF Button C", "NdofBC"}, + /* Action Zones. */ + {EVT_ACTIONZONE_AREA, "ACTIONZONE_AREA", 0, "ActionZone Area", "AZone Area"}, + {EVT_ACTIONZONE_REGION, "ACTIONZONE_REGION", 0, "ActionZone Region", "AZone Region"}, + {EVT_ACTIONZONE_FULLSCREEN, "ACTIONZONE_FULLSCREEN", 0, "ActionZone Fullscreen", "AZone FullScr"}, {0, NULL, 0, NULL, NULL} }; @@ -518,7 +522,7 @@ static int rna_Operator_name_length(PointerRNA *ptr) return strlen(op->type->name); } -static int rna_Operator_has_reports_get(PointerRNA *ptr) +static bool rna_Operator_has_reports_get(PointerRNA *ptr) { wmOperator *op = (wmOperator *)ptr->data; return (op->reports && op->reports->list.first); @@ -590,7 +594,7 @@ static float rna_Event_pressure_get(PointerRNA *ptr) return WM_event_tablet_data(event, NULL, NULL); } -static int rna_Event_is_tablet_get(PointerRNA *ptr) +static bool rna_Event_is_tablet_get(PointerRNA *ptr) { const wmEvent *event = ptr->data; return WM_event_is_tablet(event); @@ -640,7 +644,7 @@ static void rna_Window_screen_set(PointerRNA *ptr, PointerRNA value) win->newscreen = value.data; } -static int rna_Window_screen_assign_poll(PointerRNA *UNUSED(ptr), PointerRNA value) +static bool rna_Window_screen_assign_poll(PointerRNA *UNUSED(ptr), PointerRNA value) { bScreen *screen = (bScreen *)value.id.data; @@ -785,7 +789,7 @@ static const EnumPropertyItem *rna_KeyMapItem_propvalue_itemf(bContext *C, Point return rna_enum_keymap_propvalue_items; /* ERROR */ } -static int rna_KeyMapItem_any_get(PointerRNA *ptr) +static bool rna_KeyMapItem_any_get(PointerRNA *ptr) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; @@ -801,7 +805,7 @@ static int rna_KeyMapItem_any_get(PointerRNA *ptr) } } -static void rna_KeyMapItem_any_set(PointerRNA *ptr, int value) +static void rna_KeyMapItem_any_set(PointerRNA *ptr, bool value) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; @@ -813,25 +817,25 @@ static void rna_KeyMapItem_any_set(PointerRNA *ptr, int value) } } -static int rna_KeyMapItem_shift_get(PointerRNA *ptr) +static bool rna_KeyMapItem_shift_get(PointerRNA *ptr) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; return kmi->shift != 0; } -static int rna_KeyMapItem_ctrl_get(PointerRNA *ptr) +static bool rna_KeyMapItem_ctrl_get(PointerRNA *ptr) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; return kmi->ctrl != 0; } -static int rna_KeyMapItem_alt_get(PointerRNA *ptr) +static bool rna_KeyMapItem_alt_get(PointerRNA *ptr) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; return kmi->alt != 0; } -static int rna_KeyMapItem_oskey_get(PointerRNA *ptr) +static bool rna_KeyMapItem_oskey_get(PointerRNA *ptr) { wmKeyMapItem *kmi = (wmKeyMapItem *)ptr->data; return kmi->oskey != 0; @@ -902,7 +906,7 @@ static int rna_wmKeyMapItem_name_length(PointerRNA *ptr) return strlen(ot ? RNA_struct_ui_name(ot->srna) : kmi->idname); } -static int rna_KeyMapItem_userdefined_get(PointerRNA *ptr) +static bool rna_KeyMapItem_userdefined_get(PointerRNA *ptr) { wmKeyMapItem *kmi = ptr->data; return kmi->id < 0; @@ -943,7 +947,7 @@ static void rna_wmClipboard_set(PointerRNA *UNUSED(ptr), const char *value) #ifdef WITH_PYTHON -static int rna_operator_poll_cb(bContext *C, wmOperatorType *ot) +static bool rna_operator_poll_cb(bContext *C, wmOperatorType *ot) { extern FunctionRNA rna_Operator_poll_func; @@ -951,7 +955,7 @@ static int rna_operator_poll_cb(bContext *C, wmOperatorType *ot) ParameterList list; FunctionRNA *func; void *ret; - int visible; + bool visible; RNA_pointer_create(NULL, ot->ext.srna, NULL, &ptr); /* dummy */ func = &rna_Operator_poll_func; /* RNA_struct_find_function(&ptr, "poll"); */ @@ -961,7 +965,7 @@ static int rna_operator_poll_cb(bContext *C, wmOperatorType *ot) ot->ext.call(C, &ptr, func, &list); RNA_parameter_get_lookup(&list, "visible", &ret); - visible = *(int *)ret; + visible = *(bool *)ret; RNA_parameter_list_free(&list); @@ -1012,7 +1016,7 @@ static bool rna_operator_check_cb(bContext *C, wmOperator *op) op->type->ext.call(C, &opr, func, &list); RNA_parameter_get_lookup(&list, "result", &ret); - result = (*(int *)ret) != 0; + result = (*(bool *)ret) != 0; RNA_parameter_list_free(&list); diff --git a/source/blender/makesrna/intern/rna_wm_api.c b/source/blender/makesrna/intern/rna_wm_api.c index 8e4e1053af08..3015d56e1ee0 100644 --- a/source/blender/makesrna/intern/rna_wm_api.c +++ b/source/blender/makesrna/intern/rna_wm_api.c @@ -87,7 +87,7 @@ static void rna_Operator_report(wmOperator *op, int type, const char *msg) BKE_report(op->reports, type, msg); } -static int rna_Operator_is_repeat(wmOperator *op, bContext *C) +static bool rna_Operator_is_repeat(wmOperator *op, bContext *C) { return WM_operator_is_repeat(C, op); } @@ -99,7 +99,7 @@ static void rna_Operator_enum_search_invoke(bContext *C, wmOperator *op) } -static int rna_event_modal_handler_add(struct bContext *C, struct wmOperator *operator) +static bool rna_event_modal_handler_add(struct bContext *C, struct wmOperator *operator) { return WM_event_add_modal_handler(C, operator) != NULL; } @@ -171,7 +171,7 @@ static int rna_Operator_props_popup(bContext *C, wmOperator *op, wmEvent *event) static wmKeyMapItem *rna_KeyMap_item_new( wmKeyMap *km, ReportList *reports, const char *idname, int type, int value, - int any, int shift, int ctrl, int alt, int oskey, int keymodifier, int head) + bool any, bool shift, bool ctrl, bool alt, bool oskey, int keymodifier, bool head) { /* wmWindowManager *wm = CTX_wm_manager(C); */ wmKeyMapItem *kmi = NULL; @@ -209,8 +209,8 @@ static wmKeyMapItem *rna_KeyMap_item_new( static wmKeyMapItem *rna_KeyMap_item_new_modal( wmKeyMap *km, ReportList *reports, const char *propvalue_str, - int type, int value, int any, int shift, int ctrl, int alt, - int oskey, int keymodifier) + int type, int value, bool any, bool shift, bool ctrl, bool alt, + bool oskey, int keymodifier) { int modifier = 0; int propvalue = 0; @@ -250,10 +250,10 @@ static void rna_KeyMap_item_remove(wmKeyMap *km, ReportList *reports, PointerRNA RNA_POINTER_INVALIDATE(kmi_ptr); } -static wmKeyMap *rna_keymap_new(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid, int modal) +static wmKeyMap *rna_keymap_new(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid, bool modal) { if (modal == 0) { - return WM_keymap_find(keyconf, idname, spaceid, regionid); + return WM_keymap_ensure(keyconf, idname, spaceid, regionid); } else { return WM_modalkeymap_add(keyconf, idname, NULL); /* items will be lazy init */ @@ -305,7 +305,7 @@ static PointerRNA rna_KeyConfig_find_item_from_operator( const char *idname, int opcontext, PointerRNA *properties, - int is_hotkey, + bool is_hotkey, PointerRNA *km_ptr) { char idname_bl[OP_MAX_TYPENAME]; diff --git a/source/blender/makesrna/rna_cleanup/rna_cleaner.py b/source/blender/makesrna/rna_cleanup/rna_cleaner.py index 0b80a711c3be..a936e6499bc8 100755 --- a/source/blender/makesrna/rna_cleanup/rna_cleaner.py +++ b/source/blender/makesrna/rna_cleanup/rna_cleaner.py @@ -56,19 +56,19 @@ def check_commandline(): """ import sys # Usage - if len(sys.argv)==1 or len(sys.argv)>3: + if len(sys.argv) == 1 or len(sys.argv) > 3: usage() if sys.argv[1] == '-h': help() elif not sys.argv[1].endswith((".txt", ".py")): - print ('\nBad input file extension... exiting.') + print('\nBad input file extension... exiting.') usage() else: inputfile = sys.argv[1] if len(sys.argv) == 2: sort_priority = default_sort_choice - print ('\nSecond parameter missing: choosing to order by %s.' % font_bold(sort_priority)) - elif len(sys.argv)==3: + print('\nSecond parameter missing: choosing to order by %s.' % font_bold(sort_priority)) + elif len(sys.argv) == 3: sort_priority = sys.argv[2] if sort_priority not in sort_choices: print('\nWrong sort_priority... exiting.') @@ -93,9 +93,11 @@ def check_prefix(prop, btype): return "" -def check_if_changed(a,b): - if a != b: return 'changed' - else: return 'same' +def check_if_changed(a, b): + if a != b: + return 'changed' + else: + return 'same' def get_props_from_txt(input_filename): @@ -103,12 +105,12 @@ def get_props_from_txt(input_filename): If the file is *.txt, the script assumes it is formatted as outlined in this script docstring """ - file=open(input_filename,'r') - file_lines=file.readlines() + file = open(input_filename, 'r') + file_lines = file.readlines() file.close() - props_list=[] - props_length_max=[0,0,0,0,0,0,0,0] + props_list = [] + props_length_max = [0, 0, 0, 0, 0, 0, 0, 0] done_text = "+" done = 0 @@ -117,7 +119,7 @@ def get_props_from_txt(input_filename): for iii, line in enumerate(file_lines): # debug - #print(line) + # print(line) line_strip = line.strip() # empty line or comment if not line_strip: @@ -136,7 +138,7 @@ def get_props_from_txt(input_filename): if '*' in bclass: comment, bclass = [x.strip() for x in bclass.split('*', 1)] else: - comment= '' + comment = '' # skipping the header if we have one. # the header is assumed to be "NOTE * CLASS.FROM -> TO: TYPE DESCRIPTION" @@ -155,7 +157,7 @@ def get_props_from_txt(input_filename): # make life easy and strip quotes description = description.replace("'", "").replace('"', "").replace("\\", "").strip() except ValueError: - btype, description = [tail,'NO DESCRIPTION'] + btype, description = [tail, 'NO DESCRIPTION'] # keyword-check kwcheck = check_prefix(bto, btype) @@ -164,17 +166,17 @@ def get_props_from_txt(input_filename): changed = check_if_changed(bfrom, bto) # lists formatting - props=[comment, changed, bclass, bfrom, bto, kwcheck, btype, description] + props = [comment, changed, bclass, bfrom, bto, kwcheck, btype, description] props_list.append(props) - props_length_max=list(map(max,zip(props_length_max,list(map(len,props))))) + props_length_max = list(map(max, zip(props_length_max, list(map(len, props))))) if done_text in comment: done += 1 tot += 1 - print("Total done %.2f" % (done / tot * 100.0) ) + print("Total done %.2f" % (done / tot * 100.0)) - return (props_list,props_length_max) + return (props_list, props_length_max) def get_props_from_py(input_filename): @@ -185,25 +187,25 @@ def get_props_from_py(input_filename): # adds the list "rna_api" to this function's scope rna_api = __import__(input_filename[:-3]).rna_api - props_length_max = [0 for i in rna_api[0]] # this way if the vector will take more elements we are safe - for index,props in enumerate(rna_api): + props_length_max = [0 for i in rna_api[0]] # this way if the vector will take more elements we are safe + for index, props in enumerate(rna_api): comment, changed, bclass, bfrom, bto, kwcheck, btype, description = props kwcheck = check_prefix(bto, btype) # keyword-check changed = check_if_changed(bfrom, bto) # changed? description = repr(description) description = description.replace("'", "").replace('"', "").replace("\\", "").strip() rna_api[index] = [comment, changed, bclass, bfrom, bto, kwcheck, btype, description] - props_length = list(map(len,props)) # lengths - props_length_max = list(map(max,zip(props_length_max,props_length))) # max lengths - return (rna_api,props_length_max) + props_length = list(map(len, props)) # lengths + props_length_max = list(map(max, zip(props_length_max, props_length))) # max lengths + return (rna_api, props_length_max) def get_props(input_filename): if input_filename.endswith(".txt"): - props_list,props_length_max = get_props_from_txt(input_filename) + props_list, props_length_max = get_props_from_txt(input_filename) elif input_filename.endswith(".py"): - props_list,props_length_max = get_props_from_py(input_filename) - return (props_list,props_length_max) + props_list, props_length_max = get_props_from_py(input_filename) + return (props_list, props_length_max) def sort(props_list, sort_priority): @@ -222,7 +224,7 @@ def sort(props_list, sort_priority): else: props_list = sorted(props_list, key=lambda p: p[i]) - print ('\nSorted by %s.' % font_bold(sort_priority)) + print('\nSorted by %s.' % font_bold(sort_priority)) return props_list @@ -250,30 +252,35 @@ def write_files(basename, props_list, props_length_max): * rna_api.py: unformatted, just as final output """ - f_rna = open("rna_api.py",'w') - f_txt = open(basename + '_work.txt','w') - f_py = open(basename + '_work.py','w') + f_rna = open("rna_api.py", 'w') + f_txt = open(basename + '_work.txt', 'w') + f_py = open(basename + '_work.py', 'w') # reminder: props=[comment, changed, bclass, bfrom, bto, kwcheck, btype, description] # [comment *] ToolSettings.snap_align_rotation -> use_snap_align_rotation: boolean [Align rotation with the snapping target] rna = py = txt = '' props_list = [['NOTE', 'CHANGED', 'CLASS', 'FROM', 'TO', 'KEYWORD-CHECK', 'TYPE', 'DESCRIPTION']] + props_list for props in props_list: - #txt + # txt # quick way we can tell if it changed - if props[3] == props[4]: txt += "#" - else: txt += " " + if props[3] == props[4]: + txt += "#" + else: + txt += " " - if props[0] != '': txt += '%s * ' % props[0] # comment - txt += '%s.%s -> %s: %s "%s"\n' % tuple(props[2:5] + props[6:]) # skipping keyword-check + if props[0] != '': + txt += '%s * ' % props[0] # comment + txt += '%s.%s -> %s: %s "%s"\n' % tuple(props[2:5] + props[6:]) # skipping keyword-check # rna_api - if props[0] == 'NOTE': indent = '# ' - else: indent = ' ' - rna += indent + '("%s", "%s", "%s", "%s", "%s"),\n' % tuple(props[2:5] + props[6:]) # description is already string formatted + if props[0] == 'NOTE': + indent = '# ' + else: + indent = ' ' + rna += indent + '("%s", "%s", "%s", "%s", "%s"),\n' % tuple(props[2:5] + props[6:]) # description is already string formatted # py - blanks = [' '* (x[0]-x[1]) for x in zip(props_length_max,list(map(len,props)))] - props = [('"%s"%s' if props[-1] != x[0] else "%s%s") % (x[0],x[1]) for x in zip(props,blanks)] + blanks = [' ' * (x[0] - x[1]) for x in zip(props_length_max, list(map(len, props)))] + props = [('"%s"%s' if props[-1] != x[0] else "%s%s") % (x[0], x[1]) for x in zip(props, blanks)] py += indent + '(%s, %s, %s, %s, %s, %s, %s, "%s"),\n' % tuple(props) f_txt.write(txt) @@ -290,7 +297,7 @@ def write_files(basename, props_list, props_length_max): f_py.close() f_rna.close() - print ('\nSaved %s, %s and %s.\n' % (font_bold(f_txt.name), font_bold(f_py.name), font_bold(f_rna.name) ) ) + print('\nSaved %s, %s and %s.\n' % (font_bold(f_txt.name), font_bold(f_py.name), font_bold(f_rna.name))) def main(): @@ -298,24 +305,23 @@ def main(): global sort_choices, default_sort_choice global kw_prefixes, kw - sort_choices = ['note','changed','class','from','to','kw', 'class.to'] + sort_choices = ['note', 'changed', 'class', 'from', 'to', 'kw', 'class.to'] default_sort_choice = sort_choices[-1] - kw_prefixes = [ 'active','apply','bl','exclude','has','invert','is','lock', \ - 'pressed','show','show_only','use','use_only','layers','states', 'select'] - kw = ['active','hide','invert','select','layers','mute','states','use','lock'] + kw_prefixes = ['active', 'apply', 'bl', 'exclude', 'has', 'invert', 'is', 'lock', + 'pressed', 'show', 'show_only', 'use', 'use_only', 'layers', 'states', 'select'] + kw = ['active', 'hide', 'invert', 'select', 'layers', 'mute', 'states', 'use', 'lock'] input_filename, sort_priority = check_commandline() - props_list,props_length_max = get_props(input_filename) - props_list = sort(props_list,sort_priority) + props_list, props_length_max = get_props(input_filename) + props_list = sort(props_list, sort_priority) output_basename = file_basename(input_filename) - write_files(output_basename, props_list,props_length_max) + write_files(output_basename, props_list, props_length_max) -if __name__=='__main__': +if __name__ == '__main__': import sys if not sys.version.startswith("3"): print("Incorrect python version, use python 3!") else: main() - diff --git a/source/blender/makesrna/rna_cleanup/rna_cleaner_merge.py b/source/blender/makesrna/rna_cleanup/rna_cleaner_merge.py index a5d5cebcbb78..236313f1f5c8 100755 --- a/source/blender/makesrna/rna_cleanup/rna_cleaner_merge.py +++ b/source/blender/makesrna/rna_cleanup/rna_cleaner_merge.py @@ -6,56 +6,58 @@ Example usage: python3 rna_cleaner_merge.py out_work.py rna_booleans_work.py ''' + + def main(): - def work_line_id(line): - return line[2].split("|")[-1], line[3] # class/from + def work_line_id(line): + return line[2].split("|")[-1], line[3] # class/from + if not (sys.argv[-1].endswith(".py") and sys.argv[-2].endswith(".py")): + print("Only accepts 2 py files as arguments.") - if not (sys.argv[-1].endswith(".py") and sys.argv[-2].endswith(".py")): - print("Only accepts 2 py files as arguments.") + sys.path.insert(0, ".") - sys.path.insert(0, ".") + mod_from = __import__(sys.argv[-1][:-3]) + mod_to = __import__(sys.argv[-2][:-3]) - mod_from = __import__(sys.argv[-1][:-3]) - mod_to = __import__(sys.argv[-2][:-3]) + mod_to_dict = dict([(work_line_id(line), line) for line in mod_to.rna_api]) + mod_from_dict = dict([(work_line_id(line), line) for line in mod_from.rna_api]) - mod_to_dict = dict([(work_line_id(line), line) for line in mod_to.rna_api]) - mod_from_dict = dict([(work_line_id(line), line) for line in mod_from.rna_api]) + rna_api_new = [] - rna_api_new = [] + for key, val_orig in mod_to_dict.items(): + try: + val_new = mod_from_dict.pop(key) + except: + # print("not found", key) + val_new = val_orig - for key, val_orig in mod_to_dict.items(): - try: - val_new = mod_from_dict.pop(key) - except: - # print("not found", key) - val_new = val_orig + # always take the class from the base + val = list(val_orig) + val[0] = val_new[0] # comment + val[4] = val_new[4] # -> to + val = tuple(val) + rna_api_new.append(val) - # always take the class from the base - val = list(val_orig) - val[0] = val_new[0] # comment - val[4] = val_new[4] # -> to - val = tuple(val) - rna_api_new.append(val) + def write_work_file(file_path, rna_api): + rna_api = list(rna_api) + rna_api.sort(key=work_line_id) + file_out = open(file_path, "w") + file_out.write("rna_api = [\n") + for line in rna_api: + file_out.write(" %s,\n" % (repr(line))) + file_out.write("]\n") + file_out.close() - def write_work_file(file_path, rna_api): - rna_api = list(rna_api) - rna_api.sort(key=work_line_id) - file_out = open(file_path, "w") - file_out.write("rna_api = [\n") - for line in rna_api: - file_out.write(" %s,\n" % (repr(line))) - file_out.write("]\n") - file_out.close() + file_path = sys.argv[-2][:-3] + "_merged.py" + write_work_file(file_path, rna_api_new) - file_path = sys.argv[-2][:-3] + "_merged.py" - write_work_file(file_path, rna_api_new) + if mod_from_dict: + file_path = sys.argv[-2][:-3] + "_lost.py" + write_work_file(file_path, list(mod_from_dict.values())) + print("Warning '%s' contains lost %d items from module %s.py" % (file_path, len(mod_from_dict), mod_from.__name__)) - if mod_from_dict: - file_path = sys.argv[-2][:-3] + "_lost.py" - write_work_file(file_path, list(mod_from_dict.values())) - print("Warning '%s' contains lost %d items from module %s.py" % (file_path, len(mod_from_dict), mod_from.__name__)) if __name__ == "__main__": - main() + main() diff --git a/source/blender/modifiers/CMakeLists.txt b/source/blender/modifiers/CMakeLists.txt index a70612447d35..80a670835820 100644 --- a/source/blender/modifiers/CMakeLists.txt +++ b/source/blender/modifiers/CMakeLists.txt @@ -24,7 +24,7 @@ # # ***** END GPL LICENSE BLOCK ***** -set(INC +set(INC . intern ../blenkernel diff --git a/source/blender/modifiers/intern/MOD_armature.c b/source/blender/modifiers/intern/MOD_armature.c index 0075e87e63bd..5b5e139d33aa 100644 --- a/source/blender/modifiers/intern/MOD_armature.c +++ b/source/blender/modifiers/intern/MOD_armature.c @@ -58,7 +58,7 @@ static void initData(ModifierData *md) { ArmatureModifierData *amd = (ArmatureModifierData *) md; - + amd->deformflag = ARM_DEF_VGROUP; } @@ -131,7 +131,7 @@ static void deformVerts( ArmatureModifierData *amd = (ArmatureModifierData *) md; modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */ - + armature_deform_verts(amd->object, ob, derivedData, vertexCos, NULL, numVerts, amd->deformflag, (float(*)[3])amd->prevCos, amd->defgrp_name); diff --git a/source/blender/modifiers/intern/MOD_bevel.c b/source/blender/modifiers/intern/MOD_bevel.c index b033327da014..c70870d56712 100644 --- a/source/blender/modifiers/intern/MOD_bevel.c +++ b/source/blender/modifiers/intern/MOD_bevel.c @@ -31,7 +31,7 @@ /** \file blender/modifiers/intern/MOD_bevel.c * \ingroup modifiers */ - + #include "DNA_object_types.h" #include "BLI_utildefines.h" diff --git a/source/blender/modifiers/intern/MOD_boolean.c b/source/blender/modifiers/intern/MOD_boolean.c index 8644d9fd203c..edbfd0408b5a 100644 --- a/source/blender/modifiers/intern/MOD_boolean.c +++ b/source/blender/modifiers/intern/MOD_boolean.c @@ -346,7 +346,7 @@ static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED( CustomDataMask dataMask = CD_MASK_MTFACE | CD_MASK_MEDGE; dataMask |= CD_MASK_MDEFORMVERT; - + return dataMask; } diff --git a/source/blender/modifiers/intern/MOD_build.c b/source/blender/modifiers/intern/MOD_build.c index c3fea60fe88c..e877d5649d47 100644 --- a/source/blender/modifiers/intern/MOD_build.c +++ b/source/blender/modifiers/intern/MOD_build.c @@ -106,11 +106,11 @@ static DerivedMesh *applyModifier( frac = (BKE_scene_frame_get(md->scene) - bmd->start) / bmd->length; CLAMP(frac, 0.0f, 1.0f); - + if (bmd->flag & MOD_BUILD_FLAG_REVERSE) { frac = 1.0f - frac; } - + numFaces_dst = numPoly_src * frac; numEdges_dst = numEdge_src * frac; @@ -120,7 +120,7 @@ static DerivedMesh *applyModifier( MLoop *ml, *mloop; MEdge *medge; uintptr_t hash_num, hash_num_alt; - + if (bmd->flag & MOD_BUILD_FLAG_RANDOMIZE) { BLI_array_randomize(faceMap, sizeof(*faceMap), numPoly_src, bmd->seed); @@ -198,7 +198,7 @@ static DerivedMesh *applyModifier( /* get the set of edges that will be in the new mesh */ for (i = 0; i < numEdges_dst; i++) { j = BLI_ghash_len(edgeHash); - + BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(j), SET_INT_IN_POINTER(edgeMap[i])); BLI_ghash_insert(edgeHash2, SET_INT_IN_POINTER(edgeMap[i]), @@ -240,39 +240,39 @@ static DerivedMesh *applyModifier( DM_copy_vert_data(dm, result, oldIndex, newIndex, 1); *dest = source; } - + /* copy the edges across, remapping indices */ for (i = 0; i < BLI_ghash_len(edgeHash); i++) { MEdge source; MEdge *dest; int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i))); - + source = medge_src[oldIndex]; dest = CDDM_get_edge(result, i); - + source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1))); source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2))); - + DM_copy_edge_data(dm, result, oldIndex, i, 1); *dest = source; } mpoly_dst = CDDM_get_polys(result); /* mloop_dst = */ ml_dst = CDDM_get_loops(result); - + /* copy the faces across, remapping indices */ k = 0; for (i = 0; i < numFaces_dst; i++) { MPoly *source; MPoly *dest; - + source = mpoly_src + faceMap[i]; dest = mpoly_dst + i; DM_copy_poly_data(dm, result, faceMap[i], i, 1); - + *dest = *source; dest->loopstart = k; - + DM_copy_loop_data(dm, result, source->loopstart, dest->loopstart, dest->totloop); ml_src = mloop_src + source->loopstart; @@ -285,7 +285,7 @@ static DerivedMesh *applyModifier( BLI_ghash_free(vertHash, NULL, NULL); BLI_ghash_free(edgeHash, NULL, NULL); BLI_ghash_free(edgeHash2, NULL, NULL); - + MEM_freeN(vertMap); MEM_freeN(edgeMap); MEM_freeN(faceMap); diff --git a/source/blender/modifiers/intern/MOD_cast.c b/source/blender/modifiers/intern/MOD_cast.c index 3416190b7b01..f09f2d619a23 100644 --- a/source/blender/modifiers/intern/MOD_cast.c +++ b/source/blender/modifiers/intern/MOD_cast.c @@ -67,7 +67,7 @@ static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams)) { CastModifierData *cmd = (CastModifierData *) md; short flag; - + flag = cmd->flag & (MOD_CAST_X | MOD_CAST_Y | MOD_CAST_Z); if ((cmd->fac == 0.0f) || flag == 0) return true; @@ -137,7 +137,7 @@ static void sphere_do( flag = cmd->flag; type = cmd->type; /* projection type: sphere or cylinder */ - if (type == MOD_CAST_TYPE_CYLINDER) + if (type == MOD_CAST_TYPE_CYLINDER) flag &= ~MOD_CAST_Z; ctrl_ob = cmd->object; diff --git a/source/blender/modifiers/intern/MOD_cloth.c b/source/blender/modifiers/intern/MOD_cloth.c index 5b7ebe94c32a..ef41c5a270c8 100644 --- a/source/blender/modifiers/intern/MOD_cloth.c +++ b/source/blender/modifiers/intern/MOD_cloth.c @@ -57,18 +57,18 @@ #include "MOD_util.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { ClothModifierData *clmd = (ClothModifierData *) md; - + clmd->sim_parms = MEM_callocN(sizeof(ClothSimSettings), "cloth sim parms"); clmd->coll_parms = MEM_callocN(sizeof(ClothCollSettings), "cloth coll parms"); clmd->point_cache = BKE_ptcache_add(&clmd->ptcaches); - + /* check for alloc failing */ if (!clmd->sim_parms || !clmd->coll_parms || !clmd->point_cache) return; - + cloth_init(clmd); } @@ -78,7 +78,7 @@ static void deformVerts( { DerivedMesh *dm; ClothModifierData *clmd = (ClothModifierData *) md; - + /* check for alloc failing */ if (!clmd->sim_parms || !clmd->coll_parms) { initData(md); @@ -121,11 +121,11 @@ static void deformVerts( static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx) { ClothModifierData *clmd = (ClothModifierData *) md; - + if (clmd) { /* Actual code uses get_collisionobjects */ #ifdef WITH_LEGACY_DEPSGRAPH - dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, clmd->coll_parms->group, ctx->object->lay|ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision"); + dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, clmd->coll_parms->group, ctx->object->lay | ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision"); dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, clmd->sim_parms->effector_weights, true, 0, "Cloth Field"); #else (void)ctx; @@ -138,7 +138,7 @@ static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphConte ClothModifierData *clmd = (ClothModifierData *)md; if (clmd != NULL) { /* Actual code uses get_collisionobjects */ - DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, clmd->coll_parms->group, ctx->object->lay|ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision"); + DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, clmd->coll_parms->group, ctx->object->lay | ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision"); DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, clmd->sim_parms->effector_weights, true, 0, "Cloth Field"); } @@ -171,7 +171,7 @@ static void copyData(const ModifierData *md, ModifierData *target) if (tclmd->coll_parms) MEM_freeN(tclmd->coll_parms); - + BKE_ptcache_free_list(&tclmd->ptcaches); tclmd->point_cache = NULL; @@ -194,13 +194,13 @@ static bool dependsOnTime(ModifierData *UNUSED(md)) static void freeData(ModifierData *md) { ClothModifierData *clmd = (ClothModifierData *) md; - + if (clmd) { if (G.debug_value > 0) printf("clothModifier_freeData\n"); - + cloth_free_modifier_extern(clmd); - + if (clmd->sim_parms) { if (clmd->sim_parms->effector_weights) MEM_freeN(clmd->sim_parms->effector_weights); @@ -208,13 +208,13 @@ static void freeData(ModifierData *md) } if (clmd->coll_parms) MEM_freeN(clmd->coll_parms); - + BKE_ptcache_free_list(&clmd->ptcaches); clmd->point_cache = NULL; - + if (clmd->hairdata) MEM_freeN(clmd->hairdata); - + if (clmd->solver_result) MEM_freeN(clmd->solver_result); } diff --git a/source/blender/modifiers/intern/MOD_collision.c b/source/blender/modifiers/intern/MOD_collision.c index 067f6ddf3efe..4390a5830d8c 100644 --- a/source/blender/modifiers/intern/MOD_collision.c +++ b/source/blender/modifiers/intern/MOD_collision.c @@ -49,10 +49,10 @@ #include "MOD_modifiertypes.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { CollisionModifierData *collmd = (CollisionModifierData *) md; - + collmd->x = NULL; collmd->xnew = NULL; collmd->current_x = NULL; @@ -68,7 +68,7 @@ static void initData(ModifierData *md) static void freeData(ModifierData *md) { CollisionModifierData *collmd = (CollisionModifierData *) md; - + if (collmd) { /* Seriously? */ if (collmd->bvhtree) { BLI_bvhtree_free(collmd->bvhtree); @@ -105,30 +105,30 @@ static void deformVerts( CollisionModifierData *collmd = (CollisionModifierData *) md; DerivedMesh *dm = NULL; MVert *tempVert = NULL; - + /* if possible use/create DerivedMesh */ if (derivedData) dm = CDDM_copy(derivedData); else if (ob->type == OB_MESH) dm = CDDM_from_mesh(ob->data); - + if (!ob->pd) { printf("CollisionModifier deformVerts: Should not happen!\n"); return; } - + if (dm) { float current_time = 0; unsigned int mvert_num = 0; CDDM_apply_vert_coords(dm, vertexCos); CDDM_calc_normals(dm); - + current_time = BKE_scene_frame_get(md->scene); - + if (G.debug_value > 0) printf("current_time %f, collmd->time_xnew %f\n", current_time, collmd->time_xnew); - + mvert_num = dm->getNumVerts(dm); - + if (current_time > collmd->time_xnew) { unsigned int i; @@ -144,7 +144,7 @@ static void deformVerts( /* we save global positions */ mul_m4_v3(ob->obmat, collmd->x[i].co); } - + collmd->xnew = MEM_dupallocN(collmd->x); // frame end position collmd->current_x = MEM_dupallocN(collmd->x); // inter-frame collmd->current_xnew = MEM_dupallocN(collmd->x); // inter-frame @@ -201,9 +201,9 @@ static void deformVerts( collmd->tri, collmd->tri_num, ob->pd->pdef_sboft); } - + } - + /* happens on file load (ONLY when i decomment changes in readfile.c) */ if (!collmd->bvhtree) { collmd->bvhtree = bvhtree_build_from_mvert( @@ -226,7 +226,7 @@ static void deformVerts( else if (mvert_num != collmd->mvert_num) { freeData((ModifierData *)collmd); } - + } else if (current_time < collmd->time_xnew) { freeData((ModifierData *)collmd); @@ -237,7 +237,7 @@ static void deformVerts( } } } - + if (dm) dm->release(dm); } diff --git a/source/blender/modifiers/intern/MOD_displace.c b/source/blender/modifiers/intern/MOD_displace.c index a71f58aa4a06..ed78e026a7f9 100644 --- a/source/blender/modifiers/intern/MOD_displace.c +++ b/source/blender/modifiers/intern/MOD_displace.c @@ -150,7 +150,7 @@ static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContex dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier"); } - + if (dmd->texmapping == MOD_DISP_MAP_GLOBAL || (ELEM(dmd->direction, MOD_DISP_DIR_X, MOD_DISP_DIR_Y, MOD_DISP_DIR_Z, MOD_DISP_DIR_RGB_XYZ) && diff --git a/source/blender/modifiers/intern/MOD_dynamicpaint.c b/source/blender/modifiers/intern/MOD_dynamicpaint.c index 8fa8ddd3098d..8d3aea2d5c82 100644 --- a/source/blender/modifiers/intern/MOD_dynamicpaint.c +++ b/source/blender/modifiers/intern/MOD_dynamicpaint.c @@ -47,10 +47,10 @@ #include "MOD_modifiertypes.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { DynamicPaintModifierData *pmd = (DynamicPaintModifierData *) md; - + pmd->canvas = NULL; pmd->brush = NULL; pmd->type = MOD_DYNAMICPAINT_TYPE_CANVAS; @@ -60,7 +60,7 @@ static void copyData(const ModifierData *md, ModifierData *target) { const DynamicPaintModifierData *pmd = (const DynamicPaintModifierData *)md; DynamicPaintModifierData *tpmd = (DynamicPaintModifierData *)target; - + dynamicPaint_Modifier_copy(pmd, tpmd); } @@ -79,7 +79,7 @@ static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md) DynamicPaintSurface *surface = pmd->canvas->surfaces.first; for (; surface; surface = surface->next) { /* tface */ - if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ || + if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ || surface->init_color_type == MOD_DPAINT_INITIAL_TEXTURE) { dataMask |= CD_MASK_MLOOPUV | CD_MASK_MTEXPOLY; diff --git a/source/blender/modifiers/intern/MOD_edgesplit.c b/source/blender/modifiers/intern/MOD_edgesplit.c index a0d717f1c0f3..1de698a62189 100644 --- a/source/blender/modifiers/intern/MOD_edgesplit.c +++ b/source/blender/modifiers/intern/MOD_edgesplit.c @@ -60,7 +60,7 @@ static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd) const bool calc_face_normals = (emd->flags & MOD_EDGESPLIT_FROMANGLE) != 0; bm = DM_to_bmesh(dm, calc_face_normals); - + if (emd->flags & MOD_EDGESPLIT_FROMANGLE) { BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { /* check for 1 edge having 2 face users */ @@ -78,7 +78,7 @@ static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd) } } } - + if (emd->flags & MOD_EDGESPLIT_FROMFLAG) { BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) { /* check for 2 or more edge users */ @@ -91,7 +91,7 @@ static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd) } } } - + BM_mesh_edgesplit(bm, false, true, false); /* BM_mesh_validate(bm); */ /* for troubleshooting */ diff --git a/source/blender/modifiers/intern/MOD_explode.c b/source/blender/modifiers/intern/MOD_explode.c index dc36156e9532..a7f09aec481d 100644 --- a/source/blender/modifiers/intern/MOD_explode.c +++ b/source/blender/modifiers/intern/MOD_explode.c @@ -65,7 +65,7 @@ static void initData(ModifierData *md) static void freeData(ModifierData *md) { ExplodeModifierData *emd = (ExplodeModifierData *) md; - + MEM_SAFE_FREE(emd->facepa); } static void copyData(const ModifierData *md, ModifierData *target) @@ -192,7 +192,7 @@ static int edgecut_get(EdgeHash *edgehash, unsigned int v1, unsigned int v2) return GET_INT_FROM_POINTER(BLI_edgehash_lookup(edgehash, v1, v2)); } - + static const short add_faces[24] = { 0, 0, 0, 2, 0, 1, 2, 2, 0, 2, 1, @@ -634,7 +634,7 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm) /* count new faces due to splitting */ for (i = 0, fs = facesplit; i < totface; i++, fs++) totfsplit += add_faces[*fs]; - + splitdm = CDDM_from_template_ex( dm, totesplit, 0, totface + totfsplit, 0, 0, CD_MASK_DERIVEDMESH | CD_MASK_FACECORNERS); @@ -843,7 +843,7 @@ static DerivedMesh *explodeMesh( * with BLI_edgehashIterator_getKey */ if (facepa[i] == totpart || cfra < (pars + facepa[i])->time) mindex = totvert + totpart; - else + else mindex = totvert + facepa[i]; mf = &mface[i]; @@ -934,12 +934,12 @@ static DerivedMesh *explodeMesh( dm->getTessFace(dm, i, &source); mf = CDDM_get_tessface(explode, u); - + orig_v4 = source.v4; if (facepa[i] != totpart && cfra < pa->time) mindex = totvert + totpart; - else + else mindex = totvert + facepa[i]; source.v1 = edgecut_get(vertpahash, source.v1, mindex); @@ -1021,7 +1021,7 @@ static DerivedMesh *applyModifier( { if (psmd->flag & eParticleSystemFlag_Pars) psmd->flag &= ~eParticleSystemFlag_Pars; - + if (emd->flag & eExplodeFlag_CalcFaces) emd->flag &= ~eExplodeFlag_CalcFaces; diff --git a/source/blender/modifiers/intern/MOD_fluidsim.c b/source/blender/modifiers/intern/MOD_fluidsim.c index 3e339b4f9744..00b7f245d4ce 100644 --- a/source/blender/modifiers/intern/MOD_fluidsim.c +++ b/source/blender/modifiers/intern/MOD_fluidsim.c @@ -55,13 +55,13 @@ static void initData(ModifierData *md) { FluidsimModifierData *fluidmd = (FluidsimModifierData *) md; - + fluidsim_init(fluidmd); } static void freeData(ModifierData *md) { FluidsimModifierData *fluidmd = (FluidsimModifierData *) md; - + fluidsim_free(fluidmd); } @@ -69,7 +69,7 @@ static void copyData(const ModifierData *md, ModifierData *target) { const FluidsimModifierData *fluidmd = (const FluidsimModifierData *) md; FluidsimModifierData *tfluidmd = (FluidsimModifierData *) target; - + if (fluidmd->fss) { tfluidmd->fss = MEM_dupallocN(fluidmd->fss); if (tfluidmd->fss && (tfluidmd->fss->meshVelocities != NULL)) { @@ -92,11 +92,11 @@ static DerivedMesh *applyModifier( { FluidsimModifierData *fluidmd = (FluidsimModifierData *) md; DerivedMesh *result = NULL; - + /* check for alloc failing */ if (!fluidmd->fss) { initData(md); - + if (!fluidmd->fss) { return dm; } @@ -119,7 +119,7 @@ static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContex if (ob1 != ctx->object) { FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob1, eModifierType_Fluidsim); - + /* only put dependencies from NON-DOMAIN fluids in here */ if (fluidmdtmp && fluidmdtmp->fss && (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN)) { DagNode *curNode = dag_get_node(ctx->forest, ob1); diff --git a/source/blender/modifiers/intern/MOD_fluidsim_util.c b/source/blender/modifiers/intern/MOD_fluidsim_util.c index 479466ead658..e366116a5fb3 100644 --- a/source/blender/modifiers/intern/MOD_fluidsim_util.c +++ b/source/blender/modifiers/intern/MOD_fluidsim_util.c @@ -69,10 +69,10 @@ void fluidsim_init(FluidsimModifierData *fluidmd) FluidsimSettings *fss = MEM_callocN(sizeof(FluidsimSettings), "fluidsimsettings"); fluidmd->fss = fss; - + if (!fss) return; - + fss->fmd = fluidmd; fss->type = OB_FLUIDSIM_ENABLE; fss->threads = 0; @@ -86,12 +86,12 @@ void fluidsim_init(FluidsimModifierData *fluidmd) fss->viscosityValue = 1.0; fss->viscosityExponent = 6; - + fss->grav[0] = 0.0; fss->grav[1] = 0.0; fss->grav[2] = -9.81; - fss->animStart = 0.0; + fss->animStart = 0.0; fss->animEnd = 4.0; fss->animRate = 1.0; fss->gstar = 0.005; // used as normgstar @@ -127,18 +127,18 @@ void fluidsim_init(FluidsimModifierData *fluidmd) fss->cpsTimeStart = fss->animStart; fss->cpsTimeEnd = fss->animEnd; fss->cpsQuality = 10.0; // 1.0 / 10.0 => means 0.1 width - + /* * BAD TODO: this is done in buttons_object.c in the moment * Mesh *mesh = ob->data; * // calculate bounding box * fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize); */ - + fss->meshVelocities = NULL; - + fss->lastgoodframe = -1; - + fss->flag |= OB_FLUIDSIM_ACTIVE; } @@ -160,7 +160,7 @@ void fluidsim_free(FluidsimModifierData *fluidmd) /* Seems to never be used, but for sqke of consistency... */ BLI_assert(fluidmd->point_cache == NULL); fluidmd->point_cache = NULL; - + return; } @@ -431,7 +431,7 @@ static DerivedMesh *fluidsim_read_cache( Object *ob, DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams) { - int curFrame = framenr /* - 1 */ /*scene->r.sfra*/; /* start with 0 at start frame */ + int curFrame = framenr /* - 1 */ /*scene->r.sfra*/; /* start with 0 at start frame */ /* why start with 0 as start frame?? Animations + time are frozen for frame 0 anyway. (See physics_fluid.c for that. - DG */ /* If we start with frame 0, we need to remap all animation channels, too, because they will all be 1 frame late if using frame-1! - DG */ @@ -524,7 +524,7 @@ DerivedMesh *fluidsimModifier_do( FluidsimSettings *fss = NULL; framenr = (int)scene->r.cfra; - + /* only handle fluidsim domains */ if (fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN)) return dm; @@ -543,12 +543,12 @@ DerivedMesh *fluidsimModifier_do( framenr = fss->lastgoodframe - framenr + 1; CLAMP(framenr, 1, fss->lastgoodframe); } - + /* try to read from cache */ /* if the frame is there, fine, otherwise don't do anything */ if ((result = fluidsim_read_cache(ob, dm, fluidmd, framenr, useRenderParams))) return result; - + return dm; #else /* unused */ diff --git a/source/blender/modifiers/intern/MOD_fluidsim_util.h b/source/blender/modifiers/intern/MOD_fluidsim_util.h index 61ad270f6c81..2bb1da327184 100644 --- a/source/blender/modifiers/intern/MOD_fluidsim_util.h +++ b/source/blender/modifiers/intern/MOD_fluidsim_util.h @@ -48,4 +48,3 @@ struct DerivedMesh *fluidsimModifier_do( int useRenderParams, int isFinalCalc); #endif - diff --git a/source/blender/modifiers/intern/MOD_hook.c b/source/blender/modifiers/intern/MOD_hook.c index 05defc85024e..5bbcaee2caa8 100644 --- a/source/blender/modifiers/intern/MOD_hook.c +++ b/source/blender/modifiers/intern/MOD_hook.c @@ -52,7 +52,7 @@ #include "MOD_util.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { HookModifierData *hmd = (HookModifierData *) md; @@ -117,7 +117,7 @@ static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContex if (hmd->object) { DagNode *curNode = dag_get_node(ctx->forest, hmd->object); - + if (hmd->subtarget[0]) dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Hook Modifier"); else @@ -272,7 +272,7 @@ static void deformVerts_do( float dmat[4][4]; int i, *index_pt; struct HookData_cb hd; - + if (hmd->curfalloff == NULL) { /* should never happen, but bad lib linking could cause it */ hmd->curfalloff = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f); @@ -321,7 +321,7 @@ static void deformVerts_do( /* Regarding index range checking below. * - * This should always be true and I don't generally like + * This should always be true and I don't generally like * "paranoid" style code like this, but old files can have * indices that are out of range because old blender did * not correct them on exit editmode. - zr @@ -332,13 +332,13 @@ static void deformVerts_do( } else if (hmd->indexar) { /* vertex indices? */ const int *origindex_ar; - + /* if DerivedMesh is present and has original index data, use it */ if (dm && (origindex_ar = dm->getVertDataArray(dm, CD_ORIGINDEX))) { for (i = 0, index_pt = hmd->indexar; i < hmd->totindex; i++, index_pt++) { if (*index_pt < numVerts) { int j; - + for (j = 0; j < numVerts; j++) { if (origindex_ar[j] == *index_pt) { hook_co_apply(&hd, j); diff --git a/source/blender/modifiers/intern/MOD_lattice.c b/source/blender/modifiers/intern/MOD_lattice.c index 9f4e87026e50..760e3c0e22a9 100644 --- a/source/blender/modifiers/intern/MOD_lattice.c +++ b/source/blender/modifiers/intern/MOD_lattice.c @@ -114,7 +114,7 @@ static void deformVerts( modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */ - + lattice_deform_verts(lmd->object, ob, derivedData, vertexCos, numVerts, lmd->name, lmd->strength); } diff --git a/source/blender/modifiers/intern/MOD_mask.c b/source/blender/modifiers/intern/MOD_mask.c index 326ff707225c..25db2d5ff0bd 100644 --- a/source/blender/modifiers/intern/MOD_mask.c +++ b/source/blender/modifiers/intern/MOD_mask.c @@ -77,7 +77,7 @@ static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContex if (mmd->ob_arm) { bArmature *arm = (bArmature *)mmd->ob_arm->data; DagNode *armNode = dag_get_node(ctx->forest, mmd->ob_arm); - + /* tag relationship in depsgraph, but also on the armature */ dag_add_relation(ctx->forest, armNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier"); arm->flag |= ARM_HAS_VIZ_DEPS; @@ -129,17 +129,17 @@ static DerivedMesh *applyModifier( } /* Overview of Method: - * 1. Get the vertices that are in the vertexgroup of interest + * 1. Get the vertices that are in the vertexgroup of interest * 2. Filter out unwanted geometry (i.e. not in vertexgroup), by populating mappings with new vs old indices * 3. Make a new mesh containing only the mapping data */ - + /* get original number of verts, edges, and faces */ maxVerts = dm->getNumVerts(dm); maxEdges = dm->getNumEdges(dm); maxPolys = dm->getNumPolys(dm); - - /* check if we can just return the original mesh + + /* check if we can just return the original mesh * - must have verts and therefore verts assigned to vgroups to do anything useful */ if (!(ELEM(mmd->mode, MOD_MASK_MODE_ARM, MOD_MASK_MODE_VGROUP)) || @@ -147,7 +147,7 @@ static DerivedMesh *applyModifier( { return dm; } - + /* if mode is to use selected armature bones, aggregate the bone groups */ if (mmd->mode == MOD_MASK_MODE_ARM) { /* --- using selected bones --- */ Object *oba = mmd->ob_arm; @@ -156,17 +156,17 @@ static DerivedMesh *applyModifier( bool *bone_select_array; int bone_select_tot = 0; const int defbase_tot = BLI_listbase_count(&ob->defbase); - + /* check that there is armature object with bones to use, otherwise return original mesh */ if (ELEM(NULL, oba, oba->pose, ob->defbase.first)) return dm; - - /* determine whether each vertexgroup is associated with a selected bone or not + + /* determine whether each vertexgroup is associated with a selected bone or not * - each cell is a boolean saying whether bone corresponding to the ith group is selected * - groups that don't match a bone are treated as not existing (along with the corresponding ungrouped verts) */ bone_select_array = MEM_malloc_arrayN((size_t)defbase_tot, sizeof(char), "mask array"); - + for (i = 0, def = ob->defbase.first; def; def = def->next, i++) { pchan = BKE_pose_channel_find_name(oba->pose, def->name); if (pchan && pchan->bone && (pchan->bone->flag & BONE_SELECTED)) { @@ -182,8 +182,8 @@ static DerivedMesh *applyModifier( * key = oldindex, value = newindex */ vertHash = BLI_ghash_int_new_ex("mask vert gh", (unsigned int)maxVerts); - - /* add vertices which exist in vertexgroups into vertHash for filtering + + /* add vertices which exist in vertexgroups into vertHash for filtering * - dv = for each vertex, what vertexgroups does it belong to * - dw = weight that vertex was assigned to a vertexgroup it belongs to */ @@ -191,7 +191,7 @@ static DerivedMesh *applyModifier( MDeformWeight *dw = dv->dw; bool found = false; int j; - + /* check the groups that vertex is assigned to, and see if it was any use */ for (j = 0; j < dv->totweight; j++, dw++) { if (dw->def_nr < defbase_tot) { @@ -203,16 +203,16 @@ static DerivedMesh *applyModifier( } } } - + if (found_test != found) { continue; } - + /* add to ghash for verts (numVerts acts as counter for mapping) */ BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numVerts)); numVerts++; } - + /* free temp hashes */ MEM_freeN(bone_select_array); } @@ -222,10 +222,10 @@ static DerivedMesh *applyModifier( /* if no vgroup (i.e. dverts) found, return the initial mesh */ if (defgrp_index == -1) return dm; - + /* hashes for quickly providing a mapping from old to new - use key=oldindex, value=newindex */ vertHash = BLI_ghash_int_new_ex("mask vert2 bh", (unsigned int)maxVerts); - + /* add vertices which exist in vertexgroup into ghash for filtering */ for (i = 0, dv = dvert; i < maxVerts; i++, dv++) { const bool found = defvert_find_weight(dv, defgrp_index) != 0.0f; @@ -251,12 +251,12 @@ static DerivedMesh *applyModifier( /* overalloc, assume all polys are seen */ loop_mapping = MEM_malloc_arrayN((size_t)maxPolys, sizeof(int), "mask loopmap"); - /* loop over edges and faces, and do the same thing to - * ensure that they only reference existing verts + /* loop over edges and faces, and do the same thing to + * ensure that they only reference existing verts */ for (i = 0; i < maxEdges; i++) { const MEdge *me = &medge_src[i]; - + /* only add if both verts will be in new mesh */ if (BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me->v1)) && BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me->v2))) @@ -270,14 +270,14 @@ static DerivedMesh *applyModifier( const MLoop *ml_src = &mloop_src[mp_src->loopstart]; bool ok = true; int j; - + for (j = 0; j < mp_src->totloop; j++, ml_src++) { if (!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(ml_src->v))) { ok = false; break; } } - + /* all verts must be available */ if (ok) { BLI_ghash_insert(polyHash, SET_INT_IN_POINTER(i), SET_INT_IN_POINTER(numPolys)); @@ -286,13 +286,13 @@ static DerivedMesh *applyModifier( numLoops += mp_src->totloop; } } - - - /* now we know the number of verts, edges and faces, + + + /* now we know the number of verts, edges and faces, * we can create the new (reduced) mesh */ result = CDDM_from_template(dm, numVerts, numEdges, 0, numLoops, numPolys); - + mpoly_dst = CDDM_get_polys(result); mloop_dst = CDDM_get_loops(result); medge_dst = CDDM_get_edges(result); @@ -305,21 +305,21 @@ static DerivedMesh *applyModifier( MVert *v_dst; const int i_src = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&gh_iter)); const int i_dst = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(&gh_iter)); - + v_src = &mvert_src[i_src]; v_dst = &mvert_dst[i_dst]; *v_dst = *v_src; DM_copy_vert_data(dm, result, i_src, i_dst, 1); } - + /* edges */ GHASH_ITER (gh_iter, edgeHash) { const MEdge *e_src; MEdge *e_dst; const int i_src = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&gh_iter)); const int i_dst = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(&gh_iter)); - + e_src = &medge_src[i_src]; e_dst = &medge_dst[i_dst]; @@ -328,7 +328,7 @@ static DerivedMesh *applyModifier( e_dst->v1 = GET_UINT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_UINT_IN_POINTER(e_src->v1))); e_dst->v2 = GET_UINT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_UINT_IN_POINTER(e_src->v2))); } - + /* faces */ GHASH_ITER (gh_iter, polyHash) { const int i_src = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&gh_iter)); @@ -339,7 +339,7 @@ static DerivedMesh *applyModifier( const int i_ml_dst = loop_mapping[i_dst]; const MLoop *ml_src = &mloop_src[i_ml_src]; MLoop *ml_dst = &mloop_dst[i_ml_dst]; - + DM_copy_poly_data(dm, result, i_src, i_dst, 1); DM_copy_loop_data(dm, result, i_ml_src, i_ml_dst, mp_src->totloop); @@ -356,7 +356,7 @@ static DerivedMesh *applyModifier( /* why is this needed? - campbell */ /* recalculate normals */ result->dirty |= DM_DIRTY_NORMALS; - + /* free hashes */ BLI_ghash_free(vertHash, NULL, NULL); BLI_ghash_free(edgeHash, NULL, NULL); diff --git a/source/blender/modifiers/intern/MOD_meshdeform.c b/source/blender/modifiers/intern/MOD_meshdeform.c index c45f778f2db1..39a6e9029b4a 100644 --- a/source/blender/modifiers/intern/MOD_meshdeform.c +++ b/source/blender/modifiers/intern/MOD_meshdeform.c @@ -96,7 +96,7 @@ static void copyData(const ModifierData *md, ModifierData *target) } static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md) -{ +{ MeshDeformModifierData *mmd = (MeshDeformModifierData *)md; CustomDataMask dataMask = 0; @@ -327,7 +327,7 @@ static void meshdeformModifier_do( if (cagedm) cagedm->needsFree = 1; } - + if (!cagedm) { modifier_setError(md, "Cannot get mesh from cage object"); return; @@ -465,7 +465,7 @@ void modifier_mdef_compact_influences(ModifierData *md) weights = mmd->bindweights; if (!weights) return; - + totvert = mmd->totvert; totcagevert = mmd->totcagevert; @@ -511,7 +511,7 @@ void modifier_mdef_compact_influences(ModifierData *md) } mmd->bindoffsets[b] = totinfluence; - + /* free */ MEM_freeN(mmd->bindweights); mmd->bindweights = NULL; diff --git a/source/blender/modifiers/intern/MOD_mirror.c b/source/blender/modifiers/intern/MOD_mirror.c index 23ee6379dee0..3f6480562d9b 100644 --- a/source/blender/modifiers/intern/MOD_mirror.c +++ b/source/blender/modifiers/intern/MOD_mirror.c @@ -200,7 +200,7 @@ static DerivedMesh *doMirrorOnAxis( vtmap_b++; } } - + /* handle shape keys */ totshape = CustomData_number_of_layers(&result->vertData, CD_SHAPEKEY); for (a = 0; a < totshape; a++) { @@ -209,14 +209,14 @@ static DerivedMesh *doMirrorOnAxis( mul_m4_v3(mtx, cos[i]); } } - + /* adjust mirrored edge vertex indices */ me = CDDM_get_edges(result) + maxEdges; for (i = 0; i < maxEdges; i++, me++) { me->v1 += maxVerts; me->v2 += maxVerts; } - + /* adjust mirrored poly loopstart indices, and reverse loop order (normals) */ mp = CDDM_get_polys(result) + maxPolys; ml = CDDM_get_loops(result); @@ -236,7 +236,7 @@ static DerivedMesh *doMirrorOnAxis( ml2[j].e = ml2[j + 1].e; } ml2[mp->totloop - 1].e = e; - + mp->loopstart += maxLoops; } @@ -274,7 +274,7 @@ static DerivedMesh *doMirrorOnAxis( int *flip_map = NULL, flip_map_len = 0; flip_map = defgroup_flip_map(ob, &flip_map_len, false); - + if (flip_map) { for (i = 0; i < maxVerts; dvert++, i++) { /* merged vertices get both groups, others get flipped */ @@ -336,7 +336,7 @@ static DerivedMesh *applyModifier( if (result != derivedData) result->dirty |= DM_DIRTY_NORMALS; - + return result; } diff --git a/source/blender/modifiers/intern/MOD_multires.c b/source/blender/modifiers/intern/MOD_multires.c index 183881d7d023..cdbacac97b99 100644 --- a/source/blender/modifiers/intern/MOD_multires.c +++ b/source/blender/modifiers/intern/MOD_multires.c @@ -93,17 +93,17 @@ static DerivedMesh *applyModifier( if (useRenderParams || !(flag & MOD_APPLY_USECACHE)) { DerivedMesh *cddm; - + cddm = CDDM_copy(result); /* copy hidden/masks to vertices */ if (!useRenderParams) { struct MDisps *mdisps; struct GridPaintMask *grid_paint_mask; - + mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS); grid_paint_mask = CustomData_get_layer(&me->ldata, CD_GRID_PAINT_MASK); - + if (mdisps) { subsurf_copy_grid_hidden(result, me->mpoly, cddm->getVertArray(cddm), diff --git a/source/blender/modifiers/intern/MOD_ocean.c b/source/blender/modifiers/intern/MOD_ocean.c index c29e835797b8..b845e62c530a 100644 --- a/source/blender/modifiers/intern/MOD_ocean.c +++ b/source/blender/modifiers/intern/MOD_ocean.c @@ -435,9 +435,6 @@ static DerivedMesh *doOcean( } /* update modifier */ - if (omd->refresh & MOD_OCEAN_REFRESH_ADD) { - omd->ocean = BKE_ocean_add(); - } if (omd->refresh & MOD_OCEAN_REFRESH_RESET) { init_ocean_modifier(omd); } diff --git a/source/blender/modifiers/intern/MOD_particleinstance.c b/source/blender/modifiers/intern/MOD_particleinstance.c index 9b5b07e4b74e..d88526e28454 100644 --- a/source/blender/modifiers/intern/MOD_particleinstance.c +++ b/source/blender/modifiers/intern/MOD_particleinstance.c @@ -163,7 +163,7 @@ static bool particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *ps if (p >= psys->totpart) { ChildParticle *cpa = psys->child + (p - psys->totpart); - pa = psys->particles + (between? cpa->pa[0]: cpa->parent); + pa = psys->particles + (between ? cpa->pa[0] : cpa->parent); } else { pa = psys->particles + p; @@ -187,8 +187,8 @@ static bool particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *ps /* TODO make randomization optional? */ randp = (int)(psys_frand(psys, 3578 + p) * totpart) % totpart; - minp = (int)(totpart * pimd->particle_offset) % (totpart+1); - maxp = (int)(totpart * (pimd->particle_offset + pimd->particle_amount)) % (totpart+1); + minp = (int)(totpart * pimd->particle_offset) % (totpart + 1); + maxp = (int)(totpart * (pimd->particle_offset + pimd->particle_amount)) % (totpart + 1); if (maxp > minp) { return randp < minp || randp >= maxp; @@ -223,7 +223,7 @@ static DerivedMesh *applyModifier( MPoly *mpoly, *orig_mpoly; MLoop *mloop, *orig_mloop; MVert *mvert, *orig_mvert; - int totvert, totpoly, totloop , totedge; + int totvert, totpoly, totloop, totedge; int maxvert, maxpoly, maxloop, maxedge, part_end = 0, part_start; int k, p, p_skip; short track = ob->trackflag % 3, trackneg, axis = pimd->axis; @@ -354,7 +354,7 @@ static DerivedMesh *applyModifier( for (p = part_start, p_skip = 0; p < part_end; p++) { float prev_dir[3]; float frame[4]; /* frame orientation quaternion */ - float p_random = psys_frand(psys, 77091 + 283*p); + float p_random = psys_frand(psys, 77091 + 283 * p); /* skip particle? */ if (particle_skip(pimd, psys, p)) @@ -418,7 +418,7 @@ static DerivedMesh *applyModifier( pa = psys->particles + p; else { ChildParticle *cpa = psys->child + (p - psys->totpart); - pa = psys->particles + (between? cpa->pa[0]: cpa->parent); + pa = psys->particles + (between ? cpa->pa[0] : cpa->parent); } psys_mat_hair_to_global(sim.ob, sim.psmd->dm_final, sim.psys->part->from, pa, hairmat); copy_m3_m4(mat, hairmat); @@ -426,7 +426,7 @@ static DerivedMesh *applyModifier( mat3_to_quat(frame, mat); if (pimd->rotation > 0.0f || pimd->random_rotation > 0.0f) { - float angle = 2.0f*M_PI * (pimd->rotation + pimd->random_rotation * (psys_frand(psys, 19957323 + p) - 0.5f)); + float angle = 2.0f * M_PI * (pimd->rotation + pimd->random_rotation * (psys_frand(psys, 19957323 + p) - 0.5f)); float eul[3] = { 0.0f, 0.0f, angle }; float rot[4]; diff --git a/source/blender/modifiers/intern/MOD_particlesystem.c b/source/blender/modifiers/intern/MOD_particlesystem.c index 04aec23e38ce..80b6c16b382b 100644 --- a/source/blender/modifiers/intern/MOD_particlesystem.c +++ b/source/blender/modifiers/intern/MOD_particlesystem.c @@ -49,7 +49,7 @@ #include "MOD_util.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md; psmd->psys = NULL; @@ -117,7 +117,7 @@ static void deformVerts( psys = psmd->psys; else return; - + if (!psys_check_enabled(ob, psys, (flag & MOD_APPLY_RENDER) != 0)) return; diff --git a/source/blender/modifiers/intern/MOD_remesh.c b/source/blender/modifiers/intern/MOD_remesh.c index cfe99c9a91b5..bd25f2cc727a 100644 --- a/source/blender/modifiers/intern/MOD_remesh.c +++ b/source/blender/modifiers/intern/MOD_remesh.c @@ -96,7 +96,7 @@ static void *dualcon_alloc_output(int totvert, int totquad) { return NULL; } - + output->dm = CDDM_new(totvert, 0, 0, 4 * totquad, totquad); return output; } @@ -105,9 +105,9 @@ static void dualcon_add_vert(void *output_v, const float co[3]) { DualConOutput *output = output_v; DerivedMesh *dm = output->dm; - + assert(output->curvert < dm->getNumVerts(dm)); - + copy_v3_v3(CDDM_get_verts(dm)[output->curvert].co, co); output->curvert++; } @@ -119,17 +119,17 @@ static void dualcon_add_quad(void *output_v, const int vert_indices[4]) MLoop *mloop; MPoly *cur_poly; int i; - + assert(output->curface < dm->getNumPolys(dm)); mloop = CDDM_get_loops(dm); cur_poly = CDDM_get_poly(dm, output->curface); - + cur_poly->loopstart = output->curface * 4; cur_poly->totloop = 4; for (i = 0; i < 4; i++) mloop[output->curface * 4 + i].v = vert_indices[i]; - + output->curface++; } @@ -164,7 +164,7 @@ static DerivedMesh *applyModifier( mode = DUALCON_SHARP_FEATURES; break; } - + output = dualcon(&input, dualcon_alloc_output, dualcon_add_vert, @@ -181,7 +181,7 @@ static DerivedMesh *applyModifier( if (rmd->flag & MOD_REMESH_SMOOTH_SHADING) { MPoly *mpoly = CDDM_get_polys(result); int i, totpoly = result->getNumPolys(result); - + /* Apply smooth shading to output faces */ for (i = 0; i < totpoly; i++) { mpoly[i].flag |= ME_SMOOTH; diff --git a/source/blender/modifiers/intern/MOD_screw.c b/source/blender/modifiers/intern/MOD_screw.c index 882dcb794623..5c1296d222e8 100644 --- a/source/blender/modifiers/intern/MOD_screw.c +++ b/source/blender/modifiers/intern/MOD_screw.c @@ -89,7 +89,7 @@ static void screwvert_iter_init(ScrewVertIter *iter, ScrewVertConnect *array, un iter->v_poin = NULL; iter->e = NULL; } -} +} static void screwvert_iter_step(ScrewVertIter *iter) @@ -185,7 +185,7 @@ static DerivedMesh *applyModifier( DerivedMesh *result; ScrewModifierData *ltmd = (ScrewModifierData *) md; const bool use_render_params = (flag & MOD_APPLY_RENDER) != 0; - + int *origindex; int mpoly_index = 0; unsigned int step; @@ -228,18 +228,18 @@ static DerivedMesh *applyModifier( float angle = ltmd->angle; float screw_ofs = ltmd->screw_ofs; float axis_vec[3] = {0.0f, 0.0f, 0.0f}; - float tmp_vec1[3], tmp_vec2[3]; + float tmp_vec1[3], tmp_vec2[3]; float mat3[3][3]; float mtx_tx[4][4]; /* transform the coords by an object relative to this objects transformation */ float mtx_tx_inv[4][4]; /* inverted */ float mtx_tmp_a[4][4]; - + unsigned int vc_tot_linked = 0; short other_axis_1, other_axis_2; const float *tmpf1, *tmpf2; unsigned int edge_offset; - + MPoly *mpoly_orig, *mpoly_new, *mp_new; MLoop *mloop_orig, *mloop_new, *ml_new; MEdge *medge_orig, *med_orig, *med_new, *med_new_firstloop, *medge_new; @@ -354,7 +354,7 @@ static DerivedMesh *applyModifier( close = 1; step_tot--; if (step_tot < 3) step_tot = 3; - + maxVerts = totvert * step_tot; /* -1 because we're joining back up */ maxEdges = (totvert * step_tot) + /* these are the edges between new verts */ (totedge * step_tot); /* -1 because vert edges join */ @@ -375,13 +375,13 @@ static DerivedMesh *applyModifier( if ((ltmd->flag & MOD_SCREW_UV_STRETCH_U) == 0) { uv_u_scale = (uv_u_scale / (float)ltmd->iter) * (angle / ((float)M_PI * 2.0f)); } - + result = CDDM_from_template(dm, (int)maxVerts, (int)maxEdges, 0, (int)maxPolys * 4, (int)maxPolys); - + /* copy verts from mesh */ mvert_orig = dm->getVertArray(dm); medge_orig = dm->getEdgeArray(dm); - + mvert_new = result->getVertArray(result); mpoly_new = result->getPolyArray(result); mloop_new = result->getLoopArray(result); @@ -421,10 +421,10 @@ static DerivedMesh *applyModifier( } /* Set the locations of the first set of verts */ - + mv_new = mvert_new; mv_orig = mvert_orig; - + /* Copy the first set of edges */ med_orig = medge_orig; med_new = medge_new; @@ -434,7 +434,7 @@ static DerivedMesh *applyModifier( med_new->crease = med_orig->crease; med_new->flag = med_orig->flag & ~ME_LOOSEEDGE; } - + /* build polygon -> edge map */ if (totpoly) { MPoly *mp_orig; @@ -829,7 +829,7 @@ static DerivedMesh *applyModifier( } } /* done with edge connectivity based normal flipping */ - + /* Add Faces */ for (step = 1; step < step_tot; step++) { const unsigned int varray_stride = totvert * step; @@ -852,10 +852,10 @@ static DerivedMesh *applyModifier( /* copy a slice */ DM_copy_vert_data(dm, result, 0, (int)varray_stride, (int)totvert); - + mv_new_base = mvert_new; mv_new = &mvert_new[varray_stride]; /* advance to the next slice */ - + for (j = 0; j < totvert; j++, mv_new_base++, mv_new++) { /* set normal */ if (vert_connect) { @@ -864,13 +864,13 @@ static DerivedMesh *applyModifier( /* set the normal now its transformed */ normal_float_to_short_v3(mv_new->no, nor_tx); } - + /* set location */ copy_v3_v3(mv_new->co, mv_new_base->co); - + /* only need to set these if using non cleared memory */ /*mv_new->mat_nr = mv_new->flag = 0;*/ - + if (ltmd->ob_axis) { sub_v3_v3(mv_new->co, mtx_tx[3]); @@ -881,7 +881,7 @@ static DerivedMesh *applyModifier( else { mul_m4_v3(mat, mv_new->co); } - + /* add the new edge */ med_new->v1 = varray_stride + j; med_new->v2 = med_new->v1 - totvert; @@ -907,11 +907,11 @@ static DerivedMesh *applyModifier( med_new++; } } - + mp_new = mpoly_new; ml_new = mloop_new; med_new_firstloop = medge_new; - + /* more of an offset in this case */ edge_offset = totedge + (totvert * (step_tot - (close ? 0 : 1))); @@ -1048,7 +1048,7 @@ static DerivedMesh *applyModifier( ml_new += 4; mpoly_index++; } - + /* new vertical edge */ med_new->v1 = i1; med_new->v2 = i2; diff --git a/source/blender/modifiers/intern/MOD_shrinkwrap.c b/source/blender/modifiers/intern/MOD_shrinkwrap.c index 1925bb23971e..c30be7d3a11b 100644 --- a/source/blender/modifiers/intern/MOD_shrinkwrap.c +++ b/source/blender/modifiers/intern/MOD_shrinkwrap.c @@ -168,7 +168,7 @@ static bool dependsOnNormals(ModifierData *md) if (smd->target && smd->shrinkType == MOD_SHRINKWRAP_PROJECT) return (smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL); - + return false; } diff --git a/source/blender/modifiers/intern/MOD_skin.c b/source/blender/modifiers/intern/MOD_skin.c index 9fe1dad1fff6..13e8f232b78a 100644 --- a/source/blender/modifiers/intern/MOD_skin.c +++ b/source/blender/modifiers/intern/MOD_skin.c @@ -268,7 +268,7 @@ static bool build_hull(SkinOutput *so, Frame **frames, int totframe) BMO_ITER (v, &oiter, op.slots_out, "geom_interior.out", BM_VERT) { for (i = 0; i < totframe; i++) { Frame *frame = frames[i]; - + if (!frame->detached) { for (j = 0; j < 4; j++) { if (frame->verts[j] == v) { @@ -294,7 +294,7 @@ static bool build_hull(SkinOutput *so, Frame **frames, int totframe) frame->detached = true; } } - + /* Remove triangles that would fill the original frames -- skip if * frame is partially detached */ BM_mesh_elem_hflag_disable_all(bm, BM_ALL_NOLOOP, BM_ELEM_TAG, false); @@ -449,7 +449,7 @@ static void node_frames_init(SkinNode *nf, int totframe) nf->totframe = totframe; memset(nf->frames, 0, sizeof(nf->frames)); - + nf->flag = 0; for (i = 0; i < 2; i++) nf->seam_edges[i] = -1; @@ -465,7 +465,7 @@ static void create_frame( mul_v3_v3fl(ry, mat[1], radius[0]); mul_v3_v3fl(rz, mat[2], radius[1]); - + add_v3_v3v3(frame->co[3], co, ry); add_v3_v3v3(frame->co[3], frame->co[3], rz); @@ -680,7 +680,7 @@ static void build_emats_stack( /* Mark edge as visited */ BLI_BITMAP_ENABLE(visited_e, e); - + /* Process edge */ parent_is_branch = ((emap[parent_v].count > 2) || @@ -937,14 +937,14 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig) /* Interpolate vertex group weights */ for (k = 0; k < totvgroup; k++) { float weight; - + vg = &vgroups[k]; weight = interpf(vg->w2, vg->w1, t); if (weight > 0) defvert_add_index_notest(&outdvert[v], vg->def_nr, weight); } - + outedge->v1 = u; outedge->v2 = v; u = v; @@ -952,7 +952,7 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig) if (vgroups) MEM_freeN(vgroups); - + /* Link up to final vertex */ outedge->v1 = u; outedge->v2 = e->v2; @@ -976,7 +976,7 @@ static void add_poly( { BMVert *verts[4] = {v1, v2, v3, v4}; BMFace *f; - + BLI_assert(v1 != v2 && v1 != v3 && v1 != v4); BLI_assert(v2 != v3 && v2 != v4); BLI_assert(v3 != v4); @@ -1063,7 +1063,7 @@ static void output_frames( dv = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_MDEFORMVERT); - + BLI_assert(dv->totweight == 0); defvert_copy(dv, input_dvert); } @@ -1093,14 +1093,14 @@ static int isect_ray_poly(const float ray_start[3], BMIter iter; float best_dist = FLT_MAX; bool hit = false; - + BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) { if (!v_first) v_first = v; else if (v_prev != v_first) { float dist; bool curhit; - + curhit = isect_ray_tri_v3(ray_start, ray_dir, v_first->co, v_prev->co, v->co, &dist, NULL); @@ -1161,7 +1161,7 @@ static BMFace *collapse_face_corners(BMesh *bm, BMFace *f, int n, f = NULL; BM_ITER_ELEM (vf, &iter, v_safe, BM_FACES_OF_VERT) { bool wrong_face = false; - + for (i = 0; i < orig_len; i++) { if (orig_verts[i] == v_merge) { orig_verts[i] = NULL; @@ -1259,7 +1259,7 @@ static void skin_choose_quad_bridge_order(BMVert *a[4], BMVert *b[4], shortest_len = FLT_MAX; for (i = 0; i < 8; i++) { float len = 0; - + /* Get total edge length for this configuration */ for (j = 0; j < 4; j++) len += len_squared_v3v3(a[j]->co, b[orders[i][j]]->co); @@ -1307,7 +1307,7 @@ static void skin_fix_hole_no_good_verts(BMesh *bm, Frame *frame, BMFace *split_f /* Need at least four ring edges, so subdivide longest edge if * face is a triangle */ longest_edge = BM_face_find_longest_loop(split_face)->e; - + BM_mesh_elem_hflag_disable_all(bm, BM_EDGE, BM_ELEM_TAG, false); BM_elem_flag_enable(longest_edge, BM_ELEM_TAG); @@ -1513,7 +1513,7 @@ static void skin_merge_close_frame_verts(SkinNode *skin_nodes, int totvert, { Frame **hull_frames; int v, tothullframe; - + for (v = 0; v < totvert; v++) { /* Only check branch nodes */ if (!skin_nodes[v].totframe) { @@ -1529,11 +1529,11 @@ static void skin_merge_close_frame_verts(SkinNode *skin_nodes, int totvert, static void skin_update_merged_vertices(SkinNode *skin_nodes, int totvert) { int v; - + for (v = 0; v < totvert; ++v) { SkinNode *sn = &skin_nodes[v]; int i, j; - + for (i = 0; i < sn->totframe; i++) { Frame *f = &sn->frames[i]; @@ -1553,19 +1553,19 @@ static void skin_fix_hull_topology(BMesh *bm, SkinNode *skin_nodes, int totvert) { int v; - + for (v = 0; v < totvert; v++) { SkinNode *sn = &skin_nodes[v]; int j; - + for (j = 0; j < sn->totframe; j++) { Frame *f = &sn->frames[j]; if (f->detached) { BMFace *target_face; - + skin_hole_detach_partially_attached_frame(bm, f); - + target_face = skin_hole_target_face(bm, f); if (target_face) skin_fix_hole_no_good_verts(bm, f, target_face); @@ -1578,14 +1578,14 @@ static void skin_output_end_nodes(SkinOutput *so, SkinNode *skin_nodes, int totvert) { int v; - + for (v = 0; v < totvert; ++v) { SkinNode *sn = &skin_nodes[v]; /* Assuming here just two frames */ if (sn->flag & SEAM_FRAME) { BMVert *v_order[4]; int i, order[4]; - + skin_choose_quad_bridge_order(sn->frames[0].verts, sn->frames[1].verts, order); @@ -1630,7 +1630,7 @@ static void skin_output_connections(SkinOutput *so, SkinNode *skin_nodes, int totedge) { int e; - + for (e = 0; e < totedge; e++) { SkinNode *a, *b; a = &skin_nodes[medge[e].v1]; @@ -1646,7 +1646,7 @@ static void skin_output_connections(SkinOutput *so, SkinNode *skin_nodes, fr[0]++; if ((b->flag & SEAM_FRAME) && (e != b->seam_edges[0])) fr[1]++; - + skin_choose_quad_bridge_order(fr[0]->verts, fr[1]->verts, order); for (i = 0; i < 4; i++) v_order[i] = fr[1]->verts[order[i]]; @@ -1729,15 +1729,15 @@ static bool skin_output_branch_hulls(SkinOutput *so, SkinNode *skin_nodes, { bool result = true; int v; - + for (v = 0; v < totvert; v++) { SkinNode *sn = &skin_nodes[v]; - + /* Branch node hulls */ if (!sn->totframe) { Frame **hull_frames; int tothullframe; - + hull_frames = collect_hull_frames(v, skin_nodes, emap, medge, &tothullframe); @@ -1765,7 +1765,7 @@ static BMesh *build_skin(SkinNode *skin_nodes, &bm_mesh_allocsize_default, &((struct BMeshCreateParams){.use_toolflags = true,})); so.mat_nr = 0; - + /* BMESH_TODO: bumping up the stack level (see MOD_array.c) */ BM_mesh_elem_toolflags_ensure(so.bm); BMO_push(so.bm, NULL); @@ -1878,7 +1878,7 @@ static DerivedMesh *base_skin(DerivedMesh *origdm, if (!bm) return NULL; - + result = CDDM_from_bmesh(bm, false); BM_mesh_free(bm); @@ -1912,7 +1912,7 @@ static DerivedMesh *final_skin(SkinModifierData *smd, static void initData(ModifierData *md) { SkinModifierData *smd = (SkinModifierData *) md; - + /* Enable in editmode by default */ md->mode |= eModifierMode_Editmode; diff --git a/source/blender/modifiers/intern/MOD_smoke.c b/source/blender/modifiers/intern/MOD_smoke.c index fb0648512d95..5f6d5ba58b56 100644 --- a/source/blender/modifiers/intern/MOD_smoke.c +++ b/source/blender/modifiers/intern/MOD_smoke.c @@ -57,10 +57,10 @@ #include "MOD_modifiertypes.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { SmokeModifierData *smd = (SmokeModifierData *) md; - + smd->domain = NULL; smd->flow = NULL; smd->coll = NULL; @@ -72,14 +72,14 @@ static void copyData(const ModifierData *md, ModifierData *target) { const SmokeModifierData *smd = (const SmokeModifierData *)md; SmokeModifierData *tsmd = (SmokeModifierData *)target; - + smokeModifier_copy(smd, tsmd); } static void freeData(ModifierData *md) { SmokeModifierData *smd = (SmokeModifierData *) md; - + smokeModifier_free(smd); } @@ -138,8 +138,8 @@ static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContex if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) { /* Actual code uses get_collisionobjects */ #ifdef WITH_LEGACY_DEPSGRAPH - dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->fluid_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow"); - dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->coll_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll"); + dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->fluid_group, ctx->object->lay | ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow"); + dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->coll_group, ctx->object->lay | ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll"); dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field"); #else (void)ctx; @@ -153,8 +153,8 @@ static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphConte if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) { /* Actual code uses get_collisionobjects */ - DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->fluid_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow"); - DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->coll_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll"); + DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->fluid_group, ctx->object->lay | ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow"); + DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->coll_group, ctx->object->lay | ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll"); DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field"); } diff --git a/source/blender/modifiers/intern/MOD_smooth.c b/source/blender/modifiers/intern/MOD_smooth.c index d2a086b5ff18..5aa38e2c6931 100644 --- a/source/blender/modifiers/intern/MOD_smooth.c +++ b/source/blender/modifiers/intern/MOD_smooth.c @@ -164,7 +164,7 @@ static void smoothModifier_do( /* fp is the sum of uctmp[i] verts, so must be averaged */ facw = 0.0f; - if (uctmp[i]) + if (uctmp[i]) facw = f / (float)uctmp[i]; if (flag & MOD_SMOOTH_X) @@ -185,7 +185,7 @@ static void smoothModifier_do( /* fp is the sum of uctmp[i] verts, so must be averaged */ facw = 0.0f; - if (uctmp[i]) + if (uctmp[i]) facw = fac / (float)uctmp[i]; if (flag & MOD_SMOOTH_X) diff --git a/source/blender/modifiers/intern/MOD_subsurf.c b/source/blender/modifiers/intern/MOD_subsurf.c index 18f9d0dc1b93..5a965c86a227 100644 --- a/source/blender/modifiers/intern/MOD_subsurf.c +++ b/source/blender/modifiers/intern/MOD_subsurf.c @@ -222,4 +222,3 @@ ModifierTypeInfo modifierType_Subsurf = { /* foreachIDLink */ NULL, /* foreachTexLink */ NULL, }; - diff --git a/source/blender/modifiers/intern/MOD_surface.c b/source/blender/modifiers/intern/MOD_surface.c index cd65112fd1ac..a64e05ffe1ec 100644 --- a/source/blender/modifiers/intern/MOD_surface.c +++ b/source/blender/modifiers/intern/MOD_surface.c @@ -49,10 +49,10 @@ #include "MEM_guardedalloc.h" -static void initData(ModifierData *md) +static void initData(ModifierData *md) { SurfaceModifierData *surmd = (SurfaceModifierData *) md; - + surmd->bvhtree = NULL; } @@ -72,7 +72,7 @@ static void freeData(ModifierData *md) } MEM_SAFE_FREE(surmd->x); - + MEM_SAFE_FREE(surmd->v); } } @@ -90,14 +90,14 @@ static void deformVerts( ModifierApplyFlag UNUSED(flag)) { SurfaceModifierData *surmd = (SurfaceModifierData *) md; - + if (surmd->dm) surmd->dm->release(surmd->dm); /* if possible use/create DerivedMesh */ if (derivedData) surmd->dm = CDDM_copy(derivedData); else surmd->dm = get_dm(ob, NULL, NULL, NULL, false, false); - + if (!ob->pd) { printf("SurfaceModifier deformVerts: Should not happen!\n"); return; @@ -111,7 +111,7 @@ static void deformVerts( CDDM_apply_vert_coords(surmd->dm, vertexCos); CDDM_calc_normals(surmd->dm); - + numverts = surmd->dm->getNumVerts(surmd->dm); if (numverts != surmd->numverts || @@ -145,7 +145,7 @@ static void deformVerts( v->co[0] = v->co[1] = v->co[2] = 0.0f; else sub_v3_v3v3(v->co, vec, x->co); - + copy_v3_v3(x->co, vec); } diff --git a/source/blender/modifiers/intern/MOD_util.c b/source/blender/modifiers/intern/MOD_util.c index a271d0baa918..3694428d62d2 100644 --- a/source/blender/modifiers/intern/MOD_util.c +++ b/source/blender/modifiers/intern/MOD_util.c @@ -186,7 +186,7 @@ DerivedMesh *get_dm( CDDM_apply_vert_coords(dm, vertexCos); dm->dirty |= DM_DIRTY_NORMALS; } - + if (use_orco) { DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, BKE_mesh_orco_verts_get(ob)); } diff --git a/source/blender/modifiers/intern/MOD_uvproject.c b/source/blender/modifiers/intern/MOD_uvproject.c index aa03be527be5..1089eb1bea46 100644 --- a/source/blender/modifiers/intern/MOD_uvproject.c +++ b/source/blender/modifiers/intern/MOD_uvproject.c @@ -177,7 +177,7 @@ static DerivedMesh *uvprojectModifier_do( projectors[i].uci = NULL; if (projectors[i].ob->type == OB_CAMERA) { - + cam = (Camera *)projectors[i].ob->data; if (cam->type == CAM_PANO) { projectors[i].uci = BLI_uvproject_camera_info(projectors[i].ob, NULL, aspx, aspy); @@ -241,7 +241,7 @@ static DerivedMesh *uvprojectModifier_do( /* convert coords to world space */ for (i = 0, co = coords; i < numVerts; ++i, ++co) mul_m4_v3(ob->obmat, *co); - + /* if only one projector, project coords to UVs */ if (num_projectors == 1 && projectors[0].uci == NULL) for (i = 0, co = coords; i < numVerts; ++i, ++co) @@ -322,7 +322,7 @@ static DerivedMesh *uvprojectModifier_do( } MEM_freeN(coords); - + if (free_uci) { int j; for (j = 0; j < num_projectors; ++j) { diff --git a/source/blender/modifiers/intern/MOD_weightvgproximity.c b/source/blender/modifiers/intern/MOD_weightvgproximity.c index 584c68756c18..47db0a3371ff 100644 --- a/source/blender/modifiers/intern/MOD_weightvgproximity.c +++ b/source/blender/modifiers/intern/MOD_weightvgproximity.c @@ -227,7 +227,7 @@ static void get_vert2ob_distance( */ static float get_ob2ob_distance(const Object *ob, const Object *obr) { - return len_v3v3(ob->obmat[3], obr->obmat[3]); + return len_v3v3(ob->obmat[3], obr->obmat[3]); } /** diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt index 958f275151fe..fbae0f76114d 100644 --- a/source/blender/nodes/CMakeLists.txt +++ b/source/blender/nodes/CMakeLists.txt @@ -59,6 +59,7 @@ set(SRC composite/nodes/node_composite_composite.c composite/nodes/node_composite_cornerpin.c composite/nodes/node_composite_crop.c + composite/nodes/node_composite_cryptomatte.c composite/nodes/node_composite_curves.c composite/nodes/node_composite_despeckle.c composite/nodes/node_composite_doubleEdgeMask.c @@ -172,6 +173,7 @@ set(SRC shader/nodes/node_shader_bsdf_transparent.c shader/nodes/node_shader_bsdf_velvet.c shader/nodes/node_shader_bsdf_hair.c + shader/nodes/node_shader_bsdf_hair_principled.c shader/nodes/node_shader_bump.c shader/nodes/node_shader_emission.c shader/nodes/node_shader_fresnel.c diff --git a/source/blender/nodes/NOD_composite.h b/source/blender/nodes/NOD_composite.h index a5c2e604f46e..2a82b706de57 100644 --- a/source/blender/nodes/NOD_composite.h +++ b/source/blender/nodes/NOD_composite.h @@ -109,6 +109,7 @@ void register_node_type_cmp_luma_matte(void); void register_node_type_cmp_doubleedgemask(void); void register_node_type_cmp_keyingscreen(void); void register_node_type_cmp_keying(void); +void register_node_type_cmp_cryptomatte(void); void register_node_type_cmp_translate(void); void register_node_type_cmp_rotate(void); diff --git a/source/blender/nodes/NOD_shader.h b/source/blender/nodes/NOD_shader.h index 6b2280da66cc..108e18902102 100644 --- a/source/blender/nodes/NOD_shader.h +++ b/source/blender/nodes/NOD_shader.h @@ -119,6 +119,7 @@ void register_node_type_sh_volume_absorption(void); void register_node_type_sh_volume_scatter(void); void register_node_type_sh_volume_principled(void); void register_node_type_sh_bsdf_hair(void); +void register_node_type_sh_bsdf_hair_principled(void); void register_node_type_sh_subsurface_scattering(void); void register_node_type_sh_mix_shader(void); void register_node_type_sh_add_shader(void); @@ -144,5 +145,3 @@ void register_node_type_sh_bump(void); void register_node_type_sh_tex_ies(void); #endif - - diff --git a/source/blender/nodes/NOD_static_types.h b/source/blender/nodes/NOD_static_types.h index ba2299856702..739ebe47a25f 100644 --- a/source/blender/nodes/NOD_static_types.h +++ b/source/blender/nodes/NOD_static_types.h @@ -92,6 +92,7 @@ DefNode( ShaderNode, SH_NODE_BSDF_TRANSPARENT, 0, "BS DefNode( ShaderNode, SH_NODE_BSDF_VELVET, 0, "BSDF_VELVET", BsdfVelvet, "Velvet BSDF", "" ) DefNode( ShaderNode, SH_NODE_BSDF_TOON, def_toon, "BSDF_TOON", BsdfToon, "Toon BSDF", "" ) DefNode( ShaderNode, SH_NODE_BSDF_HAIR, def_hair, "BSDF_HAIR", BsdfHair, "Hair BSDF", "" ) +DefNode( ShaderNode, SH_NODE_BSDF_HAIR_PRINCIPLED, def_hair_principled, "BSDF_HAIR_PRINCIPLED", BsdfHairPrincipled, "Principled Hair BSDF", "") DefNode( ShaderNode, SH_NODE_SUBSURFACE_SCATTERING, def_sh_subsurface, "SUBSURFACE_SCATTERING",SubsurfaceScattering,"Subsurface Scattering","") DefNode( ShaderNode, SH_NODE_VOLUME_ABSORPTION, 0, "VOLUME_ABSORPTION", VolumeAbsorption, "Volume Absorption", "" ) DefNode( ShaderNode, SH_NODE_VOLUME_SCATTER, 0, "VOLUME_SCATTER", VolumeScatter, "Volume Scatter", "" ) @@ -222,6 +223,7 @@ DefNode( CompositorNode, CMP_NODE_PIXELATE, 0, "PIXEL DefNode( CompositorNode, CMP_NODE_PLANETRACKDEFORM,def_cmp_planetrackdeform,"PLANETRACKDEFORM",PlaneTrackDeform,"Plane Track Deform","" ) DefNode( CompositorNode, CMP_NODE_CORNERPIN, 0, "CORNERPIN", CornerPin, "Corner Pin", "" ) DefNode( CompositorNode, CMP_NODE_SUNBEAMS, def_cmp_sunbeams, "SUNBEAMS", SunBeams, "Sun Beams", "" ) +DefNode( CompositorNode, CMP_NODE_CRYPTOMATTE, def_cmp_cryptomatte, "CRYPTOMATTE", Cryptomatte, "Cryptomatte", "" ) DefNode( TextureNode, TEX_NODE_OUTPUT, def_tex_output, "OUTPUT", Output, "Output", "" ) DefNode( TextureNode, TEX_NODE_CHECKER, 0, "CHECKER", Checker, "Checker", "" ) diff --git a/source/blender/nodes/composite/node_composite_tree.c b/source/blender/nodes/composite/node_composite_tree.c index ab9d041198c9..1312b7645464 100644 --- a/source/blender/nodes/composite/node_composite_tree.c +++ b/source/blender/nodes/composite/node_composite_tree.c @@ -280,7 +280,10 @@ void ntreeCompositTagRender(Scene *curscene) { Scene *sce; - for (sce = G.main->scene.first; sce; sce = sce->id.next) { + /* XXX Think using G_MAIN here is valid, since you want to update current file's scene nodes, + * not the ones in temp main generated for rendering? + * This is still rather weak though, ideally render struct would store own main AND original G_MAIN... */ + for (sce = G_MAIN->scene.first; sce; sce = sce->id.next) { if (sce->nodetree) { bNode *node; diff --git a/source/blender/nodes/composite/node_composite_util.c b/source/blender/nodes/composite/node_composite_util.c index 022794e8d42b..3f67804685ce 100644 --- a/source/blender/nodes/composite/node_composite_util.c +++ b/source/blender/nodes/composite/node_composite_util.c @@ -32,7 +32,7 @@ #include "node_composite_util.h" -int cmp_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) +bool cmp_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) { return STREQ(ntree->idname, "CompositorNodeTree"); } diff --git a/source/blender/nodes/composite/node_composite_util.h b/source/blender/nodes/composite/node_composite_util.h index 25827d914f44..3f05d7d1befd 100644 --- a/source/blender/nodes/composite/node_composite_util.h +++ b/source/blender/nodes/composite/node_composite_util.h @@ -60,9 +60,8 @@ #define CMP_SCALE_MAX 12000 -int cmp_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); +bool cmp_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); void cmp_node_update_default(struct bNodeTree *UNUSED(ntree), struct bNode *node); void cmp_node_type_base(struct bNodeType *ntype, int type, const char *name, short nclass, short flag); #endif /* __NODE_COMPOSITE_UTIL_H__ */ - diff --git a/source/blender/nodes/composite/nodes/node_composite_common.c b/source/blender/nodes/composite/nodes/node_composite_common.c index de97a5beac32..8efa44e2e5d6 100644 --- a/source/blender/nodes/composite/nodes/node_composite_common.c +++ b/source/blender/nodes/composite/nodes/node_composite_common.c @@ -64,4 +64,3 @@ void register_node_type_cmp_group(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/composite/nodes/node_composite_cryptomatte.c b/source/blender/nodes/composite/nodes/node_composite_cryptomatte.c new file mode 100644 index 000000000000..bf9ab4a5064e --- /dev/null +++ b/source/blender/nodes/composite/nodes/node_composite_cryptomatte.c @@ -0,0 +1,302 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is Copyright (C) 2018 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Lukas Stockner, Stefan Werner + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/nodes/composite/nodes/node_composite_cryptomatte.c + * \ingroup cmpnodes + */ + +#include "node_composite_util.h" +#include "BLI_assert.h" +#include "BLI_dynstr.h" +#include "BLI_hash_mm3.h" +#include "BLI_utildefines.h" + +/* this is taken from the cryptomatte specification 1.0 */ + +static inline float hash_to_float(uint32_t hash) +{ + uint32_t mantissa = hash & ((1 << 23) - 1); + uint32_t exponent = (hash >> 23) & ((1 << 8) - 1); + exponent = MAX2(exponent, (uint32_t)1); + exponent = MIN2(exponent, (uint32_t)254); + exponent = exponent << 23; + uint32_t sign = (hash >> 31); + sign = sign << 31; + uint32_t float_bits = sign | exponent | mantissa; + float f; + /* Bit casting relies on equal size for both types. */ + BLI_STATIC_ASSERT(sizeof(float) == sizeof(uint32_t), "float and uint32_t are not the same size") + memcpy(&f, &float_bits, sizeof(float)); + return f; +} + +static void cryptomatte_add(NodeCryptomatte *n, float f) +{ + /* Turn the number into a string. */ + char number[32]; + BLI_snprintf(number, sizeof(number), "<%.9g>", f); + + /* Search if we already have the number. */ + if (n->matte_id && strlen(n->matte_id) != 0) { + size_t start = 0; + const size_t end = strlen(n->matte_id); + size_t token_len = 0; + while (start < end) { + /* Ignore leading whitespace. */ + while (start < end && n->matte_id[start] == ' ') { + ++start; + } + + /* Find the next seprator. */ + char *token_end = strchr(n->matte_id + start, ','); + if (token_end == NULL || token_end == n->matte_id + start) { + token_end = n->matte_id + end; + } + /* Be aware that token_len still contains any trailing white space. */ + token_len = token_end - (n->matte_id + start); + + /* If this has a leading bracket, assume a raw floating point number and look for the closing bracket. */ + if (n->matte_id[start] == '<') { + if (strncmp(n->matte_id + start, number, strlen(number)) == 0) { + /* This number is already there, so continue. */ + return; + } + } + else { + /* Remove trailing white space */ + size_t name_len = token_len; + while (n->matte_id[start + name_len] == ' ' && name_len > 0) { + name_len--; + } + /* Calculate the hash of the token and compare. */ + uint32_t hash = BLI_hash_mm3((const unsigned char *)(n->matte_id + start), name_len, 0); + if (f == hash_to_float(hash)) { + return; + } + } + start += token_len + 1; + } + } + + DynStr *new_matte = BLI_dynstr_new(); + if (!new_matte) { + return; + } + + if (n->matte_id) { + BLI_dynstr_append(new_matte, n->matte_id); + MEM_freeN(n->matte_id); + } + + if (BLI_dynstr_get_len(new_matte) > 0) { + BLI_dynstr_append(new_matte, ","); + } + BLI_dynstr_append(new_matte, number); + n->matte_id = BLI_dynstr_get_cstring(new_matte); + BLI_dynstr_free(new_matte); +} + +static void cryptomatte_remove(NodeCryptomatte *n, float f) +{ + if (n->matte_id == NULL || strlen(n->matte_id) == 0) { + /* Empty string, nothing to remove. */ + return; + } + + /* This will be the new string without the removed key. */ + DynStr *new_matte = BLI_dynstr_new(); + if (!new_matte) { + return; + } + + /* Turn the number into a string. */ + static char number[32]; + BLI_snprintf(number, sizeof(number), "<%.9g>", f); + + /* Search if we already have the number. */ + size_t start = 0; + const size_t end = strlen(n->matte_id); + size_t token_len = 0; + bool is_first = true; + while (start < end) { + bool skip = false; + /* Ignore leading whitespace or commas. */ + while (start < end && ((n->matte_id[start] == ' ') || (n->matte_id[start] == ','))) { + ++start; + } + + /* Find the next seprator. */ + char *token_end = strchr(n->matte_id + start + 1, ','); + if (token_end == NULL || token_end == n->matte_id + start) { + token_end = n->matte_id + end; + } + /* Be aware that token_len still contains any trailing white space. */ + token_len = token_end - (n->matte_id + start); + + if (token_len == 1) { + skip = true; + } + /* If this has a leading bracket, assume a raw floating point number and look for the closing bracket. */ + else if (n->matte_id[start] == '<') { + if (strncmp(n->matte_id + start, number, strlen(number)) == 0) { + /* This number is already there, so skip it. */ + skip = true; + } + } + else { + /* Remove trailing white space */ + size_t name_len = token_len; + while (n->matte_id[start + name_len] == ' ' && name_len > 0) { + name_len--; + } + /* Calculate the hash of the token and compare. */ + uint32_t hash = BLI_hash_mm3((const unsigned char *)(n->matte_id + start), name_len, 0); + if (f == hash_to_float(hash)) { + skip = true; + } + } + if (!skip) { + if (is_first) { + is_first = false; + } + else { + BLI_dynstr_append(new_matte, ", "); + } + BLI_dynstr_nappend(new_matte, n->matte_id + start, token_len); + } + start += token_len + 1; + } + + if (n->matte_id) { + MEM_freeN(n->matte_id); + n->matte_id = NULL; + } + if (BLI_dynstr_get_len(new_matte) > 0) { + n->matte_id = BLI_dynstr_get_cstring(new_matte); + } + BLI_dynstr_free(new_matte); +} + +static bNodeSocketTemplate outputs[] = { + { SOCK_RGBA, 0, N_("Image")}, + { SOCK_FLOAT, 0, N_("Matte")}, + { SOCK_RGBA, 0, N_("Pick")}, + { -1, 0, "" } +}; + +void ntreeCompositCryptomatteSyncFromAdd(bNodeTree *UNUSED(ntree), bNode *node) +{ + NodeCryptomatte *n = node->storage; + if (n->add[0] != 0.0f) { + cryptomatte_add(n, n->add[0]); + n->add[0] = 0.0f; + n->add[1] = 0.0f; + n->add[2] = 0.0f; + } +} + +void ntreeCompositCryptomatteSyncFromRemove(bNodeTree *UNUSED(ntree), bNode *node) +{ + NodeCryptomatte *n = node->storage; + if (n->remove[0] != 0.0f) { + cryptomatte_remove(n, n->remove[0]); + n->remove[0] = 0.0f; + n->remove[1] = 0.0f; + n->remove[2] = 0.0f; + } +} + +bNodeSocket *ntreeCompositCryptomatteAddSocket(bNodeTree *ntree, bNode *node) +{ + NodeCryptomatte *n = node->storage; + char sockname[32]; + n->num_inputs++; + BLI_snprintf(sockname, sizeof(sockname), "Crypto %.2d", n->num_inputs - 1); + bNodeSocket *sock = nodeAddStaticSocket(ntree, node, SOCK_IN, SOCK_RGBA, PROP_NONE, NULL, sockname); + return sock; +} + +int ntreeCompositCryptomatteRemoveSocket(bNodeTree *ntree, bNode *node) +{ + NodeCryptomatte *n = node->storage; + if (n->num_inputs < 2) { + return 0; + } + bNodeSocket *sock = node->inputs.last; + nodeRemoveSocket(ntree, node, sock); + n->num_inputs--; + return 1; +} + +static void init(bNodeTree *ntree, bNode *node) +{ + NodeCryptomatte *user = MEM_callocN(sizeof(NodeCryptomatte), "cryptomatte user"); + node->storage = user; + + + nodeAddStaticSocket(ntree, node, SOCK_IN, SOCK_RGBA, PROP_NONE, "image", "Image"); + + /* Add three inputs by default, as recommended by the Cryptomatte specification. */ + ntreeCompositCryptomatteAddSocket(ntree, node); + ntreeCompositCryptomatteAddSocket(ntree, node); + ntreeCompositCryptomatteAddSocket(ntree, node); +} + +static void node_free_cryptomatte(bNode *node) +{ + NodeCryptomatte *nc = node->storage; + + if (nc) { + if (nc->matte_id) { + MEM_freeN(nc->matte_id); + } + + MEM_freeN(nc); + } +} + +static void node_copy_cryptomatte(bNodeTree *UNUSED(dest_ntree), bNode *dest_node, bNode *src_node) +{ + NodeCryptomatte *src_nc = src_node->storage; + NodeCryptomatte *dest_nc = MEM_dupallocN(src_nc); + + if (src_nc->matte_id) + dest_nc->matte_id = MEM_dupallocN(src_nc->matte_id); + + dest_node->storage = dest_nc; +} + +void register_node_type_cmp_cryptomatte(void) +{ + static bNodeType ntype; + + cmp_node_type_base(&ntype, CMP_NODE_CRYPTOMATTE, "Cryptomatte", NODE_CLASS_CONVERTOR, 0); + node_type_socket_templates(&ntype, NULL, outputs); + node_type_init(&ntype, init); + node_type_storage(&ntype, "NodeCryptomatte", node_free_cryptomatte, node_copy_cryptomatte); + nodeRegisterType(&ntype); +} diff --git a/source/blender/nodes/composite/nodes/node_composite_image.c b/source/blender/nodes/composite/nodes/node_composite_image.c index bf50070e5cb3..52e58a0ebd3b 100644 --- a/source/blender/nodes/composite/nodes/node_composite_image.c +++ b/source/blender/nodes/composite/nodes/node_composite_image.c @@ -388,7 +388,7 @@ static void node_composit_init_rlayers(const bContext *C, PointerRNA *ptr) } } -static int node_composit_poll_rlayers(bNodeType *UNUSED(ntype), bNodeTree *ntree) +static bool node_composit_poll_rlayers(bNodeType *UNUSED(ntype), bNodeTree *ntree) { if (STREQ(ntree->idname, "CompositorNodeTree")) { Scene *scene; diff --git a/source/blender/nodes/composite/nodes/node_composite_switch.c b/source/blender/nodes/composite/nodes/node_composite_switch.c index d7de26730d0a..60d8a13d8d71 100644 --- a/source/blender/nodes/composite/nodes/node_composite_switch.c +++ b/source/blender/nodes/composite/nodes/node_composite_switch.c @@ -53,4 +53,3 @@ void register_node_type_cmp_switch(void) node_type_size_preset(&ntype, NODE_SIZE_SMALL); nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/intern/node_common.c b/source/blender/nodes/intern/node_common.c index 4a47bf7035c7..cb04b341c267 100644 --- a/source/blender/nodes/intern/node_common.c +++ b/source/blender/nodes/intern/node_common.c @@ -81,7 +81,7 @@ void node_group_label(bNodeTree *UNUSED(ntree), bNode *node, char *label, int ma BLI_strncpy(label, (node->id) ? node->id->name + 2 : IFACE_("Missing Data-Block"), maxlen); } -int node_group_poll_instance(bNode *node, bNodeTree *nodetree) +bool node_group_poll_instance(bNode *node, bNodeTree *nodetree) { if (node->typeinfo->poll(node->typeinfo, nodetree)) { bNodeTree *grouptree = (bNodeTree *)node->id; diff --git a/source/blender/nodes/intern/node_common.h b/source/blender/nodes/intern/node_common.h index edc1f19f5545..737489474f93 100644 --- a/source/blender/nodes/intern/node_common.h +++ b/source/blender/nodes/intern/node_common.h @@ -38,7 +38,7 @@ struct bNodeTree; void node_group_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen); -int node_group_poll_instance(struct bNode *node, struct bNodeTree *nodetree); +bool node_group_poll_instance(struct bNode *node, struct bNodeTree *nodetree); void ntree_update_reroute_nodes(struct bNodeTree *ntree); diff --git a/source/blender/nodes/intern/node_exec.c b/source/blender/nodes/intern/node_exec.c index a5be5dad534d..4f7f5b5ab1cc 100644 --- a/source/blender/nodes/intern/node_exec.c +++ b/source/blender/nodes/intern/node_exec.c @@ -163,6 +163,8 @@ bNodeTreeExec *ntree_exec_begin(bNodeExecContext *context, bNodeTree *ntree, bNo /* XXX texnodes have threading issues with muting, have to disable it there ... */ /* ensure all sock->link pointers and node levels are correct */ + /* Using global main here is likely totally wrong, not sure what to do about that one though... + * We cannot even check ntree is in global main, since most of the time it won't be (thanks to ntree design)!!! */ ntreeUpdateTree(G.main, ntree); /* get a dependency-sorted list of nodes */ diff --git a/source/blender/nodes/shader/node_shader_tree.c b/source/blender/nodes/shader/node_shader_tree.c index e63dd1d99903..16fda7730409 100644 --- a/source/blender/nodes/shader/node_shader_tree.c +++ b/source/blender/nodes/shader/node_shader_tree.c @@ -64,7 +64,7 @@ #include "node_util.h" #include "node_shader_util.h" -static int shader_tree_poll(const bContext *C, bNodeTreeType *UNUSED(treetype)) +static bool shader_tree_poll(const bContext *C, bNodeTreeType *UNUSED(treetype)) { Scene *scene = CTX_data_scene(C); /* allow empty engine string too, this is from older versions that didn't have registerable engines yet */ diff --git a/source/blender/nodes/shader/node_shader_util.c b/source/blender/nodes/shader/node_shader_util.c index b25a6c2bba06..3103057cbcf5 100644 --- a/source/blender/nodes/shader/node_shader_util.c +++ b/source/blender/nodes/shader/node_shader_util.c @@ -37,7 +37,7 @@ #include "node_exec.h" -int sh_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) +bool sh_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) { return STREQ(ntree->idname, "ShaderNodeTree"); } @@ -315,4 +315,3 @@ void node_shader_gpu_tex_mapping(GPUMaterial *mat, bNode *node, GPUNodeStack *in GPU_link(mat, "texco_norm", in[0].link, &in[0].link); } } - diff --git a/source/blender/nodes/shader/node_shader_util.h b/source/blender/nodes/shader/node_shader_util.h index 51643d63f5e3..e2c1fe7897b6 100644 --- a/source/blender/nodes/shader/node_shader_util.h +++ b/source/blender/nodes/shader/node_shader_util.h @@ -80,7 +80,7 @@ #include "GPU_material.h" -int sh_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); +bool sh_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); void sh_node_type_base(struct bNodeType *ntype, int type, const char *name, short nclass, short flag); diff --git a/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c b/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c index cad0fcaa14fb..995ff0cfd401 100644 --- a/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c +++ b/source/blender/nodes/shader/nodes/node_shader_ambient_occlusion.c @@ -30,14 +30,14 @@ /* **************** OUTPUT ******************** */ static bNodeSocketTemplate sh_node_ambient_occlusion_in[] = { - { SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f}, + { SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f}, { SOCK_FLOAT, 0, N_("Distance"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f}, { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE}, { -1, 0, "" } }; static bNodeSocketTemplate sh_node_ambient_occlusion_out[] = { - { SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f}, + { SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f}, { SOCK_FLOAT, 0, N_("AO"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, { -1, 0, "" } }; @@ -49,8 +49,8 @@ static int node_shader_gpu_ambient_occlusion(GPUMaterial *mat, bNode *UNUSED(nod static void node_shader_init_ambient_occlusion(bNodeTree *UNUSED(ntree), bNode *node) { - node->custom1 = 8; /* samples */ - node->custom2 = SHD_AO_LOCAL; + node->custom1 = 16; /* samples */ + node->custom2 = 0; } /* node type definition */ @@ -67,4 +67,3 @@ void register_node_type_sh_ambient_occlusion(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_attribute.c b/source/blender/nodes/shader/nodes/node_shader_attribute.c index 0a69593cf077..ba5fa131d3e8 100644 --- a/source/blender/nodes/shader/nodes/node_shader_attribute.c +++ b/source/blender/nodes/shader/nodes/node_shader_attribute.c @@ -64,4 +64,3 @@ void register_node_type_sh_attribute(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_hair_principled.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_hair_principled.c new file mode 100644 index 000000000000..aeeb262a5a6f --- /dev/null +++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_hair_principled.c @@ -0,0 +1,133 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is Copyright (C) 2018 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Lukas Stockner, L. E. Segovia + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include "../node_shader_util.h" + +/* **************** OUTPUT ******************** */ + +/* Color, melanin and absorption coefficient default to approximately same brownish hair. */ +static bNodeSocketTemplate sh_node_bsdf_hair_principled_in[] = { + { SOCK_RGBA, 1, N_("Color"), 0.017513f, 0.005763f, 0.002059f, 1.0f, 0.0f, 1.0f}, + { SOCK_FLOAT, 1, N_("Melanin"), 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("Melanin Redness"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_RGBA, 1, N_("Tint"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f}, + { SOCK_VECTOR, 1, N_("Absorption Coefficient"), 0.245531f, 0.52f, 1.365f, 0.0f, 0.0f, 1000.0f}, + { SOCK_FLOAT, 1, N_("Roughness"), 0.3f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("Radial Roughness"), 0.3f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("Coat"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("IOR"), 1.55f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f}, + { SOCK_FLOAT, 1, N_("Offset"), 2.0f * ((float)M_PI) / 180.f, 0.0f, 0.0f, 0.0f, -M_PI_2, M_PI_2, PROP_ANGLE}, + { SOCK_FLOAT, 1, N_("Random Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("Random Roughness"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR}, + { SOCK_FLOAT, 1, N_("Random"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE}, + { -1, 0, "" }, +}; + +static bNodeSocketTemplate sh_node_bsdf_hair_principled_out[] = { + { SOCK_SHADER, 0, N_("BSDF")}, + { -1, 0, "" } +}; + +/* Initialize the custom Parametrization property to Color. */ +static void node_shader_init_hair_principled(bNodeTree *UNUSED(ntree), bNode *node) +{ + node->custom1 = SHD_PRINCIPLED_HAIR_REFLECTANCE; +} + +/* Triggers (in)visibility of some sockets when changing Parametrization. */ +static void node_shader_update_hair_principled(bNodeTree *UNUSED(ntree), bNode *node) +{ + bNodeSocket *sock; + int parametrization = node->custom1; + + for (sock = node->inputs.first; sock; sock = sock->next) { + if (STREQ(sock->name, "Color")) { + if (parametrization == SHD_PRINCIPLED_HAIR_REFLECTANCE) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + else if (STREQ(sock->name, "Melanin")) { + if (parametrization == SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + else if (STREQ(sock->name, "Melanin Redness")) { + if (parametrization == SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + else if (STREQ(sock->name, "Tint")) { + if (parametrization == SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + else if (STREQ(sock->name, "Absorption Coefficient")) { + if (parametrization == SHD_PRINCIPLED_HAIR_DIRECT_ABSORPTION) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + else if (STREQ(sock->name, "Random Color")) { + if (parametrization == SHD_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + } +} + +/* node type definition */ +void register_node_type_sh_bsdf_hair_principled(void) +{ + static bNodeType ntype; + + sh_node_type_base(&ntype, SH_NODE_BSDF_HAIR_PRINCIPLED, "Principled Hair BSDF", NODE_CLASS_SHADER, 0); + node_type_compatibility(&ntype, NODE_NEW_SHADING); + node_type_socket_templates(&ntype, sh_node_bsdf_hair_principled_in, sh_node_bsdf_hair_principled_out); + node_type_size_preset(&ntype, NODE_SIZE_LARGE); + node_type_init(&ntype, node_shader_init_hair_principled); + node_type_storage(&ntype, "", NULL, NULL); + node_type_update(&ntype, node_shader_update_hair_principled, NULL); + + nodeRegisterType(&ntype); +} diff --git a/source/blender/nodes/shader/nodes/node_shader_emission.c b/source/blender/nodes/shader/nodes/node_shader_emission.c index 1901ede4d9cf..2838e9dc54d7 100644 --- a/source/blender/nodes/shader/nodes/node_shader_emission.c +++ b/source/blender/nodes/shader/nodes/node_shader_emission.c @@ -30,7 +30,7 @@ /* **************** OUTPUT ******************** */ static bNodeSocketTemplate sh_node_emission_in[] = { - { SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f}, + { SOCK_RGBA, 1, N_("Color"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f}, { SOCK_FLOAT, 1, N_("Strength"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000000.0f}, { -1, 0, "" } }; diff --git a/source/blender/nodes/shader/nodes/node_shader_light_falloff.c b/source/blender/nodes/shader/nodes/node_shader_light_falloff.c index a137223e3db7..e28920d6f6e7 100644 --- a/source/blender/nodes/shader/nodes/node_shader_light_falloff.c +++ b/source/blender/nodes/shader/nodes/node_shader_light_falloff.c @@ -64,4 +64,3 @@ void register_node_type_sh_light_falloff(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_math.c b/source/blender/nodes/shader/nodes/node_shader_math.c index 0a75a0f8bf06..605c869099a6 100644 --- a/source/blender/nodes/shader/nodes/node_shader_math.c +++ b/source/blender/nodes/shader/nodes/node_shader_math.c @@ -226,6 +226,46 @@ static void node_shader_exec_math(void *UNUSED(data), int UNUSED(thread), bNode r = atan2(a, b); break; } + case NODE_MATH_FLOOR: + { + if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */ + r = floorf(a); + else + r = floorf(b); + break; + } + case NODE_MATH_CEIL: + { + if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */ + r = ceilf(a); + else + r = ceilf(b); + break; + } + case NODE_MATH_FRACT: + { + if (in[0]->hasinput || !in[1]->hasinput) /* This one only takes one input, so we've got to choose. */ + r = a - floorf(a); + else + r = b - floorf(b); + break; + } + case NODE_MATH_SQRT: + { + if (in[0]->hasinput || !in[1]->hasinput) { /* This one only takes one input, so we've got to choose. */ + if (a > 0) + r = sqrt(a); + else + r = 0.0; + } + else { + if (b > 0) + r = sqrt(b); + else + r = 0.0; + } + break; + } } if (node->custom2 & SHD_MATH_CLAMP) { CLAMP(r, 0.0f, 1.0f); @@ -240,7 +280,7 @@ static int gpu_shader_math(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED( "math_divide", "math_sine", "math_cosine", "math_tangent", "math_asin", "math_acos", "math_atan", "math_pow", "math_log", "math_min", "math_max", "math_round", "math_less_than", "math_greater_than", "math_modulo", "math_abs", - "math_atan2" + "math_atan2", "math_floor", "math_ceil", "math_fract", "math_sqrt" }; switch (node->custom1) { @@ -266,6 +306,10 @@ static int gpu_shader_math(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED( case NODE_MATH_ATAN: case NODE_MATH_ROUND: case NODE_MATH_ABS: + case NODE_MATH_FLOOR: + case NODE_MATH_FRACT: + case NODE_MATH_CEIL: + case NODE_MATH_SQRT: if (in[0].hasinput || !in[1].hasinput) { /* use only first item and terminator */ GPUNodeStack tmp_in[2]; diff --git a/source/blender/nodes/shader/nodes/node_shader_object_info.c b/source/blender/nodes/shader/nodes/node_shader_object_info.c index cfe417e30964..9c7ea549ea50 100644 --- a/source/blender/nodes/shader/nodes/node_shader_object_info.c +++ b/source/blender/nodes/shader/nodes/node_shader_object_info.c @@ -66,4 +66,3 @@ void register_node_type_sh_object_info(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_particle_info.c b/source/blender/nodes/shader/nodes/node_shader_particle_info.c index 3dbe5c81c570..6dd8fbee3d28 100644 --- a/source/blender/nodes/shader/nodes/node_shader_particle_info.c +++ b/source/blender/nodes/shader/nodes/node_shader_particle_info.c @@ -72,4 +72,3 @@ void register_node_type_sh_particle_info(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c b/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c index ca6a66625574..78757782203e 100644 --- a/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c +++ b/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c @@ -91,4 +91,3 @@ void register_node_type_sh_subsurface_scattering(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c b/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c index 8c5ddaafa1e4..e5bf8f497170 100644 --- a/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c +++ b/source/blender/nodes/shader/nodes/node_shader_tex_voronoi.c @@ -32,6 +32,7 @@ static bNodeSocketTemplate sh_node_tex_voronoi_in[] = { { SOCK_VECTOR, 1, N_("Vector"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE}, { SOCK_FLOAT, 1, N_("Scale"), 5.0f, 0.0f, 0.0f, 0.0f, -1000.0f, 1000.0f}, + { SOCK_FLOAT, 1, N_("Exponent"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 32.0f}, { -1, 0, "" } }; @@ -47,6 +48,8 @@ static void node_shader_init_tex_voronoi(bNodeTree *UNUSED(ntree), bNode *node) BKE_texture_mapping_default(&tex->base.tex_mapping, TEXMAP_TYPE_POINT); BKE_texture_colormapping_default(&tex->base.color_mapping); tex->coloring = SHD_VORONOI_INTENSITY; + tex->distance = SHD_VORONOI_DISTANCE; + tex->feature = SHD_VORONOI_F1; node->storage = tex; } @@ -66,6 +69,23 @@ static int node_shader_gpu_tex_voronoi(GPUMaterial *mat, bNode *node, bNodeExecD return GPU_stack_link(mat, "node_tex_voronoi", in, out, GPU_uniform(&coloring)); } +static void node_shader_update_tex_voronoi(bNodeTree *UNUSED(ntree), bNode *node) +{ + NodeTexVoronoi *tex = (NodeTexVoronoi *)node->storage; + bNodeSocket *sock; + + for (sock = node->inputs.first; sock; sock = sock->next) { + if (STREQ(sock->name, "Exponent")) { + if (tex->distance == SHD_VORONOI_MINKOWSKI) { + sock->flag &= ~SOCK_UNAVAIL; + } + else { + sock->flag |= SOCK_UNAVAIL; + } + } + } +} + /* node type definition */ void register_node_type_sh_tex_voronoi(void) { @@ -77,6 +97,7 @@ void register_node_type_sh_tex_voronoi(void) node_type_init(&ntype, node_shader_init_tex_voronoi); node_type_storage(&ntype, "NodeTexVoronoi", node_free_standard_storage, node_copy_standard_storage); node_type_gpu(&ntype, node_shader_gpu_tex_voronoi); + node_type_update(&ntype, node_shader_update_tex_voronoi, NULL); nodeRegisterType(&ntype); } diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_principled.c b/source/blender/nodes/shader/nodes/node_shader_volume_principled.c index e85fec1ec9d0..8aaf84dc2f0d 100644 --- a/source/blender/nodes/shader/nodes/node_shader_volume_principled.c +++ b/source/blender/nodes/shader/nodes/node_shader_volume_principled.c @@ -82,4 +82,3 @@ void register_node_type_sh_volume_principled(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c b/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c index aa47a44b0a6e..33180e8ecf17 100644 --- a/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c +++ b/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c @@ -60,4 +60,3 @@ void register_node_type_sh_volume_scatter(void) nodeRegisterType(&ntype); } - diff --git a/source/blender/nodes/texture/node_texture_util.c b/source/blender/nodes/texture/node_texture_util.c index 0682fa9f4148..6b9f29475b50 100644 --- a/source/blender/nodes/texture/node_texture_util.c +++ b/source/blender/nodes/texture/node_texture_util.c @@ -50,7 +50,7 @@ #include "node_texture_util.h" -int tex_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) +bool tex_node_poll_default(bNodeType *UNUSED(ntype), bNodeTree *ntree) { return STREQ(ntree->idname, "TextureNodeTree"); } diff --git a/source/blender/nodes/texture/node_texture_util.h b/source/blender/nodes/texture/node_texture_util.h index c3ccd08b2757..389be543d7e9 100644 --- a/source/blender/nodes/texture/node_texture_util.h +++ b/source/blender/nodes/texture/node_texture_util.h @@ -116,7 +116,7 @@ typedef struct TexDelegate { } TexDelegate; -int tex_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); +bool tex_node_poll_default(struct bNodeType *ntype, struct bNodeTree *ntree); void tex_node_type_base(struct bNodeType *ntype, int type, const char *name, short nclass, short flag); void tex_input_rgba(float *out, bNodeStack *in, TexParams *params, short thread); diff --git a/source/blender/nodes/texture/nodes/node_texture_math.c b/source/blender/nodes/texture/nodes/node_texture_math.c index d8dc2a62625e..f786a293080c 100644 --- a/source/blender/nodes/texture/nodes/node_texture_math.c +++ b/source/blender/nodes/texture/nodes/node_texture_math.c @@ -195,6 +195,33 @@ static void valuefn(float *out, TexParams *p, bNode *node, bNodeStack **in, shor break; } + case NODE_MATH_FLOOR: + { + *out = floorf(in0); + break; + } + + case NODE_MATH_CEIL: + { + *out = ceilf(in0); + break; + } + + case NODE_MATH_FRACT: + { + *out = in0 - floorf(in0); + break; + } + + case NODE_MATH_SQRT: + { + if (in0 > 0.0f) + *out = sqrtf(in0); + else + *out = 0.0f; + break; + } + default: { BLI_assert(0); diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h index b4c36a7c5162..69a64793ba47 100644 --- a/source/blender/python/BPY_extern.h +++ b/source/blender/python/BPY_extern.h @@ -76,6 +76,7 @@ void BPY_thread_restore(BPy_ThreadStatePtr tstate); bool BPY_execute_filepath(struct bContext *C, const char *filepath, struct ReportList *reports); bool BPY_execute_text(struct bContext *C, struct Text *text, struct ReportList *reports, const bool do_jump); bool BPY_execute_string_as_number(struct bContext *C, const char *expr, const bool verbose, double *r_value); +bool BPY_execute_string_as_intptr(struct bContext *C, const char *expr, const bool verbose, intptr_t *r_value); bool BPY_execute_string_as_string(struct bContext *C, const char *expr, const bool verbose, char **r_value); bool BPY_execute_string_ex(struct bContext *C, const char *expr, bool use_eval); bool BPY_execute_string(struct bContext *C, const char *expr); diff --git a/source/blender/python/bmesh/bmesh_py_types.c b/source/blender/python/bmesh/bmesh_py_types.c index 07c255c4abef..e8474efa31f7 100644 --- a/source/blender/python/bmesh/bmesh_py_types.c +++ b/source/blender/python/bmesh/bmesh_py_types.c @@ -38,6 +38,7 @@ #include "BKE_customdata.h" #include "BKE_DerivedMesh.h" #include "BKE_global.h" +#include "BKE_library.h" #include "bmesh.h" @@ -905,8 +906,9 @@ static PyObject *bpy_bmesh_to_mesh(BPy_BMesh *self, PyObject *args) /* python won't ensure matching uv/mtex */ BM_mesh_cd_validate(bm); + BLI_assert(BKE_id_is_in_gobal_main(&me->id)); BM_mesh_bm_to_me( - G.main, /* XXX UGLY! */ + G_MAIN, /* XXX UGLY! */ bm, me, (&(struct BMeshToMeshParams){ .calc_object_remap = true, @@ -1399,7 +1401,7 @@ static PyObject *bpy_bmvert_copy_from_vert_interp(BPy_BMVert *self, PyObject *ar return NULL; } - BM_data_interp_from_verts(bm, vert_array[0], vert_array[1], self->v, CLAMPIS(fac, 0.0f, 1.0f)); + BM_data_interp_from_verts(bm, vert_array[0], vert_array[1], self->v, clamp_f(fac, 0.0f, 1.0f)); PyMem_FREE(vert_array); Py_RETURN_NONE; diff --git a/source/blender/python/bmesh/bmesh_py_types_customdata.c b/source/blender/python/bmesh/bmesh_py_types_customdata.c index cb95ded4f0db..aee9d6405d0d 100644 --- a/source/blender/python/bmesh/bmesh_py_types_customdata.c +++ b/source/blender/python/bmesh/bmesh_py_types_customdata.c @@ -1136,7 +1136,7 @@ int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObj ret = -1; } else { - *(float *)value = CLAMPIS(tmp_val, 0.0f, 1.0f); + *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f); } break; } @@ -1148,7 +1148,7 @@ int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObj ret = -1; } else { - *(float *)value = CLAMPIS(tmp_val, 0.0f, 1.0f); + *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f); } break; } diff --git a/source/blender/python/bmesh/bmesh_py_types_meshdata.c b/source/blender/python/bmesh/bmesh_py_types_meshdata.c index 7984f625d96b..97e64fd376e3 100644 --- a/source/blender/python/bmesh/bmesh_py_types_meshdata.c +++ b/source/blender/python/bmesh/bmesh_py_types_meshdata.c @@ -38,6 +38,7 @@ #include "DNA_meshdata_types.h" #include "BLI_utildefines.h" +#include "BLI_math_base.h" #include "BLI_math_vector.h" #include "BKE_deform.h" @@ -281,7 +282,7 @@ static int bpy_bmvertskin_radius_set(BPy_BMVertSkin *self, PyObject *value, void } PyDoc_STRVAR(bpy_bmvertskin_flag__use_root_doc, -"Use as root vertex.\n\n:type: boolean" +"Use as root vertex. Setting this flag does not clear other roots in the same mesh island.\n\n:type: boolean" ); PyDoc_STRVAR(bpy_bmvertskin_flag__use_loose_doc, "Use loose vertex.\n\n:type: boolean" @@ -310,17 +311,16 @@ static int bpy_bmvertskin_flag_set(BPy_BMVertSkin *self, PyObject *value, void * } } -/* XXX Todo: Make root settable, currently the code to disable all other verts as roots sits within the modifier */ static PyGetSetDef bpy_bmvertskin_getseters[] = { /* attributes match rna_mesh_gen */ {(char *)"radius", (getter)bpy_bmvertskin_radius_get, (setter)bpy_bmvertskin_radius_set, (char *)bpy_bmvertskin_radius_doc, NULL}, - {(char *)"use_root", (getter)bpy_bmvertskin_flag_get, (setter)NULL, (char *)bpy_bmvertskin_flag__use_root_doc, (void *)MVERT_SKIN_ROOT}, + {(char *)"use_root", (getter)bpy_bmvertskin_flag_get, (setter)bpy_bmvertskin_flag_set, (char *)bpy_bmvertskin_flag__use_root_doc, (void *)MVERT_SKIN_ROOT}, {(char *)"use_loose", (getter)bpy_bmvertskin_flag_get, (setter)bpy_bmvertskin_flag_set, (char *)bpy_bmvertskin_flag__use_loose_doc, (void *)MVERT_SKIN_LOOSE}, {NULL, NULL, NULL, NULL, NULL} /* Sentinel */ }; -static PyTypeObject BPy_BMVertSkin_Type; /* bm.loops.layers.uv.active */ +static PyTypeObject BPy_BMVertSkin_Type; /* bm.loops.layers.skin.active */ static void bm_init_types_bmvertskin(void) { @@ -555,7 +555,7 @@ static int bpy_bmdeformvert_ass_subscript(BPy_BMDeformVert *self, PyObject *key, return -1; } - dw->weight = CLAMPIS(f, 0.0f, 1.0f); + dw->weight = clamp_f(f, 0.0f, 1.0f); } } else { @@ -803,4 +803,3 @@ void BPy_BM_init_types_meshdata(void) bm_init_types_bmdvert(); bm_init_types_bmvertskin(); } - diff --git a/source/blender/python/bmesh/bmesh_py_utils.c b/source/blender/python/bmesh/bmesh_py_utils.c index 224c8295a9b1..ca34de219b83 100644 --- a/source/blender/python/bmesh/bmesh_py_utils.c +++ b/source/blender/python/bmesh/bmesh_py_utils.c @@ -33,6 +33,7 @@ #include #include "BLI_utildefines.h" +#include "BLI_math_base.h" #include "MEM_guardedalloc.h" @@ -159,7 +160,7 @@ static PyObject *bpy_bm_utils_vert_collapse_faces(PyObject *UNUSED(self), PyObje bm = py_edge->bm; - e_new = BM_vert_collapse_faces(bm, py_edge->e, py_vert->v, CLAMPIS(fac, 0.0f, 1.0f), true, do_join_faces, true); + e_new = BM_vert_collapse_faces(bm, py_edge->e, py_vert->v, clamp_f(fac, 0.0f, 1.0f), true, do_join_faces, true); if (e_new) { return BPy_BMEdge_CreatePyObject(bm, e_new); @@ -365,7 +366,7 @@ static PyObject *bpy_bm_utils_edge_split(PyObject *UNUSED(self), PyObject *args) bm = py_edge->bm; - v_new = BM_edge_split(bm, py_edge->e, py_vert->v, &e_new, CLAMPIS(fac, 0.0f, 1.0f)); + v_new = BM_edge_split(bm, py_edge->e, py_vert->v, &e_new, clamp_f(fac, 0.0f, 1.0f)); if (v_new && e_new) { PyObject *ret = PyTuple_New(2); diff --git a/source/blender/python/generic/blf_py_api.c b/source/blender/python/generic/blf_py_api.c index 629335888e48..7d124966334c 100644 --- a/source/blender/python/generic/blf_py_api.c +++ b/source/blender/python/generic/blf_py_api.c @@ -461,6 +461,7 @@ PyObject *BPyInit_blf(void) PyModule_AddIntConstant(submodule, "SHADOW", BLF_SHADOW); PyModule_AddIntConstant(submodule, "KERNING_DEFAULT", BLF_KERNING_DEFAULT); PyModule_AddIntConstant(submodule, "WORD_WRAP", BLF_WORD_WRAP); + PyModule_AddIntConstant(submodule, "MONOCHROME", BLF_MONOCHROME); return submodule; } diff --git a/source/blender/python/generic/bpy_internal_import.c b/source/blender/python/generic/bpy_internal_import.c index fb89d7c9e307..553f7e43e45c 100644 --- a/source/blender/python/generic/bpy_internal_import.c +++ b/source/blender/python/generic/bpy_internal_import.c @@ -185,7 +185,7 @@ PyObject *bpy_text_import_name(const char *name, int *found) Text *text; char txtname[MAX_ID_NAME - 2]; int namelen = strlen(name); -//XXX Main *maggie = bpy_import_main ? bpy_import_main:G.main; +//XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN; Main *maggie = bpy_import_main; *found = 0; @@ -234,7 +234,7 @@ PyObject *bpy_text_reimport(PyObject *module, int *found) Text *text; const char *name; const char *filepath; -//XXX Main *maggie = bpy_import_main ? bpy_import_main:G.main; +//XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN; Main *maggie = bpy_import_main; if (!maggie) { diff --git a/source/blender/python/generic/bpy_internal_import.h b/source/blender/python/generic/bpy_internal_import.h index a184087e3593..29b11fbe8ff8 100644 --- a/source/blender/python/generic/bpy_internal_import.h +++ b/source/blender/python/generic/bpy_internal_import.h @@ -51,7 +51,7 @@ PyObject *bpy_text_reimport(PyObject *module, int *found); void bpy_text_filename_get(char *fn, size_t fn_len, struct Text *text); -/* The game engine has its own Main struct, if this is set search this rather than G.main */ +/* The game engine has its own Main struct, if this is set search this rather than G_MAIN */ struct Main *bpy_import_main_get(void); void bpy_import_main_set(struct Main *maggie); diff --git a/source/blender/python/generic/idprop_py_api.c b/source/blender/python/generic/idprop_py_api.c index 4b56d4412e6c..4d4d52328003 100644 --- a/source/blender/python/generic/idprop_py_api.c +++ b/source/blender/python/generic/idprop_py_api.c @@ -596,15 +596,15 @@ static IDProperty *idp_from_PyMapping(const char *name, PyObject *ob) return prop; } -static IDProperty *idp_from_DatablockPointer(const char *name, PyObject *ob, IDPropertyTemplate *val) +static IDProperty *idp_from_DatablockPointer(const char *name, PyObject *ob) { - pyrna_id_FromPyObject(ob, &val->id); - return IDP_New(IDP_ID, val, name); + IDPropertyTemplate val = {0}; + pyrna_id_FromPyObject(ob, &val.id); + return IDP_New(IDP_ID, &val, name); } static IDProperty *idp_from_PyObject(PyObject *name_obj, PyObject *ob) { - IDPropertyTemplate val = {0}; const char *name = idp_try_read_name(name_obj); if (name == NULL) { return NULL; @@ -626,7 +626,7 @@ static IDProperty *idp_from_PyObject(PyObject *name_obj, PyObject *ob) return idp_from_PySequence(name, ob); } else if (ob == Py_None || pyrna_id_CheckPyObject(ob)) { - return idp_from_DatablockPointer(name, ob, &val); + return idp_from_DatablockPointer(name, ob); } else if (PyMapping_Check(ob)) { return idp_from_PyMapping(name, ob); diff --git a/source/blender/python/generic/imbuf_py_api.c b/source/blender/python/generic/imbuf_py_api.c index 2e32829bf6cb..dfe4007e404c 100644 --- a/source/blender/python/generic/imbuf_py_api.c +++ b/source/blender/python/generic/imbuf_py_api.c @@ -45,6 +45,8 @@ #include #include "BLI_fileops.h" +static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf); + /* -------------------------------------------------------------------- */ /** \name Type & Utilities * \{ */ @@ -109,6 +111,27 @@ static PyObject *py_imbuf_resize(Py_ImBuf *self, PyObject *args, PyObject *kw) Py_RETURN_NONE; } +PyDoc_STRVAR(py_imbuf_copy_doc, +".. method:: copy()\n" +"\n" +" :return: A copy of the image.\n" +" :rtype: :class:`ImBuf`\n" +); +static PyObject *py_imbuf_copy(Py_ImBuf *self) +{ + PY_IMBUF_CHECK_OBJ(self); + return Py_ImBuf_CreatePyObject(self->ibuf); +} + +static PyObject *py_imbuf_deepcopy(Py_ImBuf *self, PyObject *args) +{ + if (!PyC_CheckArgs_DeepCopy(args)) { + return NULL; + } + return py_imbuf_copy(self); +} + + PyDoc_STRVAR(py_imbuf_free_doc, ".. method:: free()\n" "\n" @@ -126,6 +149,9 @@ static PyObject *py_imbuf_free(Py_ImBuf *self) static struct PyMethodDef Py_ImBuf_methods[] = { {"resize", (PyCFunction)py_imbuf_resize, METH_VARARGS | METH_KEYWORDS, (char *)py_imbuf_resize_doc}, {"free", (PyCFunction)py_imbuf_free, METH_NOARGS, (char *)py_imbuf_free_doc}, + {"copy", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc}, + {"__copy__", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc}, + {"__deepcopy__", (PyCFunction)py_imbuf_deepcopy, METH_VARARGS, (char *)py_imbuf_copy_doc}, {NULL, NULL, 0, NULL} }; diff --git a/source/blender/python/generic/imbuf_py_api.h b/source/blender/python/generic/imbuf_py_api.h index 92c1732a9c99..35adc541bfc2 100644 --- a/source/blender/python/generic/imbuf_py_api.h +++ b/source/blender/python/generic/imbuf_py_api.h @@ -27,4 +27,6 @@ PyObject *BPyInit_imbuf(void); +extern PyTypeObject Py_ImBuf_Type; + #endif /* __IMBUF_PY_API_H__ */ diff --git a/source/blender/python/generic/py_capi_utils.c b/source/blender/python/generic/py_capi_utils.c index 226464621638..d8d6b5c7ce7d 100644 --- a/source/blender/python/generic/py_capi_utils.c +++ b/source/blender/python/generic/py_capi_utils.c @@ -91,7 +91,7 @@ int PyC_AsArray_FAST( } } else if (type == &PyBool_Type) { - int *array_bool = array; + bool *array_bool = array; for (i = 0; i < length; i++) { array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0); } @@ -230,6 +230,12 @@ int PyC_ParseBool(PyObject *o, void *p) return 1; } +/* silly function, we dont use arg. just check its compatible with __deepcopy__ */ +int PyC_CheckArgs_DeepCopy(PyObject *args) +{ + PyObject *dummy_pydict; + return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0; +} #ifndef MATH_STANDALONE @@ -778,7 +784,7 @@ bool PyC_IsInterpreterActive(void) } /* Would be nice if python had this built in - * See: http://wiki.blender.org/index.php/Dev:Doc/Tools/Debugging/PyFromC + * See: https://wiki.blender.org/wiki/Tools/Debugging/PyFromC */ void PyC_RunQuicky(const char *filepath, int n, ...) { @@ -1134,6 +1140,40 @@ bool PyC_RunString_AsNumber(const char *expr, const char *filename, double *r_va return ok; } +bool PyC_RunString_AsIntPtr(const char *expr, const char *filename, intptr_t *r_value) +{ + PyObject *py_dict, *retval; + bool ok = true; + PyObject *main_mod = NULL; + + PyC_MainModule_Backup(&main_mod); + + py_dict = PyC_DefaultNameSpace(filename); + + retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict); + + if (retval == NULL) { + ok = false; + } + else { + intptr_t val; + + val = (intptr_t)PyLong_AsVoidPtr(retval); + if (val == 0 && PyErr_Occurred()) { + ok = false; + } + else { + *r_value = val; + } + + Py_DECREF(retval); + } + + PyC_MainModule_Restore(main_mod); + + return ok; +} + bool PyC_RunString_AsString(const char *expr, const char *filename, char **r_value) { PyObject *py_dict, *retval; diff --git a/source/blender/python/generic/py_capi_utils.h b/source/blender/python/generic/py_capi_utils.h index fe7a046d99c6..4c1f14f08daf 100644 --- a/source/blender/python/generic/py_capi_utils.h +++ b/source/blender/python/generic/py_capi_utils.h @@ -102,10 +102,12 @@ int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_val PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag); bool PyC_RunString_AsNumber(const char *expr, const char *filename, double *r_value); +bool PyC_RunString_AsIntPtr(const char *expr, const char *filename, intptr_t *r_value); bool PyC_RunString_AsString(const char *expr, const char *filename, char **r_value); int PyC_ParseBool(PyObject *o, void *p); +int PyC_CheckArgs_DeepCopy(PyObject *args); /* Integer parsing (with overflow checks), -1 on error. */ int PyC_Long_AsBool(PyObject *value); diff --git a/source/blender/python/generic/python_utildefines.h b/source/blender/python/generic/python_utildefines.h index 2d2d19c05f5b..83880d829730 100644 --- a/source/blender/python/generic/python_utildefines.h +++ b/source/blender/python/generic/python_utildefines.h @@ -57,4 +57,3 @@ Py_LOCAL_INLINE(int) PyList_APPEND(PyObject *op, PyObject *v) #endif #endif /* __PYTHON_UTILDEFINES_H__ */ - diff --git a/source/blender/python/intern/bpy.c b/source/blender/python/intern/bpy.c index 89a8f743cea9..d1d91f577a96 100644 --- a/source/blender/python/intern/bpy.c +++ b/source/blender/python/intern/bpy.c @@ -34,7 +34,7 @@ #include "BLI_string.h" #include "BKE_appdir.h" -#include "BKE_global.h" /* XXX, G.main only */ +#include "BKE_global.h" /* XXX, G_MAIN only */ #include "BKE_blender_version.h" #include "BKE_bpath.h" @@ -136,7 +136,7 @@ static PyObject *bpy_blend_paths(PyObject *UNUSED(self), PyObject *args, PyObjec list = PyList_New(0); - BKE_bpath_traverse_main(G.main, bpy_blend_paths_visit_cb, flag, (void *)list); + BKE_bpath_traverse_main(G_MAIN, bpy_blend_paths_visit_cb, flag, (void *)list); return list; } diff --git a/source/blender/python/intern/bpy_app_alembic.h b/source/blender/python/intern/bpy_app_alembic.h index 8cc647a77df1..773bb2fd3bfe 100644 --- a/source/blender/python/intern/bpy_app_alembic.h +++ b/source/blender/python/intern/bpy_app_alembic.h @@ -35,4 +35,3 @@ PyObject *BPY_app_alembic_struct(void); #endif /* __BPY_APP_ALEMBIC_H__ */ - diff --git a/source/blender/python/intern/bpy_app_handlers.c b/source/blender/python/intern/bpy_app_handlers.c index 90aa22de5bfe..ded5ead93aa5 100644 --- a/source/blender/python/intern/bpy_app_handlers.c +++ b/source/blender/python/intern/bpy_app_handlers.c @@ -59,6 +59,10 @@ static PyStructSequence_Field app_cb_info_fields[] = { {(char *)"load_post", (char *)"on loading a new blend file (after)"}, {(char *)"save_pre", (char *)"on saving a blend file (before)"}, {(char *)"save_post", (char *)"on saving a blend file (after)"}, + {(char *)"undo_pre", (char *)"on loading an undo step (before)"}, + {(char *)"undo_post", (char *)"on loading an undo step (after)"}, + {(char *)"redo_pre", (char *)"on loading a redo step (before)"}, + {(char *)"redo_post", (char *)"on loading a redo step (after)"}, {(char *)"scene_update_pre", (char *)"on every scene data update. Does not imply that anything changed in the " "scene, just that the dependency graph is about to be reevaluated, and the " "scene is about to be updated by Blender's animation system."}, diff --git a/source/blender/python/intern/bpy_app_openvdb.h b/source/blender/python/intern/bpy_app_openvdb.h index 12fa54ea7a35..ef7129826959 100644 --- a/source/blender/python/intern/bpy_app_openvdb.h +++ b/source/blender/python/intern/bpy_app_openvdb.h @@ -35,4 +35,3 @@ PyObject *BPY_app_openvdb_struct(void); #endif /* __BPY_APP_OPENVDB_H__ */ - diff --git a/source/blender/python/intern/bpy_app_translations.c b/source/blender/python/intern/bpy_app_translations.c index 6ba858f0228f..ffc54969d8c2 100644 --- a/source/blender/python/intern/bpy_app_translations.c +++ b/source/blender/python/intern/bpy_app_translations.c @@ -824,4 +824,3 @@ void BPY_app_translations_end(void) _clear_translations_cache(); #endif } - diff --git a/source/blender/python/intern/bpy_driver.c b/source/blender/python/intern/bpy_driver.c index 215a64a4449c..e7608e93f58a 100644 --- a/source/blender/python/intern/bpy_driver.c +++ b/source/blender/python/intern/bpy_driver.c @@ -52,9 +52,19 @@ extern void BPY_update_rna_module(void); #define USE_RNA_AS_PYOBJECT +#define USE_BYTECODE_WHITELIST + +#ifdef USE_BYTECODE_WHITELIST +# include +#endif + /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */ PyObject *bpy_pydriver_Dict = NULL; +#ifdef USE_BYTECODE_WHITELIST +static PyObject *bpy_pydriver_Dict__whitelist = NULL; +#endif + /* For faster execution we keep a special dictionary for pydrivers, with * the needed modules and aliases. */ @@ -79,6 +89,9 @@ int bpy_pydriver_create_dict(void) PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */ Py_DECREF(mod); } +#ifdef USE_BYTECODE_WHITELIST + PyObject *mod_math = mod; +#endif /* add bpy to global namespace */ mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0); @@ -95,6 +108,48 @@ int bpy_pydriver_create_dict(void) Py_DECREF(mod); } +#ifdef USE_BYTECODE_WHITELIST + /* setup the whitelist */ + { + bpy_pydriver_Dict__whitelist = PyDict_New(); + const char *whitelist[] = { + /* builtins (basic) */ + "all", + "any", + "len", + /* builtins (numeric) */ + "max", + "min", + "pow", + "round", + "sum", + /* types */ + "bool", + "float", + "int", + + NULL, + }; + + for (int i = 0; whitelist[i]; i++) { + PyDict_SetItemString(bpy_pydriver_Dict__whitelist, whitelist[i], Py_None); + } + + /* Add all of 'math' functions. */ + if (mod_math != NULL) { + PyObject *mod_math_dict = PyModule_GetDict(mod_math); + PyObject *arg_key, *arg_value; + Py_ssize_t arg_pos = 0; + while (PyDict_Next(mod_math_dict, &arg_pos, &arg_key, &arg_value)) { + const char *arg_str = _PyUnicode_AsString(arg_key); + if (arg_str[0] && arg_str[1] != '_') { + PyDict_SetItem(bpy_pydriver_Dict__whitelist, arg_key, Py_None); + } + } + } + } +#endif /* USE_BYTECODE_WHITELIST */ + return 0; } @@ -163,6 +218,14 @@ void BPY_driver_reset(void) bpy_pydriver_Dict = NULL; } +#ifdef USE_BYTECODE_WHITELIST + if (bpy_pydriver_Dict__whitelist) { + PyDict_Clear(bpy_pydriver_Dict__whitelist); + Py_DECREF(bpy_pydriver_Dict__whitelist); + bpy_pydriver_Dict__whitelist = NULL; + } +#endif + g_pydriver_state_prev.evaltime = FLT_MAX; /* freed when clearing driver dict */ @@ -185,6 +248,128 @@ static void pydriver_error(ChannelDriver *driver) PyErr_Clear(); } +#ifdef USE_BYTECODE_WHITELIST + +#define OK_OP(op) [op] = 1 + +static const char secure_opcodes[255] = { + OK_OP(POP_TOP), + OK_OP(ROT_TWO), + OK_OP(ROT_THREE), + OK_OP(DUP_TOP), + OK_OP(DUP_TOP_TWO), + OK_OP(NOP), + OK_OP(UNARY_POSITIVE), + OK_OP(UNARY_NEGATIVE), + OK_OP(UNARY_NOT), + OK_OP(UNARY_INVERT), + OK_OP(BINARY_MATRIX_MULTIPLY), + OK_OP(INPLACE_MATRIX_MULTIPLY), + OK_OP(BINARY_POWER), + OK_OP(BINARY_MULTIPLY), + OK_OP(BINARY_MODULO), + OK_OP(BINARY_ADD), + OK_OP(BINARY_SUBTRACT), + OK_OP(BINARY_SUBSCR), + OK_OP(BINARY_FLOOR_DIVIDE), + OK_OP(BINARY_TRUE_DIVIDE), + OK_OP(INPLACE_FLOOR_DIVIDE), + OK_OP(INPLACE_TRUE_DIVIDE), + OK_OP(INPLACE_ADD), + OK_OP(INPLACE_SUBTRACT), + OK_OP(INPLACE_MULTIPLY), + OK_OP(INPLACE_MODULO), + OK_OP(BINARY_LSHIFT), + OK_OP(BINARY_RSHIFT), + OK_OP(BINARY_AND), + OK_OP(BINARY_XOR), + OK_OP(BINARY_OR), + OK_OP(INPLACE_POWER), + OK_OP(INPLACE_LSHIFT), + OK_OP(INPLACE_RSHIFT), + OK_OP(INPLACE_AND), + OK_OP(INPLACE_XOR), + OK_OP(INPLACE_OR), + OK_OP(RETURN_VALUE), + OK_OP(BUILD_TUPLE), + OK_OP(BUILD_LIST), + OK_OP(BUILD_SET), + OK_OP(BUILD_MAP), + OK_OP(COMPARE_OP), + OK_OP(JUMP_FORWARD), + OK_OP(JUMP_IF_FALSE_OR_POP), + OK_OP(JUMP_IF_TRUE_OR_POP), + OK_OP(JUMP_ABSOLUTE), + OK_OP(POP_JUMP_IF_FALSE), + OK_OP(POP_JUMP_IF_TRUE), + OK_OP(LOAD_GLOBAL), + OK_OP(LOAD_FAST), + OK_OP(STORE_FAST), + OK_OP(DELETE_FAST), + OK_OP(LOAD_DEREF), + OK_OP(STORE_DEREF), + + /* special cases */ + OK_OP(LOAD_CONST), /* ok because constants are accepted */ + OK_OP(LOAD_NAME), /* ok, because PyCodeObject.names is checked */ + OK_OP(CALL_FUNCTION), /* ok, because we check its 'name' before calling */ + OK_OP(CALL_FUNCTION_KW), + OK_OP(CALL_FUNCTION_EX), +}; + +#undef OK_OP + +static bool bpy_driver_secure_bytecode_validate(PyObject *expr_code, PyObject *dict_arr[]) +{ + PyCodeObject *py_code = (PyCodeObject *)expr_code; + + /* Check names. */ + { + for (int i = 0; i < PyTuple_GET_SIZE(py_code->co_names); i++) { + PyObject *name = PyTuple_GET_ITEM(py_code->co_names, i); + + bool contains_name = false; + for (int j = 0; dict_arr[j]; j++) { + if (PyDict_Contains(dict_arr[j], name)) { + contains_name = true; + break; + } + } + + if (contains_name == false) { + fprintf(stderr, "\tBPY_driver_eval() - restructed access disallows name '%s', " + "enable auto-execution to support\n", _PyUnicode_AsString(name)); + return false; + } + } + } + + /* Check opcodes. */ + { + const _Py_CODEUNIT *codestr; + Py_ssize_t code_len; + + PyBytes_AsStringAndSize(py_code->co_code, (char **)&codestr, &code_len); + code_len /= sizeof(*codestr); + + for (Py_ssize_t i = 0; i < code_len; i++) { + const int opcode = _Py_OPCODE(codestr[i]); + if (secure_opcodes[opcode] == 0) { + fprintf(stderr, "\tBPY_driver_eval() - restructed access disallows opcode '%d', " + "enable auto-execution to support\n", opcode); + return false; + } + } + +#undef CODESIZE + } + + return true; +} + +#endif /* USE_BYTECODE_WHITELIST */ + + /* This evals py driver expressions, 'expr' is a Python expression that * should evaluate to a float number, which is returned. * @@ -217,6 +402,7 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c if (expr[0] == '\0') return 0.0f; +#ifndef USE_BYTECODE_WHITELIST if (!(G.f & G_SCRIPT_AUTOEXEC)) { if (!(G.f & G_SCRIPT_AUTOEXEC_FAIL_QUIET)) { G.f |= G_SCRIPT_AUTOEXEC_FAIL; @@ -226,6 +412,9 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c } return 0.0f; } +#else + bool is_recompile = false; +#endif use_gil = true; /* !PyC_IsInterpreterActive(); */ @@ -269,6 +458,9 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c driver->flag &= ~DRIVER_FLAG_RECOMPILE; driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */ +#ifdef USE_BYTECODE_WHITELIST + is_recompile = true; +#endif } else { expr_code = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 0); @@ -350,6 +542,24 @@ float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, c } } +#ifdef USE_BYTECODE_WHITELIST + if (is_recompile) { + if (!(G.f & G_SCRIPT_AUTOEXEC)) { + if (!bpy_driver_secure_bytecode_validate( + expr_code, (PyObject *[]){ + bpy_pydriver_Dict, + bpy_pydriver_Dict__whitelist, + driver_vars, + NULL,} + )) + { + Py_DECREF(expr_code); + expr_code = NULL; + PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, NULL); + } + } + } +#endif /* USE_BYTECODE_WHITELIST */ #if 0 /* slow, with this can avoid all Py_CompileString above. */ /* execute expression to get a value */ diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c index 2332a5fe7ae0..3403fef9752f 100644 --- a/source/blender/python/intern/bpy_interface.c +++ b/source/blender/python/intern/bpy_interface.c @@ -628,13 +628,10 @@ bool BPY_execute_string_as_number(bContext *C, const char *expr, const bool verb */ bool BPY_execute_string_as_string(bContext *C, const char *expr, const bool verbose, char **r_value) { + BLI_assert(r_value && expr); PyGILState_STATE gilstate; bool ok = true; - if (!r_value || !expr) { - return -1; - } - if (expr[0] == '\0') { *r_value = NULL; return ok; @@ -658,17 +655,49 @@ bool BPY_execute_string_as_string(bContext *C, const char *expr, const bool verb return ok; } +/** + * Support both int and pointers. + * + * \return success + */ +bool BPY_execute_string_as_intptr(bContext *C, const char *expr, const bool verbose, intptr_t *r_value) +{ + BLI_assert(r_value && expr); + PyGILState_STATE gilstate; + bool ok = true; + + if (expr[0] == '\0') { + *r_value = 0; + return ok; + } + + bpy_context_set(C, &gilstate); + + ok = PyC_RunString_AsIntPtr(expr, "", r_value); + + if (ok == false) { + if (verbose) { + BPy_errors_to_report_ex(CTX_wm_reports(C), false, false); + } + else { + PyErr_Clear(); + } + } + + bpy_context_clear(C, &gilstate); + + return ok; +} bool BPY_execute_string_ex(bContext *C, const char *expr, bool use_eval) { + BLI_assert(expr); PyGILState_STATE gilstate; PyObject *main_mod = NULL; PyObject *py_dict, *retval; bool ok = true; Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */ - if (!expr) return -1; - if (expr[0] == '\0') { return ok; } @@ -726,7 +755,7 @@ void BPY_modules_load_user(bContext *C) bpy_context_set(C, &gilstate); for (text = bmain->text.first; text; text = text->id.next) { - if (text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name + 2, ".py")) { + if (text->flags & TXT_ISSCRIPT && BLI_path_extension_check(text->id.name + 2, ".py")) { if (!(G.f & G_SCRIPT_AUTOEXEC)) { if (!(G.f & G_SCRIPT_AUTOEXEC_FAIL_QUIET)) { G.f |= G_SCRIPT_AUTOEXEC_FAIL; diff --git a/source/blender/python/intern/bpy_library_write.c b/source/blender/python/intern/bpy_library_write.c index ead10efb212b..76b7ccf72fab 100644 --- a/source/blender/python/intern/bpy_library_write.c +++ b/source/blender/python/intern/bpy_library_write.c @@ -95,7 +95,7 @@ static PyObject *bpy_lib_write(PyObject *UNUSED(self), PyObject *args, PyObject return NULL; } - Main *bmain_src = G.main; + Main *bmain_src = G_MAIN; int write_flags = 0; if (use_relative_remap) { diff --git a/source/blender/python/intern/bpy_operator_wrap.c b/source/blender/python/intern/bpy_operator_wrap.c index 9d57adca9465..ae84d83b4315 100644 --- a/source/blender/python/intern/bpy_operator_wrap.c +++ b/source/blender/python/intern/bpy_operator_wrap.c @@ -200,4 +200,3 @@ PyObject *PYOP_wrap_macro_define(PyObject *UNUSED(self), PyObject *args) return pyrna_struct_CreatePyObject(&ptr_otmacro); } - diff --git a/source/blender/python/intern/bpy_path.c b/source/blender/python/intern/bpy_path.c index 1d554b60bbe8..f182972ba9c7 100644 --- a/source/blender/python/intern/bpy_path.c +++ b/source/blender/python/intern/bpy_path.c @@ -64,4 +64,3 @@ PyObject *BPyInit__bpy_path(void) return submodule; } - diff --git a/source/blender/python/intern/bpy_props.c b/source/blender/python/intern/bpy_props.c index d0b0331430d7..0db2fc189c14 100644 --- a/source/blender/python/intern/bpy_props.c +++ b/source/blender/python/intern/bpy_props.c @@ -133,6 +133,7 @@ static const EnumPropertyItem property_subtype_array_items[] = { {PROP_XYZ, "XYZ", 0, "XYZ", ""}, {PROP_COLOR_GAMMA, "COLOR_GAMMA", 0, "Color Gamma", ""}, {PROP_LAYER, "LAYER", 0, "Layer", ""}, + {PROP_LAYER_MEMBER, "LAYER_MEMBER", 0, "Layer Member", ""}, {PROP_NONE, "NONE", 0, "None", ""}, {0, NULL, 0, NULL, NULL}}; @@ -140,7 +141,7 @@ static const EnumPropertyItem property_subtype_array_items[] = { #define BPY_PROPDEF_SUBTYPE_ARRAY_DOC \ " :arg subtype: Enumerator in ['COLOR', 'TRANSLATION', 'DIRECTION', " \ "'VELOCITY', 'ACCELERATION', 'MATRIX', 'EULER', 'QUATERNION', 'AXISANGLE', " \ - "'XYZ', 'COLOR_GAMMA', 'LAYER', 'NONE'].\n" \ + "'XYZ', 'COLOR_GAMMA', 'LAYER', 'LAYER_MEMBER', 'NONE'].\n" \ " :type subtype: string\n" /* PyObject's */ @@ -263,7 +264,7 @@ static void bpy_prop_update_cb(struct bContext *C, struct PointerRNA *ptr, struc } } -static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop) +static bool bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop) { PyObject **py_data = RNA_property_py_data_get(prop); PyObject *py_func; @@ -273,7 +274,7 @@ static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p PyGILState_STATE gilstate; bool use_gil; const bool is_write_ok = pyrna_write_check(); - int value; + bool value; BLI_assert(py_data != NULL); @@ -301,12 +302,15 @@ static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p value = false; } else { - value = PyC_Long_AsI32(ret); + int value_i = PyC_Long_AsBool(ret); - if (value == -1 && PyErr_Occurred()) { + if (value_i == -1 && PyErr_Occurred()) { PyC_Err_PrintWithFunc(py_func); value = false; } + else { + value = (bool)value_i; + } Py_DECREF(ret); } @@ -321,7 +325,7 @@ static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p return value; } -static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value) +static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, bool value) { PyObject **py_data = RNA_property_py_data_get(prop); PyObject *py_func; @@ -375,7 +379,7 @@ static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA * } } -static int bpy_prop_poll_cb(struct PointerRNA *self, PointerRNA candidate, struct PropertyRNA *prop) +static bool bpy_prop_poll_cb(struct PointerRNA *self, PointerRNA candidate, struct PropertyRNA *prop) { PyObject *py_self; PyObject *py_candidate; @@ -420,7 +424,7 @@ static int bpy_prop_poll_cb(struct PointerRNA *self, PointerRNA candidate, struc return result; } -static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values) +static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, bool *values) { PyObject **py_data = RNA_property_py_data_get(prop); PyObject *py_func; @@ -481,7 +485,7 @@ static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct Propert } } -static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values) +static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const bool *values) { PyObject **py_data = RNA_property_py_data_get(prop); PyObject *py_func; @@ -511,7 +515,7 @@ static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct Propert self = pyrna_struct_as_instance(ptr); PyTuple_SET_ITEM(args, 0, self); - py_values = PyC_Tuple_PackArray_I32FromBool(values, len); + py_values = PyC_Tuple_PackArray_Bool(values, len); PyTuple_SET_ITEM(args, 1, py_values); ret = PyObject_CallObject(py_func, args); @@ -1900,7 +1904,7 @@ static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop, PyObject *ge " :type description: string\n" \ #define BPY_PROPDEF_UNIT_DOC \ -" :arg unit: Enumerator in ['NONE', 'LENGTH', 'AREA', 'VOLUME', 'ROTATION', 'TIME', 'VELOCITY', 'ACCELERATION'].\n" \ +" :arg unit: Enumerator in ['NONE', 'LENGTH', 'AREA', 'VOLUME', 'ROTATION', 'TIME', 'VELOCITY', 'ACCELERATION', 'MASS', 'CAMERA'].\n" \ " :type unit: string\n" \ #define BPY_PROPDEF_NUM_MIN_DOC \ @@ -2097,7 +2101,7 @@ static PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject if (srna) { const char *id = NULL, *name = NULL, *description = ""; int id_len; - int def[PYRNA_STACK_ARRAY] = {0}; + bool def[PYRNA_STACK_ARRAY] = {0}; int size = 3; PropertyRNA *prop; PyObject *pydef = NULL; diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c index 30ab2049b787..28a6a4f7fb01 100644 --- a/source/blender/python/intern/bpy_rna.c +++ b/source/blender/python/intern/bpy_rna.c @@ -1667,7 +1667,7 @@ static int pyrna_py_to_prop( return -1; } else { - if (data) *((int *)data) = param; + if (data) *((bool *)data) = param; else RNA_property_boolean_set(ptr, prop, param); } break; @@ -2477,9 +2477,9 @@ static PyObject *pyrna_prop_array_subscript_slice( } case PROP_BOOLEAN: { - int values_stack[PYRNA_STACK_ARRAY]; - int *values; - if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); } + bool values_stack[PYRNA_STACK_ARRAY]; + bool *values; + if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(bool) * length); } else { values = values_stack; } RNA_property_boolean_get_array(ptr, prop, values); @@ -2860,7 +2860,7 @@ static int prop_subscript_ass_array_slice__int_recursive( } static int prop_subscript_ass_array_slice__bool_recursive( - PyObject **value_items, int *value, + PyObject **value_items, bool *value, int totdim, const int dimsize[]) { const int length = dimsize[0]; @@ -2983,9 +2983,9 @@ static int prop_subscript_ass_array_slice( } case PROP_BOOLEAN: { - int values_stack[PYRNA_STACK_ARRAY]; - int *values = (length_flat > PYRNA_STACK_ARRAY) ? - (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) : values_stack; + bool values_stack[PYRNA_STACK_ARRAY]; + bool *values = (length_flat > PYRNA_STACK_ARRAY) ? + (values_alloc = PyMem_MALLOC(sizeof(bool) * length_flat)) : values_stack; if (start != 0 || stop != length) { /* partial assignment? - need to get the array */ @@ -4915,6 +4915,8 @@ static bool foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, con case PROP_RAW_INT: if (attr_signed) return (f == 'i') ? 1 : 0; else return (f == 'I') ? 1 : 0; + case PROP_RAW_BOOLEAN: + return (f == '?') ? 1 : 0; case PROP_RAW_FLOAT: return (f == 'f') ? 1 : 0; case PROP_RAW_DOUBLE: @@ -4981,6 +4983,9 @@ static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set) case PROP_RAW_INT: ((int *)array)[i] = (int)PyLong_AsLong(item); break; + case PROP_RAW_BOOLEAN: + ((bool *)array)[i] = (int)PyLong_AsLong(item) != 0; + break; case PROP_RAW_FLOAT: ((float *)array)[i] = (float)PyFloat_AsDouble(item); break; @@ -5042,6 +5047,9 @@ static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set) case PROP_RAW_DOUBLE: item = PyFloat_FromDouble((double) ((double *)array)[i]); break; + case PROP_RAW_BOOLEAN: + item = PyBool_FromLong((long) ((bool *)array)[i]); + break; default: /* PROP_RAW_UNSET */ /* should never happen */ BLI_assert(!"Invalid array type - get"); @@ -5313,7 +5321,7 @@ static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *dat case PROP_BOOLEAN: ret = PyTuple_New(len); for (a = 0; a < len; a++) - PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((int *)data)[a])); + PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((bool *)data)[a])); break; case PROP_INT: ret = PyTuple_New(len); @@ -5356,7 +5364,7 @@ static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *dat /* see if we can coerce into a python type - PropertyType */ switch (type) { case PROP_BOOLEAN: - ret = PyBool_FromLong(*(int *)data); + ret = PyBool_FromLong(*(bool *)data); break; case PROP_INT: ret = PyLong_FromLong(*(int *)data); @@ -7017,7 +7025,7 @@ PyObject *BPY_rna_module(void) PointerRNA ptr; /* for now, return the base RNA type rather than a real module */ - RNA_main_pointer_create(G.main, &ptr); + RNA_main_pointer_create(G_MAIN, &ptr); pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr); rna_module_ptr = &pyrna->ptr; @@ -7028,9 +7036,9 @@ void BPY_update_rna_module(void) { if (rna_module_ptr) { #if 0 - RNA_main_pointer_create(G.main, rna_module_ptr); + RNA_main_pointer_create(G_MAIN, rna_module_ptr); #else - rna_module_ptr->data = G.main; /* just set data is enough */ + rna_module_ptr->data = G_MAIN; /* just set data is enough */ #endif } } @@ -7572,10 +7580,12 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v if (!(flag & PROP_REGISTER)) continue; + /* TODO(campbell): Use Python3.7x _PyObject_LookupAttr(), also in the macro below. */ identifier = RNA_property_identifier(prop); item = PyObject_GetAttrString(py_class, identifier); if (item == NULL) { + PyErr_Clear(); /* Sneaky workaround to use the class name as the bl_idname */ #define BPY_REPLACEMENT_STRING(rna_attr, py_attr) \ @@ -7591,6 +7601,9 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v } \ Py_DECREF(item); \ } \ + else { \ + PyErr_Clear(); \ + } \ } /* intentionally allow else here */ if (false) {} /* needed for macro */ diff --git a/source/blender/python/intern/bpy_rna_anim.c b/source/blender/python/intern/bpy_rna_anim.c index 3eec87593dc1..73809e965608 100644 --- a/source/blender/python/intern/bpy_rna_anim.c +++ b/source/blender/python/intern/bpy_rna_anim.c @@ -45,6 +45,7 @@ #include "BKE_fcurve.h" #include "BKE_global.h" #include "BKE_idcode.h" +#include "BKE_library.h" #include "BKE_report.h" #include "RNA_access.h" @@ -266,12 +267,14 @@ PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyOb return PyBool_FromLong(result); } else { + ID *id = self->ptr.id.data; ReportList reports; short result; BKE_reports_init(&reports, RPT_STORE); - result = insert_keyframe(G.main, &reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, keytype, options); + BLI_assert(BKE_id_is_in_gobal_main(id)); + result = insert_keyframe(G_MAIN, &reports, id, NULL, group_name, path_full, index, cfra, keytype, options); MEM_freeN((void *)path_full); if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) diff --git a/source/blender/python/intern/bpy_rna_array.c b/source/blender/python/intern/bpy_rna_array.c index 571ee0edea2c..9a184df80545 100644 --- a/source/blender/python/intern/bpy_rna_array.c +++ b/source/blender/python/intern/bpy_rna_array.c @@ -564,7 +564,7 @@ static void py_to_int(const struct ItemConvertArgData *arg, PyObject *py, char * static void py_to_bool(const struct ItemConvertArgData *UNUSED(arg), PyObject *py, char *data) { - *(int *)data = (int)PyObject_IsTrue(py); + *(bool *)data = (bool)PyObject_IsTrue(py); } static int py_float_check(PyObject *py) @@ -596,7 +596,7 @@ static void int_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, void *v static void bool_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, void *value) { - RNA_property_boolean_set_index(ptr, prop, index, *(int *)value); + RNA_property_boolean_set_index(ptr, prop, index, *(bool *)value); } static void convert_item_init_float( @@ -655,7 +655,7 @@ int pyrna_py_to_array(PointerRNA *ptr, PropertyRNA *prop, char *param_data, convert_item_init_bool(ptr, prop, &convert_item); ret = py_to_array( - py, ptr, prop, param_data, py_bool_check, "boolean", sizeof(int), + py, ptr, prop, param_data, py_bool_check, "boolean", sizeof(bool), &convert_item, (RNA_SetArrayFunc)RNA_property_boolean_set_array, error_prefix); break; } @@ -885,10 +885,9 @@ int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value) } break; } - case PROP_BOOLEAN: case PROP_INT: { - int value_i = PyLong_AsLong(value); + int value_i = PyC_Long_AsI32(value); if (value_i == -1 && PyErr_Occurred()) { PyErr_Clear(); return 0; @@ -904,10 +903,40 @@ int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value) tmp_arr = tmp; } - if (type == PROP_BOOLEAN) - RNA_property_boolean_get_array(ptr, prop, tmp_arr); - else - RNA_property_int_get_array(ptr, prop, tmp_arr); + RNA_property_int_get_array(ptr, prop, tmp_arr); + + for (i = 0; i < len; i++) { + if (tmp_arr[i] == value_i) { + break; + } + } + + if (tmp_arr != tmp) + PyMem_FREE(tmp_arr); + + return i < len ? 1 : 0; + } + break; + } + case PROP_BOOLEAN: + { + int value_i = PyC_Long_AsBool(value); + if (value_i == -1 && PyErr_Occurred()) { + PyErr_Clear(); + return 0; + } + else { + bool tmp[32]; + bool *tmp_arr; + + if (len * sizeof(bool) > sizeof(tmp)) { + tmp_arr = PyMem_MALLOC(len * sizeof(bool)); + } + else { + tmp_arr = tmp; + } + + RNA_property_boolean_get_array(ptr, prop, tmp_arr); for (i = 0; i < len; i++) { if (tmp_arr[i] == value_i) { diff --git a/source/blender/python/intern/bpy_rna_id_collection.c b/source/blender/python/intern/bpy_rna_id_collection.c index ee40d30d73bd..4806c2266ba3 100644 --- a/source/blender/python/intern/bpy_rna_id_collection.c +++ b/source/blender/python/intern/bpy_rna_id_collection.c @@ -160,7 +160,7 @@ static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject * BPy_StructRNA *pyrna = (BPy_StructRNA *)self; Main *bmain = pyrna->ptr.data; #else - Main *bmain = G.main; /* XXX Ugly, but should work! */ + Main *bmain = G_MAIN; /* XXX Ugly, but should work! */ #endif PyObject *subset = NULL; @@ -230,7 +230,6 @@ static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject * lb_index = set_listbasepointers(bmain, lb_array); while (lb_index--) { - if (val_types_bitmap && lb_array[lb_index]->first) { if (!id_check_type(lb_array[lb_index]->first, val_types_bitmap)) { continue; diff --git a/source/blender/python/intern/gpu.c b/source/blender/python/intern/gpu.c index eeec65cc202f..d99dd6c2ea9f 100644 --- a/source/blender/python/intern/gpu.c +++ b/source/blender/python/intern/gpu.c @@ -359,4 +359,3 @@ PyObject *GPU_initPython(void) PyDict_SetItem(PyImport_GetModuleDict(), PyModule_GetNameObject(module), module); return module; } - diff --git a/source/blender/python/intern/gpu_offscreen.c b/source/blender/python/intern/gpu_offscreen.c index 412e9ba1c82b..c7c106757b15 100644 --- a/source/blender/python/intern/gpu_offscreen.c +++ b/source/blender/python/intern/gpu_offscreen.c @@ -36,6 +36,7 @@ #include "WM_types.h" #include "BKE_global.h" +#include "BKE_library.h" #include "ED_screen.h" @@ -169,7 +170,7 @@ static PyObject *pygpu_offscreen_draw_view3d(BPy_GPUOffScreen *self, PyObject *a MatrixObject *py_mat_modelview, *py_mat_projection; PyObject *py_scene, *py_region, *py_view3d; - struct Main *bmain = G.main; /* XXX UGLY! */ + struct Main *bmain = G_MAIN; /* XXX UGLY! */ Scene *scene; View3D *v3d; ARegion *ar; @@ -191,6 +192,8 @@ static PyObject *pygpu_offscreen_draw_view3d(BPy_GPUOffScreen *self, PyObject *a return NULL; } + BLI_assert(BKE_id_is_in_gobal_main(&scene->id)); + fx = GPU_fx_compositor_create(); fx_settings = v3d->fx_settings; /* full copy */ diff --git a/source/blender/python/mathutils/mathutils.c b/source/blender/python/mathutils/mathutils.c index 5dddf0c760f6..ec2ccd31d0f6 100644 --- a/source/blender/python/mathutils/mathutils.c +++ b/source/blender/python/mathutils/mathutils.c @@ -419,13 +419,6 @@ PyObject *mathutils_dynstr_to_py(struct DynStr *ds) } #endif -/* silly function, we dont use arg. just check its compatible with __deepcopy__ */ -int mathutils_deepcopy_args_check(PyObject *args) -{ - PyObject *dummy_pydict; - return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0; -} - /* Mathutils Callbacks */ /* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */ diff --git a/source/blender/python/mathutils/mathutils.h b/source/blender/python/mathutils/mathutils.h index ec927a9e3161..b151ba7280dc 100644 --- a/source/blender/python/mathutils/mathutils.h +++ b/source/blender/python/mathutils/mathutils.h @@ -174,6 +174,4 @@ int column_vector_multiplication(float rvec[4], VectorObject *vec, MatrixObject PyObject *mathutils_dynstr_to_py(struct DynStr *ds); #endif -int mathutils_deepcopy_args_check(PyObject *args); - #endif /* __MATHUTILS_H__ */ diff --git a/source/blender/python/mathutils/mathutils_Color.c b/source/blender/python/mathutils/mathutils_Color.c index 9997cd9c1f58..4c1163a61813 100644 --- a/source/blender/python/mathutils/mathutils_Color.c +++ b/source/blender/python/mathutils/mathutils_Color.c @@ -33,6 +33,7 @@ #include "BLI_utildefines.h" #include "../generic/python_utildefines.h" +#include "../generic/py_capi_utils.h" #ifndef MATH_STANDALONE # include "BLI_dynstr.h" @@ -113,8 +114,9 @@ static PyObject *Color_copy(ColorObject *self) } static PyObject *Color_deepcopy(ColorObject *self, PyObject *args) { - if (!mathutils_deepcopy_args_check(args)) + if (!PyC_CheckArgs_DeepCopy(args)) { return NULL; + } return Color_copy(self); } diff --git a/source/blender/python/mathutils/mathutils_Euler.c b/source/blender/python/mathutils/mathutils_Euler.c index 026384743bd7..8be3de422263 100644 --- a/source/blender/python/mathutils/mathutils_Euler.c +++ b/source/blender/python/mathutils/mathutils_Euler.c @@ -32,6 +32,7 @@ #include "BLI_math.h" #include "BLI_utildefines.h" #include "../generic/python_utildefines.h" +#include "../generic/py_capi_utils.h" #ifndef MATH_STANDALONE # include "BLI_dynstr.h" @@ -312,8 +313,9 @@ static PyObject *Euler_copy(EulerObject *self) } static PyObject *Euler_deepcopy(EulerObject *self, PyObject *args) { - if (!mathutils_deepcopy_args_check(args)) + if (!PyC_CheckArgs_DeepCopy(args)) { return NULL; + } return Euler_copy(self); } diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c index cc6a53678956..70c400f99b8d 100644 --- a/source/blender/python/mathutils/mathutils_Matrix.c +++ b/source/blender/python/mathutils/mathutils_Matrix.c @@ -33,6 +33,7 @@ #include "BLI_utildefines.h" #include "../generic/python_utildefines.h" +#include "../generic/py_capi_utils.h" #ifndef MATH_STANDALONE # include "BLI_string.h" @@ -1945,8 +1946,9 @@ static PyObject *Matrix_copy(MatrixObject *self) } static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args) { - if (!mathutils_deepcopy_args_check(args)) + if (!PyC_CheckArgs_DeepCopy(args)) { return NULL; + } return Matrix_copy(self); } diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c index d283c717a46f..48c18dd20c14 100644 --- a/source/blender/python/mathutils/mathutils_Quaternion.c +++ b/source/blender/python/mathutils/mathutils_Quaternion.c @@ -33,6 +33,7 @@ #include "BLI_utildefines.h" #include "../generic/python_utildefines.h" +#include "../generic/py_capi_utils.h" #ifndef MATH_STANDALONE # include "BLI_dynstr.h" @@ -496,8 +497,9 @@ static PyObject *Quaternion_copy(QuaternionObject *self) } static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args) { - if (!mathutils_deepcopy_args_check(args)) + if (!PyC_CheckArgs_DeepCopy(args)) { return NULL; + } return Quaternion_copy(self); } @@ -1098,7 +1100,8 @@ static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kw { PyObject *seq = NULL; double angle = 0.0f; - float quat[QUAT_SIZE] = {0.0f, 0.0f, 0.0f, 0.0f}; + float quat[QUAT_SIZE]; + unit_qt(quat); if (kwds && PyDict_Size(kwds)) { PyErr_SetString(PyExc_TypeError, @@ -1393,4 +1396,3 @@ PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user, return (PyObject *)self; } - diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c index 65450505e083..6a40f22d9dfd 100644 --- a/source/blender/python/mathutils/mathutils_Vector.c +++ b/source/blender/python/mathutils/mathutils_Vector.c @@ -1127,23 +1127,17 @@ PyDoc_STRVAR(Vector_project_doc, static PyObject *Vector_project(VectorObject *self, PyObject *value) { const int size = self->size; - float tvec[MAX_DIMENSIONS]; - float vec[MAX_DIMENSIONS]; + float *tvec; double dot = 0.0f, dot2 = 0.0f; int x; - if (mathutils_array_parse(tvec, size, size, value, "Vector.project(other), invalid 'other' arg") == -1) + if (BaseMath_ReadCallback(self) == -1) return NULL; - if (self->size > 4) { - PyErr_SetString(PyExc_ValueError, - "Vector must be 2D, 3D or 4D"); + if (mathutils_array_parse_alloc(&tvec, size, value, "Vector.project(other), invalid 'other' arg") == -1) { return NULL; } - if (BaseMath_ReadCallback(self) == -1) - return NULL; - /* get dot products */ for (x = 0; x < size; x++) { dot += (double)(self->vec[x] * tvec[x]); @@ -1152,9 +1146,9 @@ static PyObject *Vector_project(VectorObject *self, PyObject *value) /* projection */ dot /= dot2; for (x = 0; x < size; x++) { - vec[x] = (float)dot * tvec[x]; + tvec[x] *= (float)dot; } - return Vector_CreatePyObject(vec, size, Py_TYPE(self)); + return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self)); } PyDoc_STRVAR(Vector_lerp_doc, @@ -1331,8 +1325,9 @@ static PyObject *Vector_copy(VectorObject *self) } static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args) { - if (!mathutils_deepcopy_args_check(args)) + if (!PyC_CheckArgs_DeepCopy(args)) { return NULL; + } return Vector_copy(self); } diff --git a/source/blender/python/rna_dump.py b/source/blender/python/rna_dump.py index 7259ceb67a0c..3c09175910e8 100644 --- a/source/blender/python/rna_dump.py +++ b/source/blender/python/rna_dump.py @@ -129,6 +129,7 @@ def seek(r, txt, recurs): newtxt = txt + '[' + str(i) + ']' seek(r[i], newtxt, recurs + 1) + seek(bpy.data, 'bpy.data', 0) # seek(bpy.types, 'bpy.types', 0) ''' @@ -140,8 +141,8 @@ def seek(r, txt, recurs): seek(r, 'bpy.types.' + d + '.bl_rna', 0) ''' -#print dir(bpy) +# print dir(bpy) #import sys -#sys.exit() +# sys.exit() print("iter over ", seek_count, "rna items") diff --git a/source/blender/python/simple_enum_gen.py b/source/blender/python/simple_enum_gen.py index 7e54f3dbb41b..4f3159b9b257 100644 --- a/source/blender/python/simple_enum_gen.py +++ b/source/blender/python/simple_enum_gen.py @@ -1,22 +1,22 @@ - # ***** BEGIN GPL LICENSE BLOCK ***** - # - # This program is free software; you can redistribute it and/or - # modify it under the terms of the GNU General Public License - # as published by the Free Software Foundation; either version 2 - # of the License, or (at your option) any later version. - # - # This program is distributed in the hope that it will be useful, - # but WITHOUT ANY WARRANTY; without even the implied warranty of - # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - # GNU General Public License for more details. - # - # You should have received a copy of the GNU General Public License - # along with this program; if not, write to the Free Software Foundation, - # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - # - # Contributor(s): Campbell Barton - # - # #**** END GPL LICENSE BLOCK #**** +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ***** END GPL LICENSE BLOCK ***** + +# defs = """ SPACE_EMPTY, @@ -50,8 +50,10 @@ if not w: continue - try: w.remove("#define") - except: pass + try: + w.remove("#define") + except: + pass # print w @@ -59,7 +61,3 @@ py_val = w[0] print '\tPyModule_AddObject(mod, "%s", PyLong_FromSize_t(%s));' % (val, py_val) - - - - diff --git a/source/blender/render/extern/include/RE_engine.h b/source/blender/render/extern/include/RE_engine.h index cb27ccdbecfa..5c1dc468b8f7 100644 --- a/source/blender/render/extern/include/RE_engine.h +++ b/source/blender/render/extern/include/RE_engine.h @@ -141,16 +141,16 @@ void RE_result_load_from_file(struct RenderResult *result, struct ReportList *re struct RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h, const char *layername, const char *viewname); void RE_engine_update_result(RenderEngine *engine, struct RenderResult *result); void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, const char *chan_id, const char *layername); -void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int cancel, int highlight, int merge_results); +void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, bool cancel, bool highlight, bool merge_results); struct RenderResult *RE_engine_get_result(struct RenderEngine *engine); const char *RE_engine_active_view_get(RenderEngine *engine); void RE_engine_active_view_set(RenderEngine *engine, const char *viewname); -float RE_engine_get_camera_shift_x(RenderEngine *engine, struct Object *camera, int use_spherical_stereo); -void RE_engine_get_camera_model_matrix(RenderEngine *engine, struct Object *camera, int use_spherical_stereo, float *r_modelmat); -int RE_engine_get_spherical_stereo(RenderEngine *engine, struct Object *camera); +float RE_engine_get_camera_shift_x(RenderEngine *engine, struct Object *camera, bool use_spherical_stereo); +void RE_engine_get_camera_model_matrix(RenderEngine *engine, struct Object *camera, bool use_spherical_stereo, float *r_modelmat); +bool RE_engine_get_spherical_stereo(RenderEngine *engine, struct Object *camera); -int RE_engine_test_break(RenderEngine *engine); +bool RE_engine_test_break(RenderEngine *engine); void RE_engine_update_stats(RenderEngine *engine, const char *stats, const char *info); void RE_engine_update_progress(RenderEngine *engine, float progress); void RE_engine_update_memory_stats(RenderEngine *engine, float mem_used, float mem_peak); @@ -178,4 +178,3 @@ struct RenderData *RE_engine_get_render_data(struct Render *re); void RE_bake_engine_set_engine_parameters(struct Render *re, struct Main *bmain, struct Scene *scene); #endif /* __RE_ENGINE_H__ */ - diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h index 719883948811..95c87b520436 100644 --- a/source/blender/render/extern/include/RE_pipeline.h +++ b/source/blender/render/extern/include/RE_pipeline.h @@ -394,4 +394,3 @@ struct RenderView *RE_RenderViewGetByName(struct RenderResult *res, const char * RenderResult *RE_DuplicateRenderResult(RenderResult *rr); #endif /* __RE_PIPELINE_H__ */ - diff --git a/source/blender/render/intern/include/envmap.h b/source/blender/render/intern/include/envmap.h index c66427ae788f..cf9efcb0beb6 100644 --- a/source/blender/render/intern/include/envmap.h +++ b/source/blender/render/intern/include/envmap.h @@ -51,4 +51,3 @@ int envmaptex(struct Tex *tex, const float texvec[3], float dxt[3], float dyt[3] void env_rotate_scene(struct Render *re, float mat[4][4], int do_rotate); #endif /* __ENVMAP_H__ */ - diff --git a/source/blender/render/intern/include/initrender.h b/source/blender/render/intern/include/initrender.h index 0f952baf2575..36773b4c73eb 100644 --- a/source/blender/render/intern/include/initrender.h +++ b/source/blender/render/intern/include/initrender.h @@ -45,4 +45,3 @@ void RE_parts_clamp(Render *re); #endif /* __INITRENDER_H__ */ - diff --git a/source/blender/render/intern/include/occlusion.h b/source/blender/render/intern/include/occlusion.h index 4a70d691436c..15a5a04e3f6e 100644 --- a/source/blender/render/intern/include/occlusion.h +++ b/source/blender/render/intern/include/occlusion.h @@ -46,4 +46,3 @@ void cache_occ_samples(struct Render *re, struct RenderPart *pa, struct ShadeSam void free_occ_samples(struct Render *re, struct RenderPart *pa); #endif - diff --git a/source/blender/render/intern/include/pixelshading.h b/source/blender/render/intern/include/pixelshading.h index 0e630eda475b..ff4f705a6176 100644 --- a/source/blender/render/intern/include/pixelshading.h +++ b/source/blender/render/intern/include/pixelshading.h @@ -59,4 +59,3 @@ void shadeSunView(float col_r[3], const float view[3]); /* ------------------------------------------------------------------------- */ #endif - diff --git a/source/blender/render/intern/include/pointdensity.h b/source/blender/render/intern/include/pointdensity.h index eadf714c1bab..18289d009d58 100644 --- a/source/blender/render/intern/include/pointdensity.h +++ b/source/blender/render/intern/include/pointdensity.h @@ -48,4 +48,3 @@ void free_pointdensities(struct Render *re); int pointdensitytex(struct Tex *tex, const float texvec[3], struct TexResult *texres); #endif /* __POINTDENSITY_H__ */ - diff --git a/source/blender/render/intern/include/rayintersection.h b/source/blender/render/intern/include/rayintersection.h index a303301ad3be..aab511d61919 100644 --- a/source/blender/render/intern/include/rayintersection.h +++ b/source/blender/render/intern/include/rayintersection.h @@ -133,4 +133,3 @@ typedef struct Isect { #endif #endif /* __RAYINTERSECTION_H__ */ - diff --git a/source/blender/render/intern/include/render_result.h b/source/blender/render/intern/include/render_result.h index 7757e395af4b..7713c9c7fba4 100644 --- a/source/blender/render/intern/include/render_result.h +++ b/source/blender/render/intern/include/render_result.h @@ -118,4 +118,3 @@ void render_result_views_shallowdelete(struct RenderResult *rr); bool render_result_has_views(struct RenderResult *rr); #endif /* __RENDER_RESULT_H__ */ - diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h index 8685a51d7b17..a07d7bf6da37 100644 --- a/source/blender/render/intern/include/render_types.h +++ b/source/blender/render/intern/include/render_types.h @@ -686,4 +686,3 @@ typedef struct LampRen { #define R_TRANSFORMED (1|2) #endif /* __RENDER_TYPES_H__ */ - diff --git a/source/blender/render/intern/include/renderdatabase.h b/source/blender/render/intern/include/renderdatabase.h index d0b0d6952244..1840ec493c84 100644 --- a/source/blender/render/intern/include/renderdatabase.h +++ b/source/blender/render/intern/include/renderdatabase.h @@ -171,4 +171,3 @@ void RE_Database_FromScene_Vectors(Render *re, struct Main *bmain, struct Scene #endif #endif /* __RENDERDATABASE_H__ */ - diff --git a/source/blender/render/intern/include/renderpipeline.h b/source/blender/render/intern/include/renderpipeline.h index 3208288328bf..925924499cd3 100644 --- a/source/blender/render/intern/include/renderpipeline.h +++ b/source/blender/render/intern/include/renderpipeline.h @@ -44,4 +44,3 @@ void render_update_anim_renderdata(struct Render *re, struct RenderData *rd); void render_copy_renderdata(struct RenderData *to, struct RenderData *from); #endif /* __RENDERPIPELINE_H__ */ - diff --git a/source/blender/render/intern/include/shadbuf.h b/source/blender/render/intern/include/shadbuf.h index ddf5de8d9743..5901d2187dc3 100644 --- a/source/blender/render/intern/include/shadbuf.h +++ b/source/blender/render/intern/include/shadbuf.h @@ -109,4 +109,3 @@ typedef struct ISBData { } ISBData; #endif /* __SHADBUF_H__ */ - diff --git a/source/blender/render/intern/include/sss.h b/source/blender/render/intern/include/sss.h index c8f759cfe4e3..e01dfe738517 100644 --- a/source/blender/render/intern/include/sss.h +++ b/source/blender/render/intern/include/sss.h @@ -64,4 +64,3 @@ int sample_sss(struct Render *re, struct Material *mat, const float co[3], float int sss_pass_done(struct Render *re, struct Material *mat); #endif /*__SSS_H__*/ - diff --git a/source/blender/render/intern/include/strand.h b/source/blender/render/intern/include/strand.h index f4e22c78b42a..354ba3f0f07f 100644 --- a/source/blender/render/intern/include/strand.h +++ b/source/blender/render/intern/include/strand.h @@ -96,4 +96,3 @@ void strand_shade_segment(struct Render *re, struct StrandShadeCache *cache, str void strand_shade_unref(struct StrandShadeCache *cache, struct ObjectInstanceRen *obi, struct StrandVert *svert); #endif - diff --git a/source/blender/render/intern/include/texture.h b/source/blender/render/intern/include/texture.h index dfb491f46b0a..f6d39b81f2ae 100644 --- a/source/blender/render/intern/include/texture.h +++ b/source/blender/render/intern/include/texture.h @@ -93,4 +93,3 @@ int imagewrap(struct Tex *tex, struct Image *ima, struct ImBuf *ibuf, const floa void image_sample(struct Image *ima, float fx, float fy, float dx, float dy, float result[4], struct ImagePool *pool); #endif /* __TEXTURE_H__ */ - diff --git a/source/blender/render/intern/include/zbuf.h b/source/blender/render/intern/include/zbuf.h index 95c78e6d6146..50ad78b5be78 100644 --- a/source/blender/render/intern/include/zbuf.h +++ b/source/blender/render/intern/include/zbuf.h @@ -148,4 +148,3 @@ void zspan_scanconvert_strand(ZSpan *zspan, void *handle, float *v1, float *v2, void zbufsinglewire(ZSpan *zspan, int obi, int zvlnr, const float ho1[4], const float ho2[4]); #endif - diff --git a/source/blender/render/intern/raytrace/rayobject.cpp b/source/blender/render/intern/raytrace/rayobject.cpp index fee877b311de..bb429dc77a4b 100644 --- a/source/blender/render/intern/raytrace/rayobject.cpp +++ b/source/blender/render/intern/raytrace/rayobject.cpp @@ -531,4 +531,3 @@ void RE_rayobject_set_control(RayObject *r, void *data, RE_rayobjectcontrol_test r->control.test_break = test_break; } } - diff --git a/source/blender/render/intern/raytrace/rayobject_empty.cpp b/source/blender/render/intern/raytrace/rayobject_empty.cpp index 6382e6f524ca..b05316016406 100644 --- a/source/blender/render/intern/raytrace/rayobject_empty.cpp +++ b/source/blender/render/intern/raytrace/rayobject_empty.cpp @@ -78,4 +78,3 @@ RayObject *RE_rayobject_empty_create() { return RE_rayobject_unalignRayAPI( &empty_raytree ); } - diff --git a/source/blender/render/intern/raytrace/rayobject_instance.cpp b/source/blender/render/intern/raytrace/rayobject_instance.cpp index 361e7963d964..4497f34cebd3 100644 --- a/source/blender/render/intern/raytrace/rayobject_instance.cpp +++ b/source/blender/render/intern/raytrace/rayobject_instance.cpp @@ -208,4 +208,3 @@ static void RE_rayobject_instance_bb(RayObject *o, float *min, float *max) DO_MINMAX(t, min, max); } } - diff --git a/source/blender/render/intern/raytrace/rayobject_octree.cpp b/source/blender/render/intern/raytrace/rayobject_octree.cpp index 4b73e64ca450..466d5e28b24d 100644 --- a/source/blender/render/intern/raytrace/rayobject_octree.cpp +++ b/source/blender/render/intern/raytrace/rayobject_octree.cpp @@ -1096,6 +1096,3 @@ static int RE_rayobject_octree_intersect(RayObject *tree, Isect *is) /* reached end, no intersections found */ return 0; } - - - diff --git a/source/blender/render/intern/source/bake_api.c b/source/blender/render/intern/source/bake_api.c index 8b25c1fe9626..4d5a84588977 100644 --- a/source/blender/render/intern/source/bake_api.c +++ b/source/blender/render/intern/source/bake_api.c @@ -568,7 +568,8 @@ bool RE_bake_pixels_populate_from_objects( /* cast ray */ if (!cast_ray_highpoly(treeData, tri_low, tris_high, pixel_array_from, pixel_array_to, mat_low, - highpoly, co, dir, i, tot_highpoly)) { + highpoly, co, dir, i, tot_highpoly)) + { /* if it fails mask out the original pixel array */ pixel_array_from[i].primitive_id = -1; } diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c index d26c7d9ead92..316fb63af1c8 100644 --- a/source/blender/render/intern/source/convertblender.c +++ b/source/blender/render/intern/source/convertblender.c @@ -3757,24 +3757,24 @@ static GroupObject *add_render_lamp(Render *re, Object *ob) } else if (lar->type==LA_AREA) { switch (lar->area_shape) { - case LA_AREA_SQUARE: - lar->ray_totsamp= lar->ray_samp*lar->ray_samp; - lar->ray_sampy= lar->ray_samp; - lar->area_sizey= lar->area_size; - break; - case LA_AREA_RECT: - lar->ray_totsamp= lar->ray_samp*lar->ray_sampy; - break; - case LA_AREA_CUBE: - lar->ray_totsamp= lar->ray_samp*lar->ray_samp*lar->ray_samp; - lar->ray_sampy= lar->ray_samp; - lar->ray_sampz= lar->ray_samp; - lar->area_sizey= lar->area_size; - lar->area_sizez= lar->area_size; - break; - case LA_AREA_BOX: - lar->ray_totsamp= lar->ray_samp*lar->ray_sampy*lar->ray_sampz; - break; + case LA_AREA_SQUARE: + lar->ray_totsamp= lar->ray_samp*lar->ray_samp; + lar->ray_sampy= lar->ray_samp; + lar->area_sizey= lar->area_size; + break; + case LA_AREA_RECT: + lar->ray_totsamp= lar->ray_samp*lar->ray_sampy; + break; + case LA_AREA_CUBE: + lar->ray_totsamp= lar->ray_samp*lar->ray_samp*lar->ray_samp; + lar->ray_sampy= lar->ray_samp; + lar->ray_sampz= lar->ray_samp; + lar->area_sizey= lar->area_size; + lar->area_sizez= lar->area_size; + break; + case LA_AREA_BOX: + lar->ray_totsamp= lar->ray_samp*lar->ray_sampy*lar->ray_sampz; + break; } area_lamp_vectors(lar); diff --git a/source/blender/render/intern/source/external_engine.c b/source/blender/render/intern/source/external_engine.c index b99ab611458a..3520a3120120 100644 --- a/source/blender/render/intern/source/external_engine.c +++ b/source/blender/render/intern/source/external_engine.c @@ -258,7 +258,7 @@ void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, co render_result_add_pass(re->result, name, channels, chan_id, layername, NULL); } -void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel, int highlight, int merge_results) +void RE_engine_end_result(RenderEngine *engine, RenderResult *result, bool cancel, bool highlight, bool merge_results) { Render *re = engine->re; @@ -309,7 +309,7 @@ RenderResult *RE_engine_get_result(RenderEngine *engine) /* Cancel */ -int RE_engine_test_break(RenderEngine *engine) +bool RE_engine_test_break(RenderEngine *engine) { Render *re = engine->re; @@ -402,7 +402,7 @@ void RE_engine_active_view_set(RenderEngine *engine, const char *viewname) RE_SetActiveRenderView(re, viewname); } -float RE_engine_get_camera_shift_x(RenderEngine *engine, Object *camera, int use_spherical_stereo) +float RE_engine_get_camera_shift_x(RenderEngine *engine, Object *camera, bool use_spherical_stereo) { Render *re = engine->re; @@ -413,7 +413,7 @@ float RE_engine_get_camera_shift_x(RenderEngine *engine, Object *camera, int use return BKE_camera_multiview_shift_x(re ? &re->r : NULL, camera, re->viewname); } -void RE_engine_get_camera_model_matrix(RenderEngine *engine, Object *camera, int use_spherical_stereo, float *r_modelmat) +void RE_engine_get_camera_model_matrix(RenderEngine *engine, Object *camera, bool use_spherical_stereo, float *r_modelmat) { Render *re = engine->re; @@ -424,7 +424,7 @@ void RE_engine_get_camera_model_matrix(RenderEngine *engine, Object *camera, int BKE_camera_multiview_model_matrix(re ? &re->r : NULL, camera, re->viewname, (float (*)[4])r_modelmat); } -int RE_engine_get_spherical_stereo(RenderEngine *engine, Object *camera) +bool RE_engine_get_spherical_stereo(RenderEngine *engine, Object *camera) { Render *re = engine->re; return BKE_camera_multiview_spherical_stereo(re ? &re->r : NULL, camera) ? 1 : 0; @@ -790,8 +790,9 @@ void RE_engine_register_pass(struct RenderEngine *engine, struct Scene *scene, s /* Register the pass in all scenes that have a render layer node for this layer. * Since multiple scenes can be used in the compositor, the code must loop over all scenes * and check whether their nodetree has a node that needs to be updated. */ - Scene *sce; - for (sce = G.main->scene.first; sce; sce = sce->id.next) { + /* NOTE: using G_MAIN seems valid here, + * unless we want to register that for every other temp Main we could generate??? */ + for (Scene *sce = G_MAIN->scene.first; sce; sce = sce->id.next) { if (sce->nodetree) { ntreeCompositRegisterPass(sce->nodetree, scene, srl, name, type); } diff --git a/source/blender/render/intern/source/initrender.c b/source/blender/render/intern/source/initrender.c index 34e47a00c7af..b834a3afbf0a 100644 --- a/source/blender/render/intern/source/initrender.c +++ b/source/blender/render/intern/source/initrender.c @@ -620,6 +620,3 @@ void RE_parts_init(Render *re, bool do_crop) } } } - - - diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c index 8aa90a390b3f..9b9a5aabca62 100644 --- a/source/blender/render/intern/source/occlusion.c +++ b/source/blender/render/intern/source/occlusion.c @@ -1530,4 +1530,3 @@ void free_occ_samples(Render *re, RenderPart *pa) cache->step = 0; } } - diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c index ea47ac34f13a..97971030dfbc 100644 --- a/source/blender/render/intern/source/pipeline.c +++ b/source/blender/render/intern/source/pipeline.c @@ -198,7 +198,8 @@ static void stats_background(void *UNUSED(arg), RenderStats *rs) /* Flush stdout to be sure python callbacks are printing stuff after blender. */ fflush(stdout); - BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS); + /* NOTE: using G_MAIN seems valid here??? Not sure it's actually even used anyway, we could as well pass NULL? */ + BLI_callback_exec(G_MAIN, NULL, BLI_CB_EVT_RENDER_STATS); fputc('\n', stdout); fflush(stdout); @@ -3409,7 +3410,7 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen ImageFormatData imf = rd->im_format; imf.imtype = R_IMF_IMTYPE_JPEG90; - if (BLI_testextensie(name, ".exr")) + if (BLI_path_extension_check(name, ".exr")) name[strlen(name) - 4] = 0; BKE_image_path_ensure_ext_from_imformat(name, &imf); @@ -3464,7 +3465,7 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen ImageFormatData imf = rd->im_format; imf.imtype = R_IMF_IMTYPE_JPEG90; - if (BLI_testextensie(name, ".exr")) + if (BLI_path_extension_check(name, ".exr")) name[strlen(name) - 4] = 0; BKE_image_path_ensure_ext_from_imformat(name, &imf); @@ -3577,7 +3578,8 @@ static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovie /* Flush stdout to be sure python callbacks are printing stuff after blender. */ fflush(stdout); - BLI_callback_exec(re->main, NULL, BLI_CB_EVT_RENDER_STATS); + /* NOTE: using G_MAIN seems valid here??? Not sure it's actually even used anyway, we could as well pass NULL? */ + BLI_callback_exec(G_MAIN, NULL, BLI_CB_EVT_RENDER_STATS); BLI_timecode_string_from_time_simple(name, sizeof(name), re->i.lastframetime - render_time); printf(" (Saving: %s)\n", name); diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c index df1cb868230e..6e3dffccc163 100644 --- a/source/blender/render/intern/source/rayshade.c +++ b/source/blender/render/intern/source/rayshade.c @@ -2500,4 +2500,3 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float shadfac[4]) } } - diff --git a/source/blender/render/intern/source/render_result.c b/source/blender/render/intern/source/render_result.c index d9e83b209b89..4f2b0980762e 100644 --- a/source/blender/render/intern/source/render_result.c +++ b/source/blender/render/intern/source/render_result.c @@ -912,7 +912,8 @@ bool RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *fil /* Skip non-RGBA and Z passes if not using multi layer. */ if (!multi_layer && !(STREQ(rp->name, RE_PASSNAME_COMBINED) || STREQ(rp->name, "") || - (STREQ(rp->name, RE_PASSNAME_Z) && write_z))) { + (STREQ(rp->name, RE_PASSNAME_Z) && write_z))) + { continue; } @@ -1257,7 +1258,7 @@ static void render_result_exr_file_cache_path(Scene *sce, const char *root, char const char *blendfile_path = BKE_main_blendfile_path_from_global(); if (blendfile_path[0] != '\0') { BLI_split_dirfile(blendfile_path, dirname, filename, sizeof(dirname), sizeof(filename)); - BLI_replace_extension(filename, sizeof(filename), ""); /* strip '.blend' */ + BLI_path_extension_replace(filename, sizeof(filename), ""); /* strip '.blend' */ BLI_hash_md5_buffer(blendfile_path, strlen(blendfile_path), path_digest); } else { diff --git a/source/blender/render/intern/source/render_texture.c b/source/blender/render/intern/source/render_texture.c index 8450098d7334..7426e9536325 100644 --- a/source/blender/render/intern/source/render_texture.c +++ b/source/blender/render/intern/source/render_texture.c @@ -1453,127 +1453,127 @@ void texture_rgb_blend(float in[3], const float tex[3], const float out[3], floa float facm; switch (blendtype) { - case MTEX_BLEND: - fact*= facg; - facm= 1.0f-fact; - - in[0]= (fact*tex[0] + facm*out[0]); - in[1]= (fact*tex[1] + facm*out[1]); - in[2]= (fact*tex[2] + facm*out[2]); - break; - - case MTEX_MUL: - fact*= facg; - facm= 1.0f-fact; - in[0]= (facm+fact*tex[0])*out[0]; - in[1]= (facm+fact*tex[1])*out[1]; - in[2]= (facm+fact*tex[2])*out[2]; - break; - - case MTEX_SCREEN: - fact*= facg; - facm= 1.0f-fact; - in[0]= 1.0f - (facm+fact*(1.0f-tex[0])) * (1.0f-out[0]); - in[1]= 1.0f - (facm+fact*(1.0f-tex[1])) * (1.0f-out[1]); - in[2]= 1.0f - (facm+fact*(1.0f-tex[2])) * (1.0f-out[2]); - break; - - case MTEX_OVERLAY: - fact*= facg; - facm= 1.0f-fact; - - if (out[0] < 0.5f) - in[0] = out[0] * (facm + 2.0f*fact*tex[0]); - else - in[0] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[0])) * (1.0f - out[0]); - if (out[1] < 0.5f) - in[1] = out[1] * (facm + 2.0f*fact*tex[1]); - else - in[1] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[1])) * (1.0f - out[1]); - if (out[2] < 0.5f) - in[2] = out[2] * (facm + 2.0f*fact*tex[2]); - else - in[2] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[2])) * (1.0f - out[2]); - break; - - case MTEX_SUB: - fact= -fact; - ATTR_FALLTHROUGH; - case MTEX_ADD: - fact*= facg; - in[0]= (fact*tex[0] + out[0]); - in[1]= (fact*tex[1] + out[1]); - in[2]= (fact*tex[2] + out[2]); - break; - - case MTEX_DIV: - fact*= facg; - facm= 1.0f-fact; - - if (tex[0]!=0.0f) - in[0]= facm*out[0] + fact*out[0]/tex[0]; - if (tex[1]!=0.0f) - in[1]= facm*out[1] + fact*out[1]/tex[1]; - if (tex[2]!=0.0f) - in[2]= facm*out[2] + fact*out[2]/tex[2]; - - break; - - case MTEX_DIFF: - fact*= facg; - facm= 1.0f-fact; - in[0]= facm*out[0] + fact*fabsf(tex[0]-out[0]); - in[1]= facm*out[1] + fact*fabsf(tex[1]-out[1]); - in[2]= facm*out[2] + fact*fabsf(tex[2]-out[2]); - break; - - case MTEX_DARK: - fact*= facg; - facm= 1.0f-fact; - - in[0] = min_ff(out[0], tex[0])*fact + out[0]*facm; - in[1] = min_ff(out[1], tex[1])*fact + out[1]*facm; - in[2] = min_ff(out[2], tex[2])*fact + out[2]*facm; - break; - - case MTEX_LIGHT: - fact*= facg; - - in[0] = max_ff(fact * tex[0], out[0]); - in[1] = max_ff(fact * tex[1], out[1]); - in[2] = max_ff(fact * tex[2], out[2]); - break; - - case MTEX_BLEND_HUE: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_HUE, in, fact, tex); - break; - case MTEX_BLEND_SAT: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_SAT, in, fact, tex); - break; - case MTEX_BLEND_VAL: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_VAL, in, fact, tex); - break; - case MTEX_BLEND_COLOR: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_COLOR, in, fact, tex); - break; - case MTEX_SOFT_LIGHT: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_SOFT, in, fact, tex); - break; - case MTEX_LIN_LIGHT: - fact*= facg; - copy_v3_v3(in, out); - ramp_blend(MA_RAMP_LINEAR, in, fact, tex); - break; + case MTEX_BLEND: + fact*= facg; + facm= 1.0f-fact; + + in[0]= (fact*tex[0] + facm*out[0]); + in[1]= (fact*tex[1] + facm*out[1]); + in[2]= (fact*tex[2] + facm*out[2]); + break; + + case MTEX_MUL: + fact*= facg; + facm= 1.0f-fact; + in[0]= (facm+fact*tex[0])*out[0]; + in[1]= (facm+fact*tex[1])*out[1]; + in[2]= (facm+fact*tex[2])*out[2]; + break; + + case MTEX_SCREEN: + fact*= facg; + facm= 1.0f-fact; + in[0]= 1.0f - (facm+fact*(1.0f-tex[0])) * (1.0f-out[0]); + in[1]= 1.0f - (facm+fact*(1.0f-tex[1])) * (1.0f-out[1]); + in[2]= 1.0f - (facm+fact*(1.0f-tex[2])) * (1.0f-out[2]); + break; + + case MTEX_OVERLAY: + fact*= facg; + facm= 1.0f-fact; + + if (out[0] < 0.5f) + in[0] = out[0] * (facm + 2.0f*fact*tex[0]); + else + in[0] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[0])) * (1.0f - out[0]); + if (out[1] < 0.5f) + in[1] = out[1] * (facm + 2.0f*fact*tex[1]); + else + in[1] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[1])) * (1.0f - out[1]); + if (out[2] < 0.5f) + in[2] = out[2] * (facm + 2.0f*fact*tex[2]); + else + in[2] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[2])) * (1.0f - out[2]); + break; + + case MTEX_SUB: + fact= -fact; + ATTR_FALLTHROUGH; + case MTEX_ADD: + fact*= facg; + in[0]= (fact*tex[0] + out[0]); + in[1]= (fact*tex[1] + out[1]); + in[2]= (fact*tex[2] + out[2]); + break; + + case MTEX_DIV: + fact*= facg; + facm= 1.0f-fact; + + if (tex[0]!=0.0f) + in[0]= facm*out[0] + fact*out[0]/tex[0]; + if (tex[1]!=0.0f) + in[1]= facm*out[1] + fact*out[1]/tex[1]; + if (tex[2]!=0.0f) + in[2]= facm*out[2] + fact*out[2]/tex[2]; + + break; + + case MTEX_DIFF: + fact*= facg; + facm= 1.0f-fact; + in[0]= facm*out[0] + fact*fabsf(tex[0]-out[0]); + in[1]= facm*out[1] + fact*fabsf(tex[1]-out[1]); + in[2]= facm*out[2] + fact*fabsf(tex[2]-out[2]); + break; + + case MTEX_DARK: + fact*= facg; + facm= 1.0f-fact; + + in[0] = min_ff(out[0], tex[0])*fact + out[0]*facm; + in[1] = min_ff(out[1], tex[1])*fact + out[1]*facm; + in[2] = min_ff(out[2], tex[2])*fact + out[2]*facm; + break; + + case MTEX_LIGHT: + fact*= facg; + + in[0] = max_ff(fact * tex[0], out[0]); + in[1] = max_ff(fact * tex[1], out[1]); + in[2] = max_ff(fact * tex[2], out[2]); + break; + + case MTEX_BLEND_HUE: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_HUE, in, fact, tex); + break; + case MTEX_BLEND_SAT: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_SAT, in, fact, tex); + break; + case MTEX_BLEND_VAL: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_VAL, in, fact, tex); + break; + case MTEX_BLEND_COLOR: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_COLOR, in, fact, tex); + break; + case MTEX_SOFT_LIGHT: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_SOFT, in, fact, tex); + break; + case MTEX_LIN_LIGHT: + fact*= facg; + copy_v3_v3(in, out); + ramp_blend(MA_RAMP_LINEAR, in, fact, tex); + break; } } @@ -1589,64 +1589,64 @@ float texture_value_blend(float tex, float out, float fact, float facg, int blen if (flip) SWAP(float, fact, facm); switch (blendtype) { - case MTEX_BLEND: - in= fact*tex + facm*out; - break; - - case MTEX_MUL: - facm= 1.0f-facg; - in= (facm+fact*tex)*out; - break; - - case MTEX_SCREEN: - facm= 1.0f-facg; - in= 1.0f-(facm+fact*(1.0f-tex))*(1.0f-out); - break; - - case MTEX_OVERLAY: - facm= 1.0f-facg; - if (out < 0.5f) - in = out * (facm + 2.0f*fact*tex); - else - in = 1.0f - (facm + 2.0f*fact*(1.0f - tex)) * (1.0f - out); - break; - - case MTEX_SUB: - fact= -fact; - ATTR_FALLTHROUGH; - case MTEX_ADD: - in= fact*tex + out; - break; - - case MTEX_DIV: - if (tex!=0.0f) - in= facm*out + fact*out/tex; - break; - - case MTEX_DIFF: - in= facm*out + fact*fabsf(tex-out); - break; - - case MTEX_DARK: - in = min_ff(out, tex)*fact + out*facm; - break; - - case MTEX_LIGHT: - col= fact*tex; - if (col > out) in= col; else in= out; - break; - - case MTEX_SOFT_LIGHT: - scf=1.0f - (1.0f - tex) * (1.0f - out); - in= facm*out + fact * ((1.0f - out) * tex * out) + (out * scf); - break; - - case MTEX_LIN_LIGHT: - if (tex > 0.5f) - in = out + fact*(2.0f*(tex - 0.5f)); - else - in = out + fact*(2.0f*tex - 1.0f); - break; + case MTEX_BLEND: + in= fact*tex + facm*out; + break; + + case MTEX_MUL: + facm= 1.0f-facg; + in= (facm+fact*tex)*out; + break; + + case MTEX_SCREEN: + facm= 1.0f-facg; + in= 1.0f-(facm+fact*(1.0f-tex))*(1.0f-out); + break; + + case MTEX_OVERLAY: + facm= 1.0f-facg; + if (out < 0.5f) + in = out * (facm + 2.0f*fact*tex); + else + in = 1.0f - (facm + 2.0f*fact*(1.0f - tex)) * (1.0f - out); + break; + + case MTEX_SUB: + fact= -fact; + ATTR_FALLTHROUGH; + case MTEX_ADD: + in= fact*tex + out; + break; + + case MTEX_DIV: + if (tex!=0.0f) + in= facm*out + fact*out/tex; + break; + + case MTEX_DIFF: + in= facm*out + fact*fabsf(tex-out); + break; + + case MTEX_DARK: + in = min_ff(out, tex)*fact + out*facm; + break; + + case MTEX_LIGHT: + col= fact*tex; + if (col > out) in= col; else in= out; + break; + + case MTEX_SOFT_LIGHT: + scf=1.0f - (1.0f - tex) * (1.0f - out); + in= facm*out + fact * ((1.0f - out) * tex * out) + (out * scf); + break; + + case MTEX_LIN_LIGHT: + if (tex > 0.5f) + in = out + fact*(2.0f*(tex - 0.5f)); + else + in = out + fact*(2.0f*tex - 1.0f); + break; } return in; @@ -3201,76 +3201,76 @@ void do_sky_tex( /* Grab the mapping settings for this texture */ switch (mtex->texco) { - case TEXCO_ANGMAP: - /* only works with texture being "real" */ - /* use saacos(), fixes bug [#22398], float precision caused lo[2] to be slightly less than -1.0 */ - if (lo[0] || lo[1]) { /* check for zero case [#24807] */ - fact= (1.0f/(float)M_PI)*saacos(lo[2])/(sqrtf(lo[0]*lo[0] + lo[1]*lo[1])); - tempvec[0]= lo[0]*fact; - tempvec[1]= lo[1]*fact; - tempvec[2]= 0.0; - } - else { - /* this value has no angle, the vector is directly along the view. - * avoid divide by zero and use a dummy value. */ - tempvec[0]= 1.0f; - tempvec[1]= 0.0; - tempvec[2]= 0.0; - } - co= tempvec; - break; - - case TEXCO_H_SPHEREMAP: - case TEXCO_H_TUBEMAP: - if (skyflag & WO_ZENUP) { - if (mtex->texco==TEXCO_H_TUBEMAP) map_to_tube( tempvec, tempvec+1, lo[0], lo[2], lo[1]); - else map_to_sphere(tempvec, tempvec+1, lo[0], lo[2], lo[1]); - /* tube/spheremap maps for outside view, not inside */ - tempvec[0]= 1.0f-tempvec[0]; - /* only top half */ - tempvec[1]= 2.0f*tempvec[1]-1.0f; - tempvec[2]= 0.0; - /* and correction for do_2d_mapping */ - tempvec[0]= 2.0f*tempvec[0]-1.0f; - tempvec[1]= 2.0f*tempvec[1]-1.0f; - co= tempvec; - } - else { - /* potentially dangerous... check with multitex! */ - continue; - } - break; - case TEXCO_EQUIRECTMAP: - tempvec[0]= -atan2f(lo[2], lo[0]) / (float)M_PI; - tempvec[1]= atan2f(lo[1], hypot(lo[0], lo[2])) / (float)M_PI_2; - tempvec[2]= 0.0f; - co= tempvec; - break; - case TEXCO_OBJECT: - if (mtex->object) { - copy_v3_v3(tempvec, lo); - mul_m4_v3(mtex->object->imat_ren, tempvec); + case TEXCO_ANGMAP: + /* only works with texture being "real" */ + /* use saacos(), fixes bug [#22398], float precision caused lo[2] to be slightly less than -1.0 */ + if (lo[0] || lo[1]) { /* check for zero case [#24807] */ + fact= (1.0f/(float)M_PI)*saacos(lo[2])/(sqrtf(lo[0]*lo[0] + lo[1]*lo[1])); + tempvec[0]= lo[0]*fact; + tempvec[1]= lo[1]*fact; + tempvec[2]= 0.0; + } + else { + /* this value has no angle, the vector is directly along the view. + * avoid divide by zero and use a dummy value. */ + tempvec[0]= 1.0f; + tempvec[1]= 0.0; + tempvec[2]= 0.0; + } co= tempvec; - } - break; - - case TEXCO_GLOB: - if (rco) { - copy_v3_v3(tempvec, rco); - mul_m4_v3(R.viewinv, tempvec); + break; + + case TEXCO_H_SPHEREMAP: + case TEXCO_H_TUBEMAP: + if (skyflag & WO_ZENUP) { + if (mtex->texco==TEXCO_H_TUBEMAP) map_to_tube( tempvec, tempvec+1, lo[0], lo[2], lo[1]); + else map_to_sphere(tempvec, tempvec+1, lo[0], lo[2], lo[1]); + /* tube/spheremap maps for outside view, not inside */ + tempvec[0]= 1.0f-tempvec[0]; + /* only top half */ + tempvec[1]= 2.0f*tempvec[1]-1.0f; + tempvec[2]= 0.0; + /* and correction for do_2d_mapping */ + tempvec[0]= 2.0f*tempvec[0]-1.0f; + tempvec[1]= 2.0f*tempvec[1]-1.0f; + co= tempvec; + } + else { + /* potentially dangerous... check with multitex! */ + continue; + } + break; + case TEXCO_EQUIRECTMAP: + tempvec[0]= -atan2f(lo[2], lo[0]) / (float)M_PI; + tempvec[1]= atan2f(lo[1], hypot(lo[0], lo[2])) / (float)M_PI_2; + tempvec[2]= 0.0f; co= tempvec; - } - else - co= lo; + break; + case TEXCO_OBJECT: + if (mtex->object) { + copy_v3_v3(tempvec, lo); + mul_m4_v3(mtex->object->imat_ren, tempvec); + co= tempvec; + } + break; -// copy_v3_v3(shi->dxgl, shi->dxco); -// mul_m3_v3(R.imat, shi->dxco); -// copy_v3_v3(shi->dygl, shi->dyco); -// mul_m3_v3(R.imat, shi->dyco); - break; - case TEXCO_VIEW: - co = view; - break; + case TEXCO_GLOB: + if (rco) { + copy_v3_v3(tempvec, rco); + mul_m4_v3(R.viewinv, tempvec); + co= tempvec; + } + else + co= lo; + +// copy_v3_v3(shi->dxgl, shi->dxco); +// mul_m3_v3(R.imat, shi->dxco); +// copy_v3_v3(shi->dygl, shi->dyco); +// mul_m3_v3(R.imat, shi->dyco); + break; + case TEXCO_VIEW: + co = view; + break; } /* placement */ diff --git a/source/blender/render/intern/source/renderdatabase.c b/source/blender/render/intern/source/renderdatabase.c index 67bfd1bfdc75..831f94138df0 100644 --- a/source/blender/render/intern/source/renderdatabase.c +++ b/source/blender/render/intern/source/renderdatabase.c @@ -1600,4 +1600,3 @@ int clip_render_object(float boundbox[2][3], float bounds[4], float winmat[4][4] return flag; } - diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c index d79749871c30..407f0b145782 100644 --- a/source/blender/render/intern/source/shadeinput.c +++ b/source/blender/render/intern/source/shadeinput.c @@ -1487,4 +1487,3 @@ int shade_samples(ShadeSample *ssamp, PixStr *ps, int x, int y) } return 0; } - diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c index 57394c1fcb97..7d96cc664294 100644 --- a/source/blender/render/intern/source/shadeoutput.c +++ b/source/blender/render/intern/source/shadeoutput.c @@ -1048,18 +1048,18 @@ static void do_specular_ramp(ShadeInput *shi, float is, float t, float spec[3]) /* input */ switch (ma->rampin_spec) { - case MA_RAMP_IN_ENERGY: - fac= t; - break; - case MA_RAMP_IN_SHADER: - fac= is; - break; - case MA_RAMP_IN_NOR: - fac= shi->view[0]*shi->vn[0] + shi->view[1]*shi->vn[1] + shi->view[2]*shi->vn[2]; - break; - default: - fac= 0.0f; - break; + case MA_RAMP_IN_ENERGY: + fac= t; + break; + case MA_RAMP_IN_SHADER: + fac= is; + break; + case MA_RAMP_IN_NOR: + fac= shi->view[0]*shi->vn[0] + shi->view[1]*shi->vn[1] + shi->view[2]*shi->vn[2]; + break; + default: + fac= 0.0f; + break; } BKE_colorband_evaluate(ma->ramp_spec, fac, col); @@ -1848,7 +1848,8 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr) /* AO pass */ if (((passflag & SCE_PASS_COMBINED) && (shi->combinedflag & (SCE_PASS_AO|SCE_PASS_ENVIRONMENT|SCE_PASS_INDIRECT))) || - (passflag & (SCE_PASS_AO|SCE_PASS_ENVIRONMENT|SCE_PASS_INDIRECT))) { + (passflag & (SCE_PASS_AO|SCE_PASS_ENVIRONMENT|SCE_PASS_INDIRECT))) + { if ((R.wrld.mode & (WO_AMB_OCC|WO_ENV_LIGHT|WO_INDIRECT_LIGHT)) && (R.r.mode & R_SHADOW)) { /* AO was calculated for scanline already */ if (shi->depth || shi->volume_depth) diff --git a/source/blender/render/intern/source/sss.c b/source/blender/render/intern/source/sss.c index 5919b8130d72..6c180c47152b 100644 --- a/source/blender/render/intern/source/sss.c +++ b/source/blender/render/intern/source/sss.c @@ -1071,4 +1071,3 @@ int sss_pass_done(struct Render *re, struct Material *mat) { return ((re->flag & R_BAKING) || !(re->r.mode & R_SSS) || (re->sss_hash && BLI_ghash_lookup(re->sss_hash, mat))); } - diff --git a/source/blender/render/intern/source/strand.c b/source/blender/render/intern/source/strand.c index 5fde688481ad..8f07b339929a 100644 --- a/source/blender/render/intern/source/strand.c +++ b/source/blender/render/intern/source/strand.c @@ -1066,4 +1066,3 @@ void strand_minmax(StrandRen *strand, float min[3], float max[3], const float wi } } } - diff --git a/source/blender/render/intern/source/volume_precache.c b/source/blender/render/intern/source/volume_precache.c index 8e79f3098146..54a0e67eef0f 100644 --- a/source/blender/render/intern/source/volume_precache.c +++ b/source/blender/render/intern/source/volume_precache.c @@ -852,4 +852,3 @@ int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, const return inside; } - diff --git a/source/blender/windowmanager/CMakeLists.txt b/source/blender/windowmanager/CMakeLists.txt index 59260d110084..42863bceccf1 100644 --- a/source/blender/windowmanager/CMakeLists.txt +++ b/source/blender/windowmanager/CMakeLists.txt @@ -53,7 +53,6 @@ set(INC_SYS set(SRC intern/wm.c - intern/wm_playanim.c intern/wm_cursors.c intern/wm_dragdrop.c intern/wm_draw.c @@ -65,12 +64,16 @@ set(SRC intern/wm_init_exit.c intern/wm_jobs.c intern/wm_keymap.c + intern/wm_menu_type.c intern/wm_operator_props.c + intern/wm_operator_type.c intern/wm_operators.c + intern/wm_playanim.c + intern/wm_stereo.c intern/wm_subwindow.c intern/wm_tooltip.c + intern/wm_uilist_type.c intern/wm_window.c - intern/wm_stereo.c WM_api.h WM_keymap.h diff --git a/source/blender/windowmanager/WM_api.h b/source/blender/windowmanager/WM_api.h index 3324fec4cac8..dd2f9b4c4504 100644 --- a/source/blender/windowmanager/WM_api.h +++ b/source/blender/windowmanager/WM_api.h @@ -72,6 +72,9 @@ struct wmNDOFMotionData; typedef struct wmJob wmJob; /* general API */ +void WM_init_state_app_template_set(const char *app_template); +const char *WM_init_state_app_template_get(void); + void WM_init_state_size_set (int stax, int stay, int sizx, int sizy); void WM_init_state_fullscreen_set(void); void WM_init_state_normal_set(void); @@ -129,10 +132,11 @@ void WM_cursor_grab_enable(struct wmWindow *win, bool wrap, bool hide, int boun void WM_cursor_grab_disable(struct wmWindow *win, const int mouse_ungrab_xy[2]); void WM_cursor_time (struct wmWindow *win, int nr); -void *WM_paint_cursor_activate(struct wmWindowManager *wm, - int (*poll)(struct bContext *C), - void (*draw)(struct bContext *C, int, int, void *customdata), - void *customdata); +void *WM_paint_cursor_activate( + struct wmWindowManager *wm, + bool (*poll)(struct bContext *C), + void (*draw)(struct bContext *C, int, int, void *customdata), + void *customdata); void WM_paint_cursor_end(struct wmWindowManager *wm, void *handle); void WM_paint_cursor_tag_redraw(struct wmWindow *win, struct ARegion *ar); @@ -238,7 +242,7 @@ int WM_operator_confirm (struct bContext *C, struct wmOperator *op, const str int WM_operator_filesel (struct bContext *C, struct wmOperator *op, const struct wmEvent *event); bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const struct ImageFormatData *im_format); /* poll callback, context checks */ -int WM_operator_winactive (struct bContext *C); +bool WM_operator_winactive (struct bContext *C); /* invoke callback, exec + redo popup */ int WM_operator_props_popup_confirm(struct bContext *C, struct wmOperator *op, const struct wmEvent *event); int WM_operator_props_popup_call(struct bContext *C, struct wmOperator *op, const struct wmEvent *event); @@ -260,21 +264,8 @@ void WM_operator_type_set(struct wmOperator *op, struct wmOperatorType *ot); void WM_operator_stack_clear(struct wmWindowManager *wm); void WM_operator_handlers_clear(wmWindowManager *wm, struct wmOperatorType *ot); -struct wmOperatorType *WM_operatortype_find(const char *idname, bool quiet); -void WM_operatortype_iter(struct GHashIterator *ghi); -void WM_operatortype_append(void (*opfunc)(struct wmOperatorType *)); -void WM_operatortype_append_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata); -void WM_operatortype_append_macro_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata); -void WM_operatortype_remove_ptr(struct wmOperatorType *ot); -bool WM_operatortype_remove(const char *idname); -void WM_operatortype_last_properties_clear_all(void); - -struct wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag); -struct wmOperatorTypeMacro *WM_operatortype_macro_define(struct wmOperatorType *ot, const char *idname); - - -int WM_operator_poll (struct bContext *C, struct wmOperatorType *ot); -int WM_operator_poll_context(struct bContext *C, struct wmOperatorType *ot, short context); +bool WM_operator_poll (struct bContext *C, struct wmOperatorType *ot); +bool WM_operator_poll_context(struct bContext *C, struct wmOperatorType *ot, short context); int WM_operator_call_ex(struct bContext *C, struct wmOperator *op, const bool store); int WM_operator_call (struct bContext *C, struct wmOperator *op); int WM_operator_call_notest(struct bContext *C, struct wmOperator *op); @@ -366,14 +357,28 @@ void WM_operator_bl_idname(char *to, const char *from); void WM_operator_py_idname(char *to, const char *from); bool WM_operator_py_idname_ok_or_report(struct ReportList *reports, const char *classname, const char *idname); -/* *************** uilist types ******************** */ + +/* wm_operator_type.c */ +struct wmOperatorType *WM_operatortype_find(const char *idname, bool quiet); +void WM_operatortype_iter(struct GHashIterator *ghi); +void WM_operatortype_append(void (*opfunc)(struct wmOperatorType *)); +void WM_operatortype_append_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata); +void WM_operatortype_append_macro_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata); +void WM_operatortype_remove_ptr(struct wmOperatorType *ot); +bool WM_operatortype_remove(const char *idname); +void WM_operatortype_last_properties_clear_all(void); + +struct wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag); +struct wmOperatorTypeMacro *WM_operatortype_macro_define(struct wmOperatorType *ot, const char *idname); + +/* wm_uilist_type.c */ void WM_uilisttype_init(void); struct uiListType *WM_uilisttype_find(const char *idname, bool quiet); bool WM_uilisttype_add(struct uiListType *ult); void WM_uilisttype_freelink(struct uiListType *ult); void WM_uilisttype_free(void); -/* *************** menu types ******************** */ +/* wm_menu_type.c */ void WM_menutype_init(void); struct MenuType *WM_menutype_find(const char *idname, bool quiet); bool WM_menutype_add(struct MenuType *mt); @@ -417,8 +422,9 @@ void WM_event_drag_image(struct wmDrag *, struct ImBuf *, float scale, int sx void WM_drag_free(struct wmDrag *drag); void WM_drag_free_list(struct ListBase *lb); -struct wmDropBox *WM_dropbox_add(ListBase *lb, const char *idname, int (*poll)(struct bContext *, struct wmDrag *, const struct wmEvent *event), - void (*copy)(struct wmDrag *, struct wmDropBox *)); +struct wmDropBox *WM_dropbox_add( + ListBase *lb, const char *idname, bool (*poll)(struct bContext *, struct wmDrag *, const struct wmEvent *event), + void (*copy)(struct wmDrag *, struct wmDropBox *)); ListBase *WM_dropboxmap_find(const char *idname, int spaceid, int regionid); /* Set a subwindow active in pixelspace view, with optional scissor subset */ @@ -447,7 +453,6 @@ enum { WM_JOB_TYPE_COMPOSITE, WM_JOB_TYPE_RENDER, WM_JOB_TYPE_RENDER_PREVIEW, /* UI preview */ - WM_JOB_TYPE_SCREENCAST, WM_JOB_TYPE_OBJECT_SIM_OCEAN, WM_JOB_TYPE_OBJECT_SIM_FLUID, WM_JOB_TYPE_OBJECT_BAKE_TEXTURE, @@ -462,7 +467,7 @@ enum { WM_JOB_TYPE_POINTCACHE, WM_JOB_TYPE_DPAINT_BAKE, WM_JOB_TYPE_ALEMBIC, - /* add as needed, screencast, seq proxy build + /* add as needed, seq proxy build * if having hard coded values is a problem */ }; @@ -554,4 +559,3 @@ void WM_tooltip_refresh(struct bContext *C, struct wmWindow *win); #endif #endif /* __WM_API_H__ */ - diff --git a/source/blender/windowmanager/WM_keymap.h b/source/blender/windowmanager/WM_keymap.h index c95284143b44..c6dad2ef03ce 100644 --- a/source/blender/windowmanager/WM_keymap.h +++ b/source/blender/windowmanager/WM_keymap.h @@ -71,7 +71,7 @@ bool WM_keymap_remove_item(struct wmKeyMap *keymap, struct wmKeyMapItem * int WM_keymap_item_to_string(wmKeyMapItem *kmi, const bool compact, char *result, const int result_len); wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int regionid); -wmKeyMap *WM_keymap_find(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid); +wmKeyMap *WM_keymap_ensure(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid); wmKeyMap *WM_keymap_find_all(const struct bContext *C, const char *idname, int spaceid, int regionid); wmKeyMap *WM_keymap_active(struct wmWindowManager *wm, struct wmKeyMap *keymap); wmKeyMap *WM_keymap_guess_opname(const struct bContext *C, const char *opname); @@ -79,7 +79,7 @@ bool WM_keymap_remove(struct wmKeyConfig *keyconfig, struct wmKeyMap *keymap); bool WM_keymap_poll(struct bContext *C, struct wmKeyMap *keymap); wmKeyMapItem *WM_keymap_item_find_id(struct wmKeyMap *keymap, int id); -int WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2); +bool WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2); /* Modal Keymap */ @@ -130,4 +130,3 @@ const char *WM_bool_as_string(bool test); #endif #endif /* __WM_KEYMAP_H__ */ - diff --git a/source/blender/windowmanager/WM_types.h b/source/blender/windowmanager/WM_types.h index 8c53f5389e32..918188117ebf 100644 --- a/source/blender/windowmanager/WM_types.h +++ b/source/blender/windowmanager/WM_types.h @@ -261,7 +261,6 @@ typedef struct wmNotifier { /* NC_SCREEN screen */ #define ND_SCREENBROWSE (1<<16) #define ND_SCREENDELETE (2<<16) -#define ND_SCREENCAST (3<<16) #define ND_ANIMPLAY (4<<16) #define ND_GPENCIL (5<<16) #define ND_EDITOR_CHANGED (6<<16) /*sent to new editors after switching to them*/ @@ -570,7 +569,13 @@ typedef struct wmOperatorType { /* verify if the operator can be executed in the current context, note * that the operator might still fail to execute even if this return true */ - int (*poll)(struct bContext *) ATTR_WARN_UNUSED_RESULT; + bool (*poll)(struct bContext *) ATTR_WARN_UNUSED_RESULT; + + /* Use to check of properties should be displayed in auto-generated UI. + * Use 'check' callback to enforce refreshing. */ + bool (*poll_property)( + const struct bContext *C, struct wmOperator *op, + const PropertyRNA *prop) ATTR_WARN_UNUSED_RESULT; /* optional panel for redo and repeat, autogenerated if not set */ void (*ui)(struct bContext *, struct wmOperator *); @@ -592,7 +597,7 @@ typedef struct wmOperatorType { struct wmKeyMap *modalkeymap; /* python needs the operator type as well */ - int (*pyop_poll)(struct bContext *, struct wmOperatorType *ot) ATTR_WARN_UNUSED_RESULT; + bool (*pyop_poll)(struct bContext *, struct wmOperatorType *ot) ATTR_WARN_UNUSED_RESULT; /* RNA integration */ ExtensionRNA ext; @@ -662,7 +667,7 @@ typedef struct wmDropBox { struct wmDropBox *next, *prev; /* test if the dropbox is active, then can print optype name */ - int (*poll)(struct bContext *, struct wmDrag *, const wmEvent *); + bool (*poll)(struct bContext *, struct wmDrag *, const wmEvent *); /* before exec, this copies drag info to wmDrop properties */ void (*copy)(struct wmDrag *, struct wmDropBox *); @@ -715,4 +720,3 @@ extern struct CLG_LogRef *WM_LOG_KEYMAPS; #endif #endif /* __WM_TYPES_H__ */ - diff --git a/source/blender/windowmanager/intern/wm.c b/source/blender/windowmanager/intern/wm.c index 98d9edb9f948..132789aade47 100644 --- a/source/blender/windowmanager/intern/wm.c +++ b/source/blender/windowmanager/intern/wm.c @@ -222,130 +222,6 @@ void WM_operator_handlers_clear(wmWindowManager *wm, wmOperatorType *ot) } /* ************ uiListType handling ************** */ - -static GHash *uilisttypes_hash = NULL; - -uiListType *WM_uilisttype_find(const char *idname, bool quiet) -{ - uiListType *ult; - - if (idname[0]) { - ult = BLI_ghash_lookup(uilisttypes_hash, idname); - if (ult) { - return ult; - } - } - - if (!quiet) { - printf("search for unknown uilisttype %s\n", idname); - } - - return NULL; -} - -bool WM_uilisttype_add(uiListType *ult) -{ - BLI_ghash_insert(uilisttypes_hash, ult->idname, ult); - return 1; -} - -void WM_uilisttype_freelink(uiListType *ult) -{ - bool ok; - - ok = BLI_ghash_remove(uilisttypes_hash, ult->idname, NULL, MEM_freeN); - - BLI_assert(ok); - (void)ok; -} - -/* called on initialize WM_init() */ -void WM_uilisttype_init(void) -{ - uilisttypes_hash = BLI_ghash_str_new_ex("uilisttypes_hash gh", 16); -} - -void WM_uilisttype_free(void) -{ - GHashIterator gh_iter; - - GHASH_ITER (gh_iter, uilisttypes_hash) { - uiListType *ult = BLI_ghashIterator_getValue(&gh_iter); - if (ult->ext.free) { - ult->ext.free(ult->ext.data); - } - } - - BLI_ghash_free(uilisttypes_hash, NULL, MEM_freeN); - uilisttypes_hash = NULL; -} - -/* ************ MenuType handling ************** */ - -static GHash *menutypes_hash = NULL; - -MenuType *WM_menutype_find(const char *idname, bool quiet) -{ - MenuType *mt; - - if (idname[0]) { - mt = BLI_ghash_lookup(menutypes_hash, idname); - if (mt) - return mt; - } - - if (!quiet) - printf("search for unknown menutype %s\n", idname); - - return NULL; -} - -bool WM_menutype_add(MenuType *mt) -{ - BLI_ghash_insert(menutypes_hash, mt->idname, mt); - return true; -} - -void WM_menutype_freelink(MenuType *mt) -{ - bool ok; - - ok = BLI_ghash_remove(menutypes_hash, mt->idname, NULL, MEM_freeN); - - BLI_assert(ok); - (void)ok; -} - -/* called on initialize WM_init() */ -void WM_menutype_init(void) -{ - /* reserve size is set based on blender default setup */ - menutypes_hash = BLI_ghash_str_new_ex("menutypes_hash gh", 512); -} - -void WM_menutype_free(void) -{ - GHashIterator gh_iter; - - GHASH_ITER (gh_iter, menutypes_hash) { - MenuType *mt = BLI_ghashIterator_getValue(&gh_iter); - if (mt->ext.free) { - mt->ext.free(mt->ext.data); - } - } - - BLI_ghash_free(menutypes_hash, NULL, MEM_freeN); - menutypes_hash = NULL; -} - -bool WM_menutype_poll(bContext *C, MenuType *mt) -{ - if (mt->poll != NULL) { - return mt->poll(C, mt); - } - return true; -} - /* ****************************************** */ void WM_keymap_init(bContext *C) @@ -529,5 +405,3 @@ void WM_main(bContext *C) wm_draw_update(C); } } - - diff --git a/source/blender/windowmanager/intern/wm_dragdrop.c b/source/blender/windowmanager/intern/wm_dragdrop.c index 7a5e3e901664..8bb4bf4f3044 100644 --- a/source/blender/windowmanager/intern/wm_dragdrop.c +++ b/source/blender/windowmanager/intern/wm_dragdrop.c @@ -95,8 +95,9 @@ ListBase *WM_dropboxmap_find(const char *idname, int spaceid, int regionid) -wmDropBox *WM_dropbox_add(ListBase *lb, const char *idname, int (*poll)(bContext *, wmDrag *, const wmEvent *), - void (*copy)(wmDrag *, wmDropBox *)) +wmDropBox *WM_dropbox_add( + ListBase *lb, const char *idname, bool (*poll)(bContext *, wmDrag *, const wmEvent *), + void (*copy)(wmDrag *, wmDropBox *)) { wmDropBox *drop = MEM_callocN(sizeof(wmDropBox), "wmDropBox"); diff --git a/source/blender/windowmanager/intern/wm_draw.c b/source/blender/windowmanager/intern/wm_draw.c index aa89cd6d1ef1..d18337ee80cc 100644 --- a/source/blender/windowmanager/intern/wm_draw.c +++ b/source/blender/windowmanager/intern/wm_draw.c @@ -948,6 +948,7 @@ void WM_paint_cursor_tag_redraw(wmWindow *win, ARegion *ar) void wm_draw_update(bContext *C) { + Main *bmain = CTX_data_main(C); wmWindowManager *wm = CTX_wm_manager(C); wmWindow *win; @@ -955,7 +956,7 @@ void wm_draw_update(bContext *C) BKE_subsurf_free_unused_buffers(); #endif - GPU_free_unused_buffers(); + GPU_free_unused_buffers(bmain); for (win = wm->windows.first; win; win = win->next) { #ifdef WIN32 @@ -1068,4 +1069,3 @@ void WM_redraw_windows(bContext *C) CTX_wm_area_set(C, area_prev); CTX_wm_region_set(C, ar_prev); } - diff --git a/source/blender/windowmanager/intern/wm_event_system.c b/source/blender/windowmanager/intern/wm_event_system.c index 7e26ffa52f81..3a3008777507 100644 --- a/source/blender/windowmanager/intern/wm_event_system.c +++ b/source/blender/windowmanager/intern/wm_event_system.c @@ -451,7 +451,7 @@ static int wm_handler_ui_call(bContext *C, wmEventHandler *handler, const wmEven /* UI code doesn't handle return values - it just always returns break. * to make the DBL_CLICK conversion work, we just don't send this to UI, except mouse clicks */ if (((handler->flag & WM_HANDLER_ACCEPT_DBL_CLICK) == 0) && - (event->type != LEFTMOUSE) && + !ISMOUSE_BUTTON(event->type) && (event->val == KM_DBL_CLICK)) { return WM_HANDLER_CONTINUE; @@ -520,7 +520,7 @@ static void wm_handler_ui_cancel(bContext *C) /* ********************* operators ******************* */ -int WM_operator_poll(bContext *C, wmOperatorType *ot) +bool WM_operator_poll(bContext *C, wmOperatorType *ot) { wmOperatorTypeMacro *otmacro; @@ -541,7 +541,7 @@ int WM_operator_poll(bContext *C, wmOperatorType *ot) } /* sets up the new context and calls 'wm_operator_invoke()' with poll_only */ -int WM_operator_poll_context(bContext *C, wmOperatorType *ot, short context) +bool WM_operator_poll_context(bContext *C, wmOperatorType *ot, short context) { return wm_operator_call_internal(C, ot, NULL, NULL, context, true); } @@ -2327,6 +2327,7 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers) } } else if (event->val == KM_DBL_CLICK) { + /* The underlying event is a press, so try and handle this. */ event->val = KM_PRESS; action |= wm_handlers_do_intern(C, event, handlers); @@ -3569,7 +3570,7 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U /* if previous event was same type, and previous was release, and now it presses... */ if (wm_event_is_double_click(&event, evt)) { CLOG_INFO(WM_LOG_HANDLERS, 1, "Send double click"); - evt->val = event.val = KM_DBL_CLICK; + event.val = KM_DBL_CLICK; } /* this case happens on holding a key pressed, it should not generate diff --git a/source/blender/windowmanager/intern/wm_files.c b/source/blender/windowmanager/intern/wm_files.c index d110f7cd3ed7..477699fccaaa 100644 --- a/source/blender/windowmanager/intern/wm_files.c +++ b/source/blender/windowmanager/intern/wm_files.c @@ -64,7 +64,6 @@ #include "BLF_api.h" -#include "DNA_mesh_types.h" /* only for USE_BMESH_SAVE_AS_COMPAT */ #include "DNA_object_types.h" #include "DNA_space_types.h" #include "DNA_userdef_types.h" @@ -344,8 +343,6 @@ static void wm_init_userdef(Main *bmain, const bool read_userdef_from_memory) /* update tempdir from user preferences */ BKE_tempdir_init(U.tempdir); - - BLF_antialias_set((U.text_render & USER_TEXT_DISABLE_AA) == 0); } @@ -641,6 +638,33 @@ bool WM_file_read(bContext *C, const char *filepath, ReportList *reports) } +struct { + char app_template[64]; + bool override; +} wm_init_state_app_template = {0}; + +/** + * Used for setting app-template from the command line: + * - non-empty string: overrides. + * - empty string: override, using no app template. + * - NULL: clears override. + */ +void WM_init_state_app_template_set(const char *app_template) +{ + if (app_template) { + STRNCPY(wm_init_state_app_template.app_template, app_template); + wm_init_state_app_template.override = true; + } + else { + wm_init_state_app_template.app_template[0] = '\0'; + wm_init_state_app_template.override = false; + } +} + +const char *WM_init_state_app_template_get(void) +{ + return wm_init_state_app_template.override ? wm_init_state_app_template.app_template : NULL; +} /** * Called on startup, (context entirely filled with NULLs) @@ -749,7 +773,10 @@ int wm_homefile_read( } if ((app_template != NULL) && (app_template[0] != '\0')) { - BKE_appdir_app_template_id_search(app_template, app_template_system, sizeof(app_template_system)); + if (!BKE_appdir_app_template_id_search(app_template, app_template_system, sizeof(app_template_system))) { + /* Can safely continue with code below, just warn it's not found. */ + BKE_reportf(reports, RPT_WARNING, "Application Template '%s' not found.", app_template); + } /* Insert template name into startup file. */ @@ -1087,7 +1114,7 @@ bool write_crash_blend(void) int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on crash file */ BLI_strncpy(path, BKE_main_blendfile_path_from_global(), sizeof(path)); - BLI_replace_extension(path, sizeof(path), "_crash.blend"); + BLI_path_extension_replace(path, sizeof(path), "_crash.blend"); if (BLO_write_file(G_MAIN, path, fileflags, NULL, NULL)) { printf("written: %s\n", path); return 1; @@ -1617,9 +1644,13 @@ static int wm_homefile_read_exec(bContext *C, wmOperator *op) /* Always load preferences when switching templates. */ use_userdef = true; + + /* Turn override off, since we're explicitly loading a different app-template. */ + WM_init_state_app_template_set(NULL); } else { - app_template = NULL; + /* Normally NULL, only set when overriding from the command-line. */ + app_template = WM_init_state_app_template_get(); } if (wm_homefile_read(C, op->reports, use_factory_settings, use_empty_data, use_userdef, filepath, app_template)) { @@ -1882,7 +1913,7 @@ static int wm_revert_mainfile_exec(bContext *C, wmOperator *op) } } -static int wm_revert_mainfile_poll(bContext *UNUSED(C)) +static bool wm_revert_mainfile_poll(bContext *UNUSED(C)) { return G.relbase_valid; } @@ -2088,16 +2119,6 @@ static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op) RNA_boolean_get(op->ptr, "copy")), G_FILE_SAVE_COPY); -#ifdef USE_BMESH_SAVE_AS_COMPAT - SET_FLAG_FROM_TEST( - fileflags, - (RNA_struct_find_property(op->ptr, "use_mesh_compat") && - RNA_boolean_get(op->ptr, "use_mesh_compat")), - G_FILE_MESH_COMPAT); -#else -# error "don't remove by accident" -#endif - if (wm_file_write(C, path, fileflags, op->reports) != 0) return OPERATOR_CANCELLED; @@ -2116,9 +2137,9 @@ static bool blend_save_check(bContext *UNUSED(C), wmOperator *op) char filepath[FILE_MAX]; RNA_string_get(op->ptr, "filepath", filepath); if (!BLO_has_bfile_extension(filepath)) { - /* some users would prefer BLI_replace_extension(), + /* some users would prefer BLI_path_extension_replace(), * we keep getting nitpicking bug reports about this - campbell */ - BLI_ensure_extension(filepath, FILE_MAX, ".blend"); + BLI_path_extension_ensure(filepath, FILE_MAX, ".blend"); RNA_string_set(op->ptr, "filepath", filepath); return true; } @@ -2147,11 +2168,6 @@ void WM_OT_save_as_mainfile(wmOperatorType *ot) prop = RNA_def_boolean(ot->srna, "copy", false, "Save Copy", "Save a copy of the actual working state but does not make saved file active"); RNA_def_property_flag(prop, PROP_SKIP_SAVE); -#ifdef USE_BMESH_SAVE_AS_COMPAT - RNA_def_boolean(ot->srna, "use_mesh_compat", false, "Legacy Mesh Format", - "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will " - "be lost (no implicit triangulation)"); -#endif } static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) diff --git a/source/blender/windowmanager/intern/wm_files_link.c b/source/blender/windowmanager/intern/wm_files_link.c index 5a92a3451176..72973d3de56c 100644 --- a/source/blender/windowmanager/intern/wm_files_link.c +++ b/source/blender/windowmanager/intern/wm_files_link.c @@ -87,7 +87,7 @@ /* **************** link/append *************** */ -static int wm_link_append_poll(bContext *C) +static bool wm_link_append_poll(bContext *C) { if (WM_operator_winactive(C)) { /* linking changes active object which is pretty useful in general, @@ -455,7 +455,7 @@ static int wm_link_append_exec(bContext *C, wmOperator *op) } /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */ - GPU_materials_free(); + GPU_materials_free(bmain); /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */ BLI_strncpy(G.lib, root, FILE_MAX); @@ -751,7 +751,7 @@ static void lib_relocate_do( DAG_scene_relations_rebuild(bmain, scene); /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */ - GPU_materials_free(); + GPU_materials_free(bmain); } void WM_lib_reload(Library *lib, bContext *C, ReportList *reports) diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c index 839a881acef4..185f7a81ac42 100644 --- a/source/blender/windowmanager/intern/wm_init_exit.c +++ b/source/blender/windowmanager/intern/wm_init_exit.c @@ -166,6 +166,8 @@ void WM_init(bContext *C, int argc, const char **argv) BKE_addon_pref_type_init(); wm_operatortype_init(); + wm_operatortypes_register(); + WM_menutype_init(); WM_uilisttype_init(); @@ -193,8 +195,7 @@ void WM_init(bContext *C, int argc, const char **argv) wm_init_reports(C); /* get the default database, plus a wm */ - wm_homefile_read(C, NULL, G.factory_startup, false, true, NULL, NULL); - + wm_homefile_read(C, NULL, G.factory_startup, false, true, NULL, WM_init_state_app_template_get()); BLT_lang_set(NULL); @@ -207,10 +208,10 @@ void WM_init(bContext *C, int argc, const char **argv) GPU_init(); - GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + GPU_set_mipmap(G_MAIN, !(U.gameflags & USER_DISABLE_MIPMAP)); GPU_set_linear_mipmap(true); - GPU_set_anisotropic(U.anisotropic_filter); - GPU_set_gpu_mipmapping(U.use_gpu_mipmap); + GPU_set_anisotropic(G_MAIN, U.anisotropic_filter); + GPU_set_gpu_mipmapping(G_MAIN, U.use_gpu_mipmap); #ifdef WITH_OPENSUBDIV BKE_subsurf_osd_init(); @@ -590,7 +591,7 @@ void WM_exit_ext(bContext *C, const bool do_python) #endif GPU_global_buffer_pool_free(); - GPU_free_unused_buffers(); + GPU_free_unused_buffers(G_MAIN); GPU_exit(); } diff --git a/source/blender/windowmanager/intern/wm_jobs.c b/source/blender/windowmanager/intern/wm_jobs.c index 3a4195ae1aef..dd9e7edf4135 100644 --- a/source/blender/windowmanager/intern/wm_jobs.c +++ b/source/blender/windowmanager/intern/wm_jobs.c @@ -500,7 +500,7 @@ void WM_jobs_kill_type(struct wmWindowManager *wm, void *owner, int job_type) next_job = wm_job->next; if (!owner || wm_job->owner == owner) - if (wm_job->job_type == job_type) + if (job_type == WM_JOB_TYPE_ANY || wm_job->job_type == job_type) wm_jobs_kill_job(wm, wm_job); } } diff --git a/source/blender/windowmanager/intern/wm_keymap.c b/source/blender/windowmanager/intern/wm_keymap.c index 8b166a9364f3..ccf06155f258 100644 --- a/source/blender/windowmanager/intern/wm_keymap.c +++ b/source/blender/windowmanager/intern/wm_keymap.c @@ -771,7 +771,7 @@ wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int return NULL; } -wmKeyMap *WM_keymap_find(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid) +wmKeyMap *WM_keymap_ensure(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid) { wmKeyMap *km = WM_keymap_list_find(&keyconf->keymaps, idname, spaceid, regionid); @@ -798,7 +798,7 @@ wmKeyMap *WM_keymap_find_all(const bContext *C, const char *idname, int spaceid, wmKeyMap *WM_modalkeymap_add(wmKeyConfig *keyconf, const char *idname, const EnumPropertyItem *items) { - wmKeyMap *km = WM_keymap_find(keyconf, idname, 0, 0); + wmKeyMap *km = WM_keymap_ensure(keyconf, idname, 0, 0); km->flag |= KEYMAP_MODAL; km->modal_items = items; @@ -1346,7 +1346,7 @@ wmKeyMapItem *WM_key_event_operator( return wm_keymap_item_find(C, opname, opcontext, properties, is_hotkey, true, r_keymap); } -int WM_keymap_item_compare(wmKeyMapItem *k1, wmKeyMapItem *k2) +bool WM_keymap_item_compare(wmKeyMapItem *k1, wmKeyMapItem *k2) { int k1type, k2type; diff --git a/source/blender/windowmanager/intern/wm_menu_type.c b/source/blender/windowmanager/intern/wm_menu_type.c new file mode 100644 index 000000000000..58e85716bf14 --- /dev/null +++ b/source/blender/windowmanager/intern/wm_menu_type.c @@ -0,0 +1,105 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/windowmanager/intern/wm_menu_type.c + * \ingroup wm + * + * Menu Registry. + */ + +#include "BLI_sys_types.h" + +#include "DNA_windowmanager_types.h" + +#include "MEM_guardedalloc.h" + +#include "BLI_utildefines.h" +#include "BLI_ghash.h" + +#include "BKE_context.h" +#include "BKE_library.h" +#include "BKE_screen.h" + +#include "WM_api.h" +#include "WM_types.h" + +static GHash *menutypes_hash = NULL; + +MenuType *WM_menutype_find(const char *idname, bool quiet) +{ + MenuType *mt; + + if (idname[0]) { + mt = BLI_ghash_lookup(menutypes_hash, idname); + if (mt) + return mt; + } + + if (!quiet) + printf("search for unknown menutype %s\n", idname); + + return NULL; +} + +bool WM_menutype_add(MenuType *mt) +{ + BLI_ghash_insert(menutypes_hash, mt->idname, mt); + return true; +} + +void WM_menutype_freelink(MenuType *mt) +{ + bool ok; + + ok = BLI_ghash_remove(menutypes_hash, mt->idname, NULL, MEM_freeN); + + BLI_assert(ok); + (void)ok; +} + +/* called on initialize WM_init() */ +void WM_menutype_init(void) +{ + /* reserve size is set based on blender default setup */ + menutypes_hash = BLI_ghash_str_new_ex("menutypes_hash gh", 512); +} + +void WM_menutype_free(void) +{ + GHashIterator gh_iter; + + GHASH_ITER (gh_iter, menutypes_hash) { + MenuType *mt = BLI_ghashIterator_getValue(&gh_iter); + if (mt->ext.free) { + mt->ext.free(mt->ext.data); + } + } + + BLI_ghash_free(menutypes_hash, NULL, MEM_freeN); + menutypes_hash = NULL; +} + +bool WM_menutype_poll(bContext *C, MenuType *mt) +{ + if (mt->poll != NULL) { + return mt->poll(C, mt); + } + return true; +} diff --git a/source/blender/windowmanager/intern/wm_operator_props.c b/source/blender/windowmanager/intern/wm_operator_props.c index 8e2f41c49e0c..cfad1db132cd 100644 --- a/source/blender/windowmanager/intern/wm_operator_props.c +++ b/source/blender/windowmanager/intern/wm_operator_props.c @@ -356,9 +356,9 @@ void WM_operator_properties_checker_interval(wmOperatorType *ot, bool nth_can_di { const int nth_default = nth_can_disable ? 1 : 2; const int nth_min = min_ii(nth_default, 2); - RNA_def_int(ot->srna, "nth", nth_default, nth_min, INT_MAX, "Nth Selection", "", nth_min, 100); - RNA_def_int(ot->srna, "skip", 1, 1, INT_MAX, "Skip", "", 1, 100); - RNA_def_int(ot->srna, "offset", 0, INT_MIN, INT_MAX, "Offset", "", -100, 100); + RNA_def_int(ot->srna, "nth", nth_default, nth_min, INT_MAX, "Nth Element", "Skip every Nth element", nth_min, 100); + RNA_def_int(ot->srna, "skip", 1, 1, INT_MAX, "Skip", "Number of elements to skip at once", 1, 100); + RNA_def_int(ot->srna, "offset", 0, INT_MIN, INT_MAX, "Offset", "Offset from the starting point", -100, 100); } void WM_operator_properties_checker_interval_from_op( diff --git a/source/blender/windowmanager/intern/wm_operator_type.c b/source/blender/windowmanager/intern/wm_operator_type.c new file mode 100644 index 000000000000..25ca84f3d571 --- /dev/null +++ b/source/blender/windowmanager/intern/wm_operator_type.c @@ -0,0 +1,509 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/windowmanager/intern/wm_operator_type.c + * \ingroup wm + * + * Operator Registry. + */ + +#include "MEM_guardedalloc.h" + +#include "CLG_log.h" + +#include "DNA_ID.h" +#include "DNA_screen_types.h" +#include "DNA_scene_types.h" +#include "DNA_userdef_types.h" +#include "DNA_windowmanager_types.h" + +#include "BLT_translation.h" + +#include "BLI_blenlib.h" +#include "BLI_utildefines.h" +#include "BLI_ghash.h" + +#include "BKE_context.h" +#include "BKE_idprop.h" +#include "BKE_library.h" + +#include "RNA_access.h" +#include "RNA_define.h" + +#include "WM_api.h" +#include "WM_types.h" + +#include "wm.h" +#include "wm_event_system.h" + +#define UNDOCUMENTED_OPERATOR_TIP N_("(undocumented operator)") + +static void wm_operatortype_free_macro(wmOperatorType *ot); + +/* -------------------------------------------------------------------- */ +/** \name Operator Type Registry + * \{ */ + +static GHash *global_ops_hash = NULL; + +wmOperatorType *WM_operatortype_find(const char *idname, bool quiet) +{ + if (idname[0]) { + wmOperatorType *ot; + + /* needed to support python style names without the _OT_ syntax */ + char idname_bl[OP_MAX_TYPENAME]; + WM_operator_bl_idname(idname_bl, idname); + + ot = BLI_ghash_lookup(global_ops_hash, idname_bl); + if (ot) { + return ot; + } + + if (!quiet) { + CLOG_INFO(WM_LOG_OPERATORS, 0, "search for unknown operator '%s', '%s'\n", idname_bl, idname); + } + } + else { + if (!quiet) { + CLOG_INFO(WM_LOG_OPERATORS, 0, "search for empty operator"); + } + } + + return NULL; +} + +/* caller must free */ +void WM_operatortype_iter(GHashIterator *ghi) +{ + BLI_ghashIterator_init(ghi, global_ops_hash); +} + +/** \} */ + +/** \name Operator Type Append + * \{ */ + +/* all ops in 1 list (for time being... needs evaluation later) */ +void WM_operatortype_append(void (*opfunc)(wmOperatorType *)) +{ + wmOperatorType *ot; + + ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); + ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); + /* Set the default i18n context now, so that opfunc can redefine it if needed! */ + RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); + ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; + opfunc(ot); + + if (ot->name == NULL) { + CLOG_ERROR(WM_LOG_OPERATORS, "Operator '%s' has no name property", ot->idname); + } + + /* XXX All ops should have a description but for now allow them not to. */ + RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP); + RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); + + BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); +} + +void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata) +{ + wmOperatorType *ot; + + ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); + ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); + /* Set the default i18n context now, so that opfunc can redefine it if needed! */ + RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); + ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; + opfunc(ot, userdata); + RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP); + RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); + + BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); +} + + +/* called on initialize WM_exit() */ +void WM_operatortype_remove_ptr(wmOperatorType *ot) +{ + BLI_assert(ot == WM_operatortype_find(ot->idname, false)); + + RNA_struct_free(&BLENDER_RNA, ot->srna); + + if (ot->last_properties) { + IDP_FreeProperty(ot->last_properties); + MEM_freeN(ot->last_properties); + } + + if (ot->macro.first) + wm_operatortype_free_macro(ot); + + BLI_ghash_remove(global_ops_hash, ot->idname, NULL, NULL); + + WM_keyconfig_update_operatortype(); + + MEM_freeN(ot); +} + +bool WM_operatortype_remove(const char *idname) +{ + wmOperatorType *ot = WM_operatortype_find(idname, 0); + + if (ot == NULL) + return false; + + WM_operatortype_remove_ptr(ot); + + return true; +} + +/* called on initialize WM_init() */ +void wm_operatortype_init(void) +{ + /* reserve size is set based on blender default setup */ + global_ops_hash = BLI_ghash_str_new_ex("wm_operatortype_init gh", 2048); +} + +static void operatortype_ghash_free_cb(wmOperatorType *ot) +{ + if (ot->last_properties) { + IDP_FreeProperty(ot->last_properties); + MEM_freeN(ot->last_properties); + } + + if (ot->macro.first) + wm_operatortype_free_macro(ot); + + if (ot->ext.srna) /* python operator, allocs own string */ + MEM_freeN((void *)ot->idname); + + MEM_freeN(ot); +} + +void wm_operatortype_free(void) +{ + BLI_ghash_free(global_ops_hash, NULL, (GHashValFreeFP)operatortype_ghash_free_cb); + global_ops_hash = NULL; +} + +/** + * Remove memory of all previously executed tools. + */ +void WM_operatortype_last_properties_clear_all(void) +{ + GHashIterator iter; + + for (WM_operatortype_iter(&iter); + (!BLI_ghashIterator_done(&iter)); + (BLI_ghashIterator_step(&iter))) + { + wmOperatorType *ot = BLI_ghashIterator_getValue(&iter); + + if (ot->last_properties) { + IDP_FreeProperty(ot->last_properties); + MEM_freeN(ot->last_properties); + ot->last_properties = NULL; + } + } +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Operator Macro Type + * \{ */ + +typedef struct { + int retval; +} MacroData; + +static void wm_macro_start(wmOperator *op) +{ + if (op->customdata == NULL) { + op->customdata = MEM_callocN(sizeof(MacroData), "MacroData"); + } +} + +static int wm_macro_end(wmOperator *op, int retval) +{ + if (retval & OPERATOR_CANCELLED) { + MacroData *md = op->customdata; + + if (md->retval & OPERATOR_FINISHED) { + retval |= OPERATOR_FINISHED; + retval &= ~OPERATOR_CANCELLED; + } + } + + /* if modal is ending, free custom data */ + if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) { + if (op->customdata) { + MEM_freeN(op->customdata); + op->customdata = NULL; + } + } + + return retval; +} + +/* macro exec only runs exec calls */ +static int wm_macro_exec(bContext *C, wmOperator *op) +{ + wmOperator *opm; + int retval = OPERATOR_FINISHED; + + wm_macro_start(op); + + for (opm = op->macro.first; opm; opm = opm->next) { + + if (opm->type->exec) { + retval = opm->type->exec(C, opm); + OPERATOR_RETVAL_CHECK(retval); + + if (retval & OPERATOR_FINISHED) { + MacroData *md = op->customdata; + md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ + } + else { + break; /* operator didn't finish, end macro */ + } + } + else { + CLOG_WARN(WM_LOG_OPERATORS, "'%s' cant exec macro", opm->type->idname); + } + } + + return wm_macro_end(op, retval); +} + +static int wm_macro_invoke_internal(bContext *C, wmOperator *op, const wmEvent *event, wmOperator *opm) +{ + int retval = OPERATOR_FINISHED; + + /* start from operator received as argument */ + for (; opm; opm = opm->next) { + if (opm->type->invoke) + retval = opm->type->invoke(C, opm, event); + else if (opm->type->exec) + retval = opm->type->exec(C, opm); + + OPERATOR_RETVAL_CHECK(retval); + + BLI_movelisttolist(&op->reports->list, &opm->reports->list); + + if (retval & OPERATOR_FINISHED) { + MacroData *md = op->customdata; + md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ + } + else { + break; /* operator didn't finish, end macro */ + } + } + + return wm_macro_end(op, retval); +} + +static int wm_macro_invoke(bContext *C, wmOperator *op, const wmEvent *event) +{ + wm_macro_start(op); + return wm_macro_invoke_internal(C, op, event, op->macro.first); +} + +static int wm_macro_modal(bContext *C, wmOperator *op, const wmEvent *event) +{ + wmOperator *opm = op->opm; + int retval = OPERATOR_FINISHED; + + if (opm == NULL) { + CLOG_ERROR(WM_LOG_OPERATORS, "macro error, calling NULL modal()"); + } + else { + retval = opm->type->modal(C, opm, event); + OPERATOR_RETVAL_CHECK(retval); + + /* if we're halfway through using a tool and cancel it, clear the options [#37149] */ + if (retval & OPERATOR_CANCELLED) { + WM_operator_properties_clear(opm->ptr); + } + + /* if this one is done but it's not the last operator in the macro */ + if ((retval & OPERATOR_FINISHED) && opm->next) { + MacroData *md = op->customdata; + + md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ + + retval = wm_macro_invoke_internal(C, op, event, opm->next); + + /* if new operator is modal and also added its own handler */ + if (retval & OPERATOR_RUNNING_MODAL && op->opm != opm) { + wmWindow *win = CTX_wm_window(C); + wmEventHandler *handler; + + handler = BLI_findptr(&win->modalhandlers, op, offsetof(wmEventHandler, op)); + if (handler) { + BLI_remlink(&win->modalhandlers, handler); + wm_event_free_handler(handler); + } + + /* if operator is blocking, grab cursor + * This may end up grabbing twice, but we don't care. + * */ + if (op->opm->type->flag & OPTYPE_BLOCKING) { + int bounds[4] = {-1, -1, -1, -1}; + const bool wrap = ( + (U.uiflag & USER_CONTINUOUS_MOUSE) && + ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR))); + + if (wrap) { + ARegion *ar = CTX_wm_region(C); + if (ar) { + bounds[0] = ar->winrct.xmin; + bounds[1] = ar->winrct.ymax; + bounds[2] = ar->winrct.xmax; + bounds[3] = ar->winrct.ymin; + } + } + + WM_cursor_grab_enable(win, wrap, false, bounds); + } + } + } + } + + return wm_macro_end(op, retval); +} + +static void wm_macro_cancel(bContext *C, wmOperator *op) +{ + /* call cancel on the current modal operator, if any */ + if (op->opm && op->opm->type->cancel) { + op->opm->type->cancel(C, op->opm); + } + + wm_macro_end(op, OPERATOR_CANCELLED); +} + +/* Names have to be static for now */ +wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag) +{ + wmOperatorType *ot; + const char *i18n_context; + + if (WM_operatortype_find(idname, true)) { + CLOG_ERROR(WM_LOG_OPERATORS, "operator %s exists, cannot create macro", idname); + return NULL; + } + + ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); + ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); + + ot->idname = idname; + ot->name = name; + ot->description = description; + ot->flag = OPTYPE_MACRO | flag; + + ot->exec = wm_macro_exec; + ot->invoke = wm_macro_invoke; + ot->modal = wm_macro_modal; + ot->cancel = wm_macro_cancel; + ot->poll = NULL; + + if (!ot->description) /* XXX All ops should have a description but for now allow them not to. */ + ot->description = UNDOCUMENTED_OPERATOR_TIP; + + RNA_def_struct_ui_text(ot->srna, ot->name, ot->description); + RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); + /* Use i18n context from ext.srna if possible (py operators). */ + i18n_context = ot->ext.srna ? RNA_struct_translation_context(ot->ext.srna) : BLT_I18NCONTEXT_OPERATOR_DEFAULT; + RNA_def_struct_translation_context(ot->srna, i18n_context); + ot->translation_context = i18n_context; + + BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); + + return ot; +} + +void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata) +{ + wmOperatorType *ot; + + ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); + ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); + + ot->flag = OPTYPE_MACRO; + ot->exec = wm_macro_exec; + ot->invoke = wm_macro_invoke; + ot->modal = wm_macro_modal; + ot->cancel = wm_macro_cancel; + ot->poll = NULL; + + if (!ot->description) + ot->description = UNDOCUMENTED_OPERATOR_TIP; + + /* Set the default i18n context now, so that opfunc can redefine it if needed! */ + RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); + ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; + opfunc(ot, userdata); + + RNA_def_struct_ui_text(ot->srna, ot->name, ot->description); + RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); + + BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); +} + +wmOperatorTypeMacro *WM_operatortype_macro_define(wmOperatorType *ot, const char *idname) +{ + wmOperatorTypeMacro *otmacro = MEM_callocN(sizeof(wmOperatorTypeMacro), "wmOperatorTypeMacro"); + + BLI_strncpy(otmacro->idname, idname, OP_MAX_TYPENAME); + + /* do this on first use, since operatordefinitions might have been not done yet */ + WM_operator_properties_alloc(&(otmacro->ptr), &(otmacro->properties), idname); + WM_operator_properties_sanitize(otmacro->ptr, 1); + + BLI_addtail(&ot->macro, otmacro); + + { + /* operator should always be found but in the event its not. don't segfault */ + wmOperatorType *otsub = WM_operatortype_find(idname, 0); + if (otsub) { + RNA_def_pointer_runtime(ot->srna, otsub->idname, otsub->srna, + otsub->name, otsub->description); + } + } + + return otmacro; +} + +static void wm_operatortype_free_macro(wmOperatorType *ot) +{ + wmOperatorTypeMacro *otmacro; + + for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) { + if (otmacro->ptr) { + WM_operator_properties_free(otmacro->ptr); + MEM_freeN(otmacro->ptr); + } + } + BLI_freelistN(&ot->macro); +} + +/** \} */ diff --git a/source/blender/windowmanager/intern/wm_operators.c b/source/blender/windowmanager/intern/wm_operators.c index 540b3c2c0605..b9f117738a56 100644 --- a/source/blender/windowmanager/intern/wm_operators.c +++ b/source/blender/windowmanager/intern/wm_operators.c @@ -119,416 +119,10 @@ #include "wm_files.h" #include "wm_window.h" -static GHash *global_ops_hash = NULL; - #define UNDOCUMENTED_OPERATOR_TIP N_("(undocumented operator)") /* ************ operator API, exported ********** */ - -wmOperatorType *WM_operatortype_find(const char *idname, bool quiet) -{ - if (idname[0]) { - wmOperatorType *ot; - - /* needed to support python style names without the _OT_ syntax */ - char idname_bl[OP_MAX_TYPENAME]; - WM_operator_bl_idname(idname_bl, idname); - - ot = BLI_ghash_lookup(global_ops_hash, idname_bl); - if (ot) { - return ot; - } - - if (!quiet) { - CLOG_INFO(WM_LOG_OPERATORS, 0, "search for unknown operator '%s', '%s'\n", idname_bl, idname); - } - } - else { - if (!quiet) { - CLOG_INFO(WM_LOG_OPERATORS, 0, "search for empty operator"); - } - } - - return NULL; -} - -/* caller must free */ -void WM_operatortype_iter(GHashIterator *ghi) -{ - BLI_ghashIterator_init(ghi, global_ops_hash); -} - -/* all ops in 1 list (for time being... needs evaluation later) */ -void WM_operatortype_append(void (*opfunc)(wmOperatorType *)) -{ - wmOperatorType *ot; - - ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); - ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); - /* Set the default i18n context now, so that opfunc can redefine it if needed! */ - RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); - ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; - opfunc(ot); - - if (ot->name == NULL) { - CLOG_ERROR(WM_LOG_OPERATORS, "Operator '%s' has no name property", ot->idname); - } - - /* XXX All ops should have a description but for now allow them not to. */ - RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP); - RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); - - BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); -} - -void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata) -{ - wmOperatorType *ot; - - ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); - ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); - /* Set the default i18n context now, so that opfunc can redefine it if needed! */ - RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); - ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; - opfunc(ot, userdata); - RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP); - RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); - - BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); -} - -/* ********************* macro operator ******************** */ - -typedef struct { - int retval; -} MacroData; - -static void wm_macro_start(wmOperator *op) -{ - if (op->customdata == NULL) { - op->customdata = MEM_callocN(sizeof(MacroData), "MacroData"); - } -} - -static int wm_macro_end(wmOperator *op, int retval) -{ - if (retval & OPERATOR_CANCELLED) { - MacroData *md = op->customdata; - - if (md->retval & OPERATOR_FINISHED) { - retval |= OPERATOR_FINISHED; - retval &= ~OPERATOR_CANCELLED; - } - } - - /* if modal is ending, free custom data */ - if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) { - if (op->customdata) { - MEM_freeN(op->customdata); - op->customdata = NULL; - } - } - - return retval; -} - -/* macro exec only runs exec calls */ -static int wm_macro_exec(bContext *C, wmOperator *op) -{ - wmOperator *opm; - int retval = OPERATOR_FINISHED; - - wm_macro_start(op); - - for (opm = op->macro.first; opm; opm = opm->next) { - - if (opm->type->exec) { - retval = opm->type->exec(C, opm); - OPERATOR_RETVAL_CHECK(retval); - - if (retval & OPERATOR_FINISHED) { - MacroData *md = op->customdata; - md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ - } - else { - break; /* operator didn't finish, end macro */ - } - } - else { - CLOG_WARN(WM_LOG_OPERATORS, "'%s' cant exec macro", opm->type->idname); - } - } - - return wm_macro_end(op, retval); -} - -static int wm_macro_invoke_internal(bContext *C, wmOperator *op, const wmEvent *event, wmOperator *opm) -{ - int retval = OPERATOR_FINISHED; - - /* start from operator received as argument */ - for (; opm; opm = opm->next) { - if (opm->type->invoke) - retval = opm->type->invoke(C, opm, event); - else if (opm->type->exec) - retval = opm->type->exec(C, opm); - - OPERATOR_RETVAL_CHECK(retval); - - BLI_movelisttolist(&op->reports->list, &opm->reports->list); - - if (retval & OPERATOR_FINISHED) { - MacroData *md = op->customdata; - md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ - } - else { - break; /* operator didn't finish, end macro */ - } - } - - return wm_macro_end(op, retval); -} - -static int wm_macro_invoke(bContext *C, wmOperator *op, const wmEvent *event) -{ - wm_macro_start(op); - return wm_macro_invoke_internal(C, op, event, op->macro.first); -} - -static int wm_macro_modal(bContext *C, wmOperator *op, const wmEvent *event) -{ - wmOperator *opm = op->opm; - int retval = OPERATOR_FINISHED; - - if (opm == NULL) { - CLOG_ERROR(WM_LOG_OPERATORS, "macro error, calling NULL modal()"); - } - else { - retval = opm->type->modal(C, opm, event); - OPERATOR_RETVAL_CHECK(retval); - - /* if we're halfway through using a tool and cancel it, clear the options [#37149] */ - if (retval & OPERATOR_CANCELLED) { - WM_operator_properties_clear(opm->ptr); - } - - /* if this one is done but it's not the last operator in the macro */ - if ((retval & OPERATOR_FINISHED) && opm->next) { - MacroData *md = op->customdata; - - md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */ - - retval = wm_macro_invoke_internal(C, op, event, opm->next); - - /* if new operator is modal and also added its own handler */ - if (retval & OPERATOR_RUNNING_MODAL && op->opm != opm) { - wmWindow *win = CTX_wm_window(C); - wmEventHandler *handler; - - handler = BLI_findptr(&win->modalhandlers, op, offsetof(wmEventHandler, op)); - if (handler) { - BLI_remlink(&win->modalhandlers, handler); - wm_event_free_handler(handler); - } - - /* if operator is blocking, grab cursor - * This may end up grabbing twice, but we don't care. - * */ - if (op->opm->type->flag & OPTYPE_BLOCKING) { - int bounds[4] = {-1, -1, -1, -1}; - const bool wrap = ( - (U.uiflag & USER_CONTINUOUS_MOUSE) && - ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR))); - - if (wrap) { - ARegion *ar = CTX_wm_region(C); - if (ar) { - bounds[0] = ar->winrct.xmin; - bounds[1] = ar->winrct.ymax; - bounds[2] = ar->winrct.xmax; - bounds[3] = ar->winrct.ymin; - } - } - - WM_cursor_grab_enable(win, wrap, false, bounds); - } - } - } - } - - return wm_macro_end(op, retval); -} - -static void wm_macro_cancel(bContext *C, wmOperator *op) -{ - /* call cancel on the current modal operator, if any */ - if (op->opm && op->opm->type->cancel) { - op->opm->type->cancel(C, op->opm); - } - - wm_macro_end(op, OPERATOR_CANCELLED); -} - -/* Names have to be static for now */ -wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag) -{ - wmOperatorType *ot; - const char *i18n_context; - - if (WM_operatortype_find(idname, true)) { - CLOG_ERROR(WM_LOG_OPERATORS, "operator %s exists, cannot create macro", idname); - return NULL; - } - - ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); - ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); - - ot->idname = idname; - ot->name = name; - ot->description = description; - ot->flag = OPTYPE_MACRO | flag; - - ot->exec = wm_macro_exec; - ot->invoke = wm_macro_invoke; - ot->modal = wm_macro_modal; - ot->cancel = wm_macro_cancel; - ot->poll = NULL; - - if (!ot->description) /* XXX All ops should have a description but for now allow them not to. */ - ot->description = UNDOCUMENTED_OPERATOR_TIP; - - RNA_def_struct_ui_text(ot->srna, ot->name, ot->description); - RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); - /* Use i18n context from ext.srna if possible (py operators). */ - i18n_context = ot->ext.srna ? RNA_struct_translation_context(ot->ext.srna) : BLT_I18NCONTEXT_OPERATOR_DEFAULT; - RNA_def_struct_translation_context(ot->srna, i18n_context); - ot->translation_context = i18n_context; - - BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); - - return ot; -} - -void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata) -{ - wmOperatorType *ot; - - ot = MEM_callocN(sizeof(wmOperatorType), "operatortype"); - ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties); - - ot->flag = OPTYPE_MACRO; - ot->exec = wm_macro_exec; - ot->invoke = wm_macro_invoke; - ot->modal = wm_macro_modal; - ot->cancel = wm_macro_cancel; - ot->poll = NULL; - - if (!ot->description) - ot->description = UNDOCUMENTED_OPERATOR_TIP; - - /* Set the default i18n context now, so that opfunc can redefine it if needed! */ - RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT); - ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT; - opfunc(ot, userdata); - - RNA_def_struct_ui_text(ot->srna, ot->name, ot->description); - RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname); - - BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot); -} - -wmOperatorTypeMacro *WM_operatortype_macro_define(wmOperatorType *ot, const char *idname) -{ - wmOperatorTypeMacro *otmacro = MEM_callocN(sizeof(wmOperatorTypeMacro), "wmOperatorTypeMacro"); - - BLI_strncpy(otmacro->idname, idname, OP_MAX_TYPENAME); - - /* do this on first use, since operatordefinitions might have been not done yet */ - WM_operator_properties_alloc(&(otmacro->ptr), &(otmacro->properties), idname); - WM_operator_properties_sanitize(otmacro->ptr, 1); - - BLI_addtail(&ot->macro, otmacro); - - { - /* operator should always be found but in the event its not. don't segfault */ - wmOperatorType *otsub = WM_operatortype_find(idname, 0); - if (otsub) { - RNA_def_pointer_runtime(ot->srna, otsub->idname, otsub->srna, - otsub->name, otsub->description); - } - } - - return otmacro; -} - -static void wm_operatortype_free_macro(wmOperatorType *ot) -{ - wmOperatorTypeMacro *otmacro; - - for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) { - if (otmacro->ptr) { - WM_operator_properties_free(otmacro->ptr); - MEM_freeN(otmacro->ptr); - } - } - BLI_freelistN(&ot->macro); -} - -void WM_operatortype_remove_ptr(wmOperatorType *ot) -{ - BLI_assert(ot == WM_operatortype_find(ot->idname, false)); - - RNA_struct_free(&BLENDER_RNA, ot->srna); - - if (ot->last_properties) { - IDP_FreeProperty(ot->last_properties); - MEM_freeN(ot->last_properties); - } - - if (ot->macro.first) - wm_operatortype_free_macro(ot); - - BLI_ghash_remove(global_ops_hash, ot->idname, NULL, NULL); - - WM_keyconfig_update_operatortype(); - - MEM_freeN(ot); -} - -bool WM_operatortype_remove(const char *idname) -{ - wmOperatorType *ot = WM_operatortype_find(idname, 0); - - if (ot == NULL) - return false; - - WM_operatortype_remove_ptr(ot); - - return true; -} - -/** - * Remove memory of all previously executed tools. - */ -void WM_operatortype_last_properties_clear_all(void) -{ - GHashIterator iter; - - for (WM_operatortype_iter(&iter); - (!BLI_ghashIterator_done(&iter)); - (BLI_ghashIterator_step(&iter))) - { - wmOperatorType *ot = BLI_ghashIterator_getValue(&iter); - - if (ot->last_properties) { - IDP_FreeProperty(ot->last_properties); - MEM_freeN(ot->last_properties); - ot->last_properties = NULL; - } - } -} - /* SOME_OT_op -> some.op */ void WM_operator_py_idname(char *to, const char *from) { @@ -742,9 +336,8 @@ bool WM_operator_pystring_abbreviate(char *str, int str_len_max) /* return NULL if no match is found */ #if 0 -static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index) +static const char *wm_context_member_from_ptr(bContext *C, PointerRNA *ptr) { - /* loop over all context items and do 2 checks * * - see if the pointer is in the context. @@ -758,13 +351,9 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert const char *member_found = NULL; const char *member_id = NULL; - char *prop_str = NULL; - char *ret = NULL; - - for (link = lb.first; link; link = link->next) { const char *identifier = link->data; - PointerRNA ctx_item_ptr = {{0}} // CTX_data_pointer_get(C, identifier); // XXX, this isnt working + PointerRNA ctx_item_ptr = {{0}}; // CTX_data_pointer_get(C, identifier); // XXX, this isnt working if (ctx_item_ptr.type == NULL) { continue; @@ -785,36 +374,27 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert } } } + BLI_freelistN(&lb); if (member_found) { - prop_str = RNA_path_property_py(ptr, prop, index); - if (prop_str) { - ret = BLI_sprintfN("bpy.context.%s.%s", member_found, prop_str); - MEM_freeN(prop_str); - } + return member_found; } else if (member_id) { - prop_str = RNA_path_struct_property_py(ptr, prop, index); - if (prop_str) { - ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str); - MEM_freeN(prop_str); - } + return member_id; + } + else { + return NULL; } - - BLI_freelistN(&lb); - - return ret; } + #else /* use hard coded checks for now */ -static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index) + +static const char *wm_context_member_from_ptr(bContext *C, PointerRNA *ptr) { const char *member_id = NULL; - char *prop_str = NULL; - char *ret = NULL; - if (ptr->id.data) { #define CTX_TEST_PTR_ID(C, member, idptr) \ @@ -911,23 +491,29 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert default: break; } - - if (member_id) { - prop_str = RNA_path_struct_property_py(ptr, prop, index); - if (prop_str) { - ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str); - MEM_freeN(prop_str); - } - } #undef CTX_TEST_PTR_ID #undef CTX_TEST_PTR_ID_CAST #undef CTX_TEST_SPACE_TYPE } - return ret; + return member_id; } #endif +static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index) +{ + const char *member_id = wm_context_member_from_ptr(C, ptr); + char *ret = NULL; + if (member_id != NULL) { + char *prop_str = RNA_path_struct_property_py(ptr, prop, index); + if (prop_str) { + ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str); + MEM_freeN(prop_str); + } + } + return ret; +} + char *WM_prop_pystring_assign(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index) { char *lhs, *rhs, *ret; @@ -1273,7 +859,7 @@ bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const struct ImageFor } /* op->poll */ -int WM_operator_winactive(bContext *C) +bool WM_operator_winactive(bContext *C) { if (CTX_wm_window(C) == NULL) return 0; return 1; @@ -1410,13 +996,13 @@ static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op) if (op->type->flag & OPTYPE_MACRO) { for (op = op->macro.first; op; op = op->next) { - uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); + uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); if (op->next) uiItemS(layout); } } else { - uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); + uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); } UI_block_bounds_set_popup(block, 4, 0, 0); @@ -1485,7 +1071,7 @@ static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData) layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style); - uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); + uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE); /* clear so the OK button is left alone */ UI_block_func_set(block, NULL, NULL, NULL); @@ -1524,7 +1110,7 @@ static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData) layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style); /* since ui is defined the auto-layout args are not used */ - uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'V', 0); + uiTemplateOperatorPropertyButs(C, layout, op, 'V', 0); UI_block_func_set(block, NULL, NULL, NULL); @@ -1899,8 +1485,7 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar if (mt) { UI_menutype_draw(C, mt, layout); -// wmWindowManager *wm = CTX_wm_manager(C); -// uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE); +// uiItemM(layout, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE); } UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN); @@ -2037,7 +1622,7 @@ static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEv } /* op->poll */ -static int wm_search_menu_poll(bContext *C) +static bool wm_search_menu_poll(bContext *C) { if (CTX_wm_window(C) == NULL) { return 0; @@ -2124,7 +1709,7 @@ static void WM_OT_call_menu_pie(wmOperatorType *ot) /* this poll functions is needed in place of WM_operator_winactive * while it crashes on full screen */ -static int wm_operator_winactive_normal(bContext *C) +static bool wm_operator_winactive_normal(bContext *C) { wmWindow *win = CTX_wm_window(C); @@ -2221,8 +1806,9 @@ static void WM_OT_console_toggle(wmOperatorType *ot) * - draw(bContext): drawing callback for paint cursor */ -void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C), - wmPaintCursorDraw draw, void *customdata) +void *WM_paint_cursor_activate( + wmWindowManager *wm, bool (*poll)(bContext *C), + wmPaintCursorDraw draw, void *customdata) { wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor"); @@ -3465,22 +3051,6 @@ static void WM_OT_doc_view_manual_ui_context(wmOperatorType *ot) /* ******************************************************* */ -static void operatortype_ghash_free_cb(wmOperatorType *ot) -{ - if (ot->last_properties) { - IDP_FreeProperty(ot->last_properties); - MEM_freeN(ot->last_properties); - } - - if (ot->macro.first) - wm_operatortype_free_macro(ot); - - if (ot->ext.srna) /* python operator, allocs own string */ - MEM_freeN((void *)ot->idname); - - MEM_freeN(ot); -} - /* ******************************************************* */ /* toggle 3D for current window, turning it fullscreen if needed */ static void WM_OT_stereo3d_set(wmOperatorType *ot) @@ -3512,20 +3082,8 @@ static void WM_OT_stereo3d_set(wmOperatorType *ot) RNA_def_property_flag(prop, PROP_SKIP_SAVE); } -/* ******************************************************* */ -/* called on initialize WM_exit() */ -void wm_operatortype_free(void) +void wm_operatortypes_register(void) { - BLI_ghash_free(global_ops_hash, NULL, (GHashValFreeFP)operatortype_ghash_free_cb); - global_ops_hash = NULL; -} - -/* called on initialize WM_init() */ -void wm_operatortype_init(void) -{ - /* reserve size is set based on blender default setup */ - global_ops_hash = BLI_ghash_str_new_ex("wm_operatortype_init gh", 2048); - WM_operatortype_append(WM_OT_window_close); WM_operatortype_append(WM_OT_window_duplicate); WM_operatortype_append(WM_OT_read_history); @@ -3762,7 +3320,7 @@ static void gesture_zoom_border_modal_keymap(wmKeyConfig *keyconf) /* default keymap for windows and screens, only call once per WM */ void wm_window_keymap(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_find(keyconf, "Window", 0, 0); + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Window", 0, 0); wmKeyMapItem *kmi; /* note, this doesn't replace existing keymap items */ diff --git a/source/blender/windowmanager/intern/wm_playanim.c b/source/blender/windowmanager/intern/wm_playanim.c index d9d5bf901ca0..f2c24858e170 100644 --- a/source/blender/windowmanager/intern/wm_playanim.c +++ b/source/blender/windowmanager/intern/wm_playanim.c @@ -28,8 +28,11 @@ /** \file blender/windowmanager/intern/wm_playanim.c * \ingroup wm * + * Animation player for image sequences & video's with sound support. + * Launched in a separate process from Blender's #RENDER_OT_play_rendered_anim + * * \note This file uses ghost directly and none of the WM definitions. - * this could be made into its own module, alongside creator/ + * this could be made into its own module, alongside creator. */ #include @@ -132,6 +135,9 @@ typedef struct PlayState { /* restarts player for file drop */ char dropped_file[FILE_MAX]; + + bool need_frame_update; + int frame_cursor_x; } PlayState; /* for debugging */ @@ -548,8 +554,18 @@ static void update_sound_fps(void) #endif } -static void change_frame(PlayState *ps, int cx) +static void tag_change_frame(PlayState *ps, int cx) +{ + ps->need_frame_update = true; + ps->frame_cursor_x = cx; +} + +static void change_frame(PlayState *ps) { + if (!ps->need_frame_update) { + return; + } + int sizex, sizey; int i, i_last; @@ -559,7 +575,7 @@ static void change_frame(PlayState *ps, int cx) playanim_window_get_size(&sizex, &sizey); i_last = ((struct PlayAnimPict *)picsbase.last)->frame; - i = (i_last * cx) / sizex; + i = (i_last * ps->frame_cursor_x) / sizex; CLAMP(i, 0, i_last); #ifdef WITH_AUDASPACE @@ -600,6 +616,8 @@ static void change_frame(PlayState *ps, int cx) ps->sstep = true; ps->wait2 = false; ps->next_frame = 0; + + ps->need_frame_update = false; } static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void) @@ -951,7 +969,7 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void) if (type == GHOST_kEventButtonDown) { if (inside_window) { g_WS.qual |= WS_QUAL_LMOUSE; - change_frame(ps, cx); + tag_change_frame(ps, cx); } } else @@ -996,7 +1014,7 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void) GHOST_ScreenToClient(g_WS.ghost_window, cd->x, cd->y, &cx, &cy); - change_frame(ps, cx); + tag_change_frame(ps, cx); } break; } @@ -1428,23 +1446,18 @@ static char *wm_main_playanim_intern(int argc, const char **argv) ps.next_frame = ps.direction; - while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, ps.wait2))) { - if (hasevent) { - GHOST_DispatchEvents(g_WS.ghost_system); - } - /* Note, this still draws for mousemoves on pause */ - if (ps.wait2) { - if (hasevent) { - if (ibuf) { - while (pupdate_time()) PIL_sleep_ms(1); - ptottime -= swaptime; - playanim_toscreen(&ps, ps.picture, ibuf, ps.fontid, ps.fstep); - } - } - } - if (ps.go == false) { - break; - } + while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, 0))) { + GHOST_DispatchEvents(g_WS.ghost_system); + } + if (ps.go == false) { + break; + } + change_frame(&ps); + if (!hasevent) { + PIL_sleep_ms(1); + } + if (ps.wait2) { + continue; } ps.wait2 = ps.sstep; diff --git a/source/blender/windowmanager/intern/wm_subwindow.c b/source/blender/windowmanager/intern/wm_subwindow.c index 0633122b8db9..214e8bd84cee 100644 --- a/source/blender/windowmanager/intern/wm_subwindow.c +++ b/source/blender/windowmanager/intern/wm_subwindow.c @@ -379,4 +379,3 @@ void wmOrtho2_pixelspace(const float x, const float y) } /* ********** END MY WINDOW ************** */ - diff --git a/source/blender/windowmanager/intern/wm_uilist_type.c b/source/blender/windowmanager/intern/wm_uilist_type.c new file mode 100644 index 000000000000..52619a09218c --- /dev/null +++ b/source/blender/windowmanager/intern/wm_uilist_type.c @@ -0,0 +1,98 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/windowmanager/intern/wm_uilist_type.c + * \ingroup wm + * + * UI List Registry. + */ + +#include "BLI_sys_types.h" + +#include "DNA_windowmanager_types.h" + +#include "MEM_guardedalloc.h" + +#include "BLI_utildefines.h" +#include "BLI_ghash.h" + +#include "BKE_context.h" +#include "BKE_library.h" +#include "BKE_screen.h" + +#include "WM_api.h" +#include "WM_types.h" + +static GHash *uilisttypes_hash = NULL; + +uiListType *WM_uilisttype_find(const char *idname, bool quiet) +{ + uiListType *ult; + + if (idname[0]) { + ult = BLI_ghash_lookup(uilisttypes_hash, idname); + if (ult) { + return ult; + } + } + + if (!quiet) { + printf("search for unknown uilisttype %s\n", idname); + } + + return NULL; +} + +bool WM_uilisttype_add(uiListType *ult) +{ + BLI_ghash_insert(uilisttypes_hash, ult->idname, ult); + return 1; +} + +void WM_uilisttype_freelink(uiListType *ult) +{ + bool ok; + + ok = BLI_ghash_remove(uilisttypes_hash, ult->idname, NULL, MEM_freeN); + + BLI_assert(ok); + (void)ok; +} + +/* called on initialize WM_init() */ +void WM_uilisttype_init(void) +{ + uilisttypes_hash = BLI_ghash_str_new_ex("uilisttypes_hash gh", 16); +} + +void WM_uilisttype_free(void) +{ + GHashIterator gh_iter; + + GHASH_ITER (gh_iter, uilisttypes_hash) { + uiListType *ult = BLI_ghashIterator_getValue(&gh_iter); + if (ult->ext.free) { + ult->ext.free(ult->ext.data); + } + } + + BLI_ghash_free(uilisttypes_hash, NULL, MEM_freeN); + uilisttypes_hash = NULL; +} diff --git a/source/blender/windowmanager/intern/wm_window.c b/source/blender/windowmanager/intern/wm_window.c index b7221d5bb5dc..b529febc86f5 100644 --- a/source/blender/windowmanager/intern/wm_window.c +++ b/source/blender/windowmanager/intern/wm_window.c @@ -719,13 +719,13 @@ void wm_window_ghostwindows_ensure(wmWindowManager *wm) win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state"); /* add keymap handlers (1 handler for all keys in map!) */ - keymap = WM_keymap_find(wm->defaultconf, "Window", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Window", 0, 0); WM_event_add_keymap_handler(&win->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Screen", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Screen", 0, 0); WM_event_add_keymap_handler(&win->handlers, keymap); - keymap = WM_keymap_find(wm->defaultconf, "Screen Editing", 0, 0); + keymap = WM_keymap_ensure(wm->defaultconf, "Screen Editing", 0, 0); WM_event_add_keymap_handler(&win->modalhandlers, keymap); /* add drop boxes */ @@ -1216,11 +1216,6 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr state = GHOST_GetWindowState(win->ghostwin); win->windowstate = state; - /* stop screencast if resize */ - if (type == GHOST_kEventWindowSize) { - WM_jobs_stop(wm, win->screen, NULL); - } - WM_window_set_dpi(win); /* win32: gives undefined window size when minimized */ diff --git a/source/blender/windowmanager/wm.h b/source/blender/windowmanager/wm.h index 42b1b2a5fb4b..5f850a076f0e 100644 --- a/source/blender/windowmanager/wm.h +++ b/source/blender/windowmanager/wm.h @@ -39,7 +39,7 @@ typedef struct wmPaintCursor { void *customdata; - int (*poll)(struct bContext *C); + bool (*poll)(struct bContext *C); void (*draw)(bContext *C, int, int, void *customdata); } wmPaintCursor; @@ -59,6 +59,7 @@ void wm_operator_register(bContext *C, wmOperator *op); void wm_operatortype_free(void); void wm_operatortype_init(void); void wm_window_keymap(wmKeyConfig *keyconf); +void wm_operatortypes_register(void); /* wm_gesture.c */ void wm_gesture_draw(struct wmWindow *win); diff --git a/source/blender/windowmanager/wm_cursors.h b/source/blender/windowmanager/wm_cursors.h index 939409f95112..f863d8bfdd96 100644 --- a/source/blender/windowmanager/wm_cursors.h +++ b/source/blender/windowmanager/wm_cursors.h @@ -115,4 +115,3 @@ bool wm_cursor_arrow_move(struct wmWindow *win, const struct wmEvent *event); #endif /* __WM_CURSORS_H__ */ - diff --git a/source/blender/windowmanager/wm_draw.h b/source/blender/windowmanager/wm_draw.h index bf4a2ae9cbcc..de9ad5997819 100644 --- a/source/blender/windowmanager/wm_draw.h +++ b/source/blender/windowmanager/wm_draw.h @@ -61,4 +61,3 @@ void wm_triple_draw_textures (struct wmWindow *win, struct wmDrawTriple *triple void wm_draw_data_free (struct wmWindow *win); #endif /* __WM_DRAW_H__ */ - diff --git a/source/blender/windowmanager/wm_event_types.h b/source/blender/windowmanager/wm_event_types.h index 2e9722b75e38..55f29ccb0488 100644 --- a/source/blender/windowmanager/wm_event_types.h +++ b/source/blender/windowmanager/wm_event_types.h @@ -458,4 +458,3 @@ enum { #endif /* __WM_EVENT_TYPES_H__ */ - diff --git a/source/blender/windowmanager/wm_files.h b/source/blender/windowmanager/wm_files.h index 80777a904a14..147ed8829666 100644 --- a/source/blender/windowmanager/wm_files.h +++ b/source/blender/windowmanager/wm_files.h @@ -67,4 +67,3 @@ void WM_OT_lib_relocate(struct wmOperatorType *ot); void WM_OT_lib_reload(struct wmOperatorType *ot); #endif /* __WM_FILES_H__ */ - diff --git a/source/blender/windowmanager/wm_subwindow.h b/source/blender/windowmanager/wm_subwindow.h index 1a159d707866..3240ee4a0173 100644 --- a/source/blender/windowmanager/wm_subwindow.h +++ b/source/blender/windowmanager/wm_subwindow.h @@ -49,4 +49,3 @@ void wm_subwindow_rect_get(wmWindow *win, int swinid, struct rcti *r_rect); void wm_subwindow_rect_set(wmWindow *win, int swinid, const rcti *rect); #endif /* __WM_SUBWINDOW_H__ */ - diff --git a/source/blender/windowmanager/wm_window.h b/source/blender/windowmanager/wm_window.h index e00132be42c7..44e415e88327 100644 --- a/source/blender/windowmanager/wm_window.h +++ b/source/blender/windowmanager/wm_window.h @@ -90,4 +90,3 @@ void wm_quit_with_optional_confirmation_prompt(bContext *C, wmWindow *win) ATTR #define WM_WIN_INIT_PAD 40 #endif /* __WM_WINDOW_H__ */ - diff --git a/source/blenderplayer/CMakeLists.txt b/source/blenderplayer/CMakeLists.txt index eed971f006e3..65394cc71259 100644 --- a/source/blenderplayer/CMakeLists.txt +++ b/source/blenderplayer/CMakeLists.txt @@ -119,7 +119,26 @@ endif() bf_blenkernel bf_physics bf_depsgraph + bf_physics + bf_intern_rigidbody + bf_blenloader + ge_blen_routines + bf_editor_datafiles + ge_converter + ge_logic_ketsji + ge_phys_bullet + ge_phys_dummy + ge_logic + ge_rasterizer + ge_oglrasterizer + ge_logic_expressions + ge_scenegraph bf_ikplugin + bf_intern_itasc + bf_intern_iksolver + bf_intern_smoke + bf_modifiers + bf_intern_moto bf_nodes bf_gpu bf_imbuf diff --git a/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt b/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt index 0e570e192581..10df43d72307 100644 --- a/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt +++ b/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt @@ -27,7 +27,7 @@ # this warning on generated files gets annoying remove_strict_flags() -set(INC +set(INC . .. ../../blender/blenlib @@ -39,7 +39,7 @@ set(INC ) set(INC_SYS - + ) set(SRC diff --git a/source/blenderplayer/bad_level_call_stubs/stubs.c b/source/blenderplayer/bad_level_call_stubs/stubs.c index bd19d59a0a62..966acccd334e 100644 --- a/source/blenderplayer/bad_level_call_stubs/stubs.c +++ b/source/blenderplayer/bad_level_call_stubs/stubs.c @@ -238,9 +238,9 @@ void RE_texture_rng_exit() RET_NONE bool RE_layers_have_name(struct RenderResult *result) RET_ZERO const char *RE_engine_active_view_get(struct RenderEngine *engine) RET_NULL void RE_engine_active_view_set(struct RenderEngine *engine, const char *viewname) RET_NONE -void RE_engine_get_camera_model_matrix(struct RenderEngine *engine, struct Object *camera, int use_spherical_stereo, float *r_modelmat) RET_NONE -float RE_engine_get_camera_shift_x(struct RenderEngine *engine, struct Object *camera, int use_spherical_stereo) RET_ZERO -int RE_engine_get_spherical_stereo(struct RenderEngine *engine, struct Object *camera) RET_ZERO +void RE_engine_get_camera_model_matrix(struct RenderEngine *engine, struct Object *camera, bool use_spherical_stereo, float *r_modelmat) RET_NONE +float RE_engine_get_camera_shift_x(struct RenderEngine *engine, struct Object *camera, bool use_spherical_stereo) RET_ZERO +bool RE_engine_get_spherical_stereo(struct RenderEngine *engine, struct Object *camera) RET_ZERO void RE_SetActiveRenderView(struct Render *re, const char *viewname) RET_NONE struct RenderPass *RE_pass_find_by_name(volatile struct RenderLayer *rl, const char *name, const char *viewname) RET_NULL @@ -422,7 +422,7 @@ void PE_current_changed(struct Main *bmain, struct Scene *scene, struct Object * /* rna keymap */ struct wmKeyMap *WM_keymap_active(struct wmWindowManager *wm, struct wmKeyMap *keymap) RET_NULL -struct wmKeyMap *WM_keymap_find(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid) RET_NULL +struct wmKeyMap *WM_keymap_ensure(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid) RET_NULL struct wmKeyMapItem *WM_keymap_add_item(struct wmKeyMap *keymap, const char *idname, int type, int val, int modifier, int keymodifier) RET_NULL struct wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int regionid) RET_NULL struct wmKeyConfig *WM_keyconfig_new(struct wmWindowManager *wm, const char *idname) RET_NULL @@ -435,7 +435,7 @@ void WM_keymap_restore_to_default(struct wmKeyMap *keymap, struct bContext *C) R void WM_keymap_restore_item_to_default(struct bContext *C, struct wmKeyMap *keymap, struct wmKeyMapItem *kmi) RET_NONE void WM_keymap_properties_reset(struct wmKeyMapItem *kmi, struct IDProperty *properties) RET_NONE void WM_keyconfig_update_tag(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi) RET_NONE -int WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2) RET_ZERO +bool WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2) RET_ZERO int WM_keymap_map_type_get(struct wmKeyMapItem *kmi) RET_ZERO @@ -479,7 +479,7 @@ void ED_node_tree_path_get_fixedbuf(struct SpaceNode *snode, char *value, int ma void ED_node_tree_start(struct SpaceNode *snode, struct bNodeTree *ntree, struct ID *id, struct ID *from) RET_NONE void ED_node_tree_push(struct SpaceNode *snode, struct bNodeTree *ntree, struct bNode *gnode) RET_NONE void ED_node_tree_pop(struct SpaceNode *snode) RET_NONE -int ED_view3d_scene_layer_set(int lay, const int *values, int *active) RET_ZERO +int ED_view3d_scene_layer_set(int lay, const bool *values, int *active) RET_ZERO void ED_view3d_quadview_update(struct ScrArea *sa, struct ARegion *ar, bool do_clip) RET_NONE void ED_view3d_from_m4(float mat[4][4], float ofs[3], float quat[4], float *dist) RET_NONE struct BGpic *ED_view3d_background_image_new(struct View3D *v3d) RET_NULL @@ -511,9 +511,9 @@ void uiLayoutSetEnabled(uiLayout *layout, bool enabled) RET_NONE void uiLayoutSetAlignment(uiLayout *layout, char alignment) RET_NONE void uiLayoutSetScaleX(struct uiLayout *layout, float scale) RET_NONE void uiLayoutSetScaleY(struct uiLayout *layout, float scale) RET_NONE -void uiTemplateIconView(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, int show_labels, float icon_scale) RET_NONE +void uiTemplateIconView(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool show_labels, float icon_scale) RET_NONE void ED_base_object_free_and_unlink(struct Main *bmain, struct Scene *scene, struct Base *base) RET_NONE -void ED_mesh_update(struct Mesh *mesh, struct bContext *C, int calc_edges, int calc_tessface) RET_NONE +void ED_mesh_update(struct Mesh *mesh, struct bContext *C, bool calc_edges, bool calc_tessface) RET_NONE void ED_mesh_vertices_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE void ED_mesh_edges_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE void ED_mesh_tessfaces_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE @@ -570,17 +570,19 @@ void uiItemR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int void uiItemFullO(uiLayout *layout, const char *idname, const char *name, int icon, struct IDProperty *properties, int context, int flag, struct PointerRNA *r_opptr) RET_NONE void uiItemFullO_ptr(struct uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon, struct IDProperty *properties, int context, int flag, struct PointerRNA *r_opptr) RET_NONE void uiItemFullOMenuHold_ptr( uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon, struct IDProperty *properties, int context, int flag, const char *menu_id, /* extra menu arg. */ PointerRNA *r_opptr) RET_NONE -struct uiLayout *uiLayoutRow(uiLayout *layout, int align) RET_NULL -struct uiLayout *uiLayoutColumn(uiLayout *layout, int align) RET_NULL -struct uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, int align) RET_NULL +struct uiLayout *uiLayoutRow(uiLayout *layout, bool align) RET_NULL +struct uiLayout *uiLayoutColumn(uiLayout *layout, bool align) RET_NULL +struct uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, bool align) RET_NULL struct uiLayout *uiLayoutBox(struct uiLayout *layout) RET_NULL -struct uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, int align) RET_NULL +struct uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, bool align) RET_NULL bool uiLayoutGetRedAlert(struct uiLayout *layout) RET_ZERO void uiLayoutSetRedAlert(uiLayout *layout, bool redalert) RET_NONE void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE void uiItemMenuEnumR_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *name, int icon) RET_NONE void uiItemMenuEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name, int icon) RET_NONE +void uiItemEnumR_string_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *value, const char *name, int icon) RET_NONE void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, const char *name, int icon) RET_NONE +void uiItemPointerR_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, struct PointerRNA *searchptr, PropertyRNA *searchprop, const char *name, int icon) RET_NONE void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, const char *name, int icon) RET_NONE void uiItemsEnumO(uiLayout *layout, const char *opname, const char *propname) RET_NONE void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value) RET_NONE @@ -591,7 +593,7 @@ void uiItemIntO(uiLayout *layout, const char *name, int icon, const char *opname void uiItemFloatO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, float value) RET_NONE void uiItemStringO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value) RET_NONE void uiItemL(struct uiLayout *layout, const char *name, int icon) RET_NONE -void uiItemM(uiLayout *layout, struct bContext *C, const char *menuname, const char *name, int icon) RET_NONE +void uiItemM(uiLayout *layout, const char *menuname, const char *name, int icon) RET_NONE void uiItemS(struct uiLayout *layout) RET_NONE void uiItemFullR(uiLayout *layout, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, int value, int flag, const char *name, int icon) RET_NONE void uiLayoutSetContextPointer(uiLayout *layout, const char *name, struct PointerRNA *ptr) RET_NONE @@ -606,11 +608,11 @@ void uiTemplateHeader(struct uiLayout *layout, struct bContext *C) RET_NONE void uiTemplateID(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int filter) RET_NONE struct uiLayout *uiTemplateModifier(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr) RET_NULL struct uiLayout *uiTemplateConstraint(struct uiLayout *layout, struct PointerRNA *ptr) RET_NULL -void uiTemplatePreview(struct uiLayout *layout, struct bContext *C, struct ID *id, int show_buttons, struct ID *parent, +void uiTemplatePreview(struct uiLayout *layout, struct bContext *C, struct ID *id, bool show_buttons, struct ID *parent, struct MTex *slot, const char *preview_id) RET_NONE void uiTemplateIDPreview(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int rows, int cols, int filter) RET_NONE -void uiTemplateCurveMapping(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int type, int levels, int brush, int neg_slope) RET_NONE -void uiTemplateColorRamp(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int expand) RET_NONE +void uiTemplateCurveMapping(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int type, bool levels, bool brush, bool neg_slope) RET_NONE +void uiTemplateColorRamp(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool expand) RET_NONE void uiTemplateLayers(uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *used_ptr, const char *used_propname, int active_layer) RET_NONE void uiTemplateImageLayers(struct uiLayout *layout, struct bContext *C, struct Image *ima, struct ImageUser *iuser) RET_NONE void uiTemplateList(struct uiLayout *layout, struct bContext *C, const char *listtype_name, const char *list_id, @@ -620,8 +622,8 @@ void uiTemplateRunningJobs(struct uiLayout *layout, struct bContext *C) RET_NONE void uiTemplateOperatorSearch(struct uiLayout *layout) RET_NONE void uiTemplateHeader3D(struct uiLayout *layout, struct bContext *C) RET_NONE void uiTemplateEditModeSelection(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, int compact, int multiview, int cubemap) RET_NONE -void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int value_slider, int lock, int lock_luminosity, int cubic) RET_NONE +void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, bool compact, bool multiview, bool cubemap) RET_NONE +void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool value_slider, bool lock, bool lock_luminosity, bool cubic) RET_NONE void uiTemplateHistogram(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE void uiTemplateReportsBanner(uiLayout *layout, struct bContext *C) RET_NONE void uiTemplateWaveform(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE @@ -631,16 +633,16 @@ void uiTemplateNodeView(struct uiLayout *layout, struct bContext *C, struct bNod void uiTemplateTextureUser(struct uiLayout *layout, struct bContext *C) RET_NONE void uiTemplateTextureShow(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop) RET_NONE void uiTemplateKeymapItemProperties(struct uiLayout *layout, struct PointerRNA *ptr) RET_NONE -void uiTemplateMovieClip(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, int compact) RET_NONE +void uiTemplateMovieClip(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, bool compact) RET_NONE void uiTemplateMovieclipInformation(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr) RET_NONE void uiTemplateTrack(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateMarker(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *userptr, PointerRNA *trackptr, int compact) RET_NONE -void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, int color_management) RET_NONE +void uiTemplateMarker(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *userptr, PointerRNA *trackptr, bool compact) RET_NONE +void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, bool color_management) RET_NONE void uiTemplateColorspaceSettings(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE void uiTemplateColormanagedViewSettings(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname) RET_NONE void uiTemplateComponentMenu(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name) RET_NONE void uiTemplateNodeSocket(struct uiLayout *layout, struct bContext *C, float *color) RET_NONE -void uiTemplatePalette(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, int color) RET_NONE +void uiTemplatePalette(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, bool color) RET_NONE void uiTemplateImageStereo3d(struct uiLayout *layout, struct PointerRNA *stereo3d_format_ptr) RET_NONE void uiTemplateCacheFile(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname) RET_NONE @@ -655,14 +657,14 @@ void RE_engine_update_result(struct RenderEngine *engine, struct RenderResult *r void RE_engine_update_progress(struct RenderEngine *engine, float progress) RET_NONE void RE_engine_set_error_message(RenderEngine *engine, const char *msg) RET_NONE void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, const char *chan_id, const char *layername) RET_NONE -void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int cancel, int highlight, int merge_results) RET_NONE +void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, bool cancel, bool highlight, bool merge_results) RET_NONE void RE_engine_update_stats(RenderEngine *engine, const char *stats, const char *info) RET_NONE void RE_layer_load_from_file(struct RenderLayer *layer, struct ReportList *reports, const char *filename, int x, int y) RET_NONE void RE_result_load_from_file(struct RenderResult *result, struct ReportList *reports, const char *filename) RET_NONE void RE_AcquireResultImage(struct Render *re, struct RenderResult *rr, const int view_id) RET_NONE void RE_ReleaseResult(struct Render *re) RET_NONE void RE_ReleaseResultImage(struct Render *re) RET_NONE -int RE_engine_test_break(struct RenderEngine *engine) RET_ZERO +bool RE_engine_test_break(struct RenderEngine *engine) RET_ZERO void RE_engines_init() RET_NONE void RE_engines_exit() RET_NONE void RE_engine_report(struct RenderEngine *engine, int type, const char *msg) RET_NONE @@ -689,8 +691,8 @@ struct wmOperatorTypeMacro *WM_operatortype_macro_define(struct wmOperatorType * int WM_operator_call_py(struct bContext *C, struct wmOperatorType *ot, short context, struct PointerRNA *properties, struct ReportList *reports, const bool is_undo) RET_ZERO void WM_operatortype_remove_ptr(struct wmOperatorType *ot) RET_NONE bool WM_operatortype_remove(const char *idname) RET_ZERO -int WM_operator_poll(struct bContext *C, struct wmOperatorType *ot) RET_ZERO -int WM_operator_poll_context(struct bContext *C, struct wmOperatorType *ot, short context) RET_ZERO +bool WM_operator_poll(struct bContext *C, struct wmOperatorType *ot) RET_ZERO +bool WM_operator_poll_context(struct bContext *C, struct wmOperatorType *ot, short context) RET_ZERO int WM_operator_props_popup(struct bContext *C, struct wmOperator *op, const struct wmEvent *event) RET_ZERO void WM_operator_properties_free(struct PointerRNA *ptr) RET_NONE void WM_operator_properties_create(struct PointerRNA *ptr, const char *opstring) RET_NONE diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt index 5af22fd10bd7..c2008668cafe 100644 --- a/source/creator/CMakeLists.txt +++ b/source/creator/CMakeLists.txt @@ -341,7 +341,7 @@ install( if(WITH_PYTHON) # install(CODE "message(\"copying blender scripts...\")") - + # exclude addons_contrib if release if("${BLENDER_VERSION_CYCLE}" STREQUAL "release" OR "${BLENDER_VERSION_CYCLE}" STREQUAL "rc") @@ -367,7 +367,7 @@ if(WITH_PYTHON) PATTERN "${ADDON_EXCLUDE_CONDITIONAL}" EXCLUDE PATTERN "${FREESTYLE_EXCLUDE_CONDITIONAL}" EXCLUDE ) - + unset(ADDON_EXCLUDE_CONDITIONAL) unset(FREESTYLE_EXCLUDE_CONDITIONAL) endif() @@ -655,7 +655,7 @@ if(UNIX AND NOT APPLE) unset(_suffix) endif() unset(_target_LIB) - + endif() endif() elseif(WIN32) @@ -725,7 +725,7 @@ elseif(WIN32) ) if(WITH_PYTHON_INSTALL_NUMPY) - set(PYTHON_NUMPY_VERSION 1.13) + set(PYTHON_NUMPY_VERSION 1.15) add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${BLENDER_VERSION}/python/lib/site-packages COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/${BLENDER_VERSION}/python/lib/site-packages) @@ -788,12 +788,12 @@ elseif(WIN32) if(WITH_CODEC_FFMPEG) install( FILES - ${LIBDIR}/ffmpeg/lib/avcodec-57.dll - ${LIBDIR}/ffmpeg/lib/avformat-57.dll - ${LIBDIR}/ffmpeg/lib/avdevice-57.dll - ${LIBDIR}/ffmpeg/lib/avutil-55.dll - ${LIBDIR}/ffmpeg/lib/swscale-4.dll - ${LIBDIR}/ffmpeg/lib/swresample-2.dll + ${LIBDIR}/ffmpeg/lib/avcodec-58.dll + ${LIBDIR}/ffmpeg/lib/avformat-58.dll + ${LIBDIR}/ffmpeg/lib/avdevice-58.dll + ${LIBDIR}/ffmpeg/lib/avutil-56.dll + ${LIBDIR}/ffmpeg/lib/swscale-5.dll + ${LIBDIR}/ffmpeg/lib/swresample-3.dll DESTINATION "." ) endif() @@ -819,7 +819,7 @@ elseif(WIN32) DESTINATION "." ) endif() - + if(WITH_SYSTEM_AUDASPACE) install( FILES @@ -836,21 +836,12 @@ elseif(WIN32) DESTINATION "." ) endif() - + install( # x86 builds can run on x64 Windows, so this is required at all times FILES ${LIBDIR}/thumbhandler/lib/BlendThumb64.dll DESTINATION "." ) - if(WITH_OPENCOLORIO) - set(OCIOBIN ${LIBDIR}/opencolorio/bin) - install( - FILES - ${OCIOBIN}/OpenColorIO.dll - DESTINATION "." - ) - endif() - elseif(APPLE) # handy install macro to exclude files, we use \$ escape for the "to" @@ -947,7 +938,7 @@ elseif(APPLE) ) unset(_py_inc_suffix) endif() - + # install blenderplayer bundle - copy of blender.app above. re-using macros et al # note we are using OSX Bundle as base and copying Blender dummy bundle on top of it if(WITH_GAMEENGINE AND WITH_PLAYER) diff --git a/source/creator/creator.c b/source/creator/creator.c index 04a7a5fc8c0a..c96abc63eb75 100644 --- a/source/creator/creator.c +++ b/source/creator/creator.c @@ -340,7 +340,7 @@ int main( #endif main_callback_setup(); - + #if defined(__APPLE__) && !defined(WITH_PYTHON_MODULE) /* patch to ignore argument finder gives us (pid?) */ if (argc == 2 && STREQLEN(argv[1], "-psn_", 5)) { @@ -355,7 +355,7 @@ int main( } } #endif - + #ifdef __FreeBSD__ fpsetmask(0); #endif @@ -377,7 +377,7 @@ int main( BKE_brush_system_init(); RE_texture_rng_init(); - + BLI_callback_global_init(); @@ -432,7 +432,7 @@ int main( /* Initialize ffmpeg if built in, also needed for bg mode if videos are * rendered via ffmpeg */ BKE_sound_init_once(); - + init_def_material(); if (G.background == 0) { @@ -468,7 +468,7 @@ int main( #else printf("\n* WARNING * - Blender compiled without Python!\nthis is not intended for typical usage\n\n"); #endif - + CTX_py_init_set(C, 1); WM_keymap_init(C); @@ -481,7 +481,7 @@ int main( /* OK we are ready for it */ #ifndef WITH_PYTHON_MODULE main_args_setup_post(C, ba); - + if (G.background == 0) { if (!G.file_loaded) if (U.uiflag2 & USER_KEEP_SESSION) diff --git a/source/creator/creator_args.c b/source/creator/creator_args.c index 231c967ffa44..dec1df2a9cbe 100644 --- a/source/creator/creator_args.c +++ b/source/creator/creator_args.c @@ -60,6 +60,8 @@ #include "BKE_sound.h" #include "BKE_image.h" +#include "DNA_screen_types.h" + #include "DEG_depsgraph.h" #ifdef WITH_FFMPEG @@ -578,6 +580,7 @@ static int arg_handle_print_help(int UNUSED(argc), const char **UNUSED(argv), vo printf("\n"); printf("Misc Options:\n"); + BLI_argsPrintArgDoc(ba, "--app-template"); BLI_argsPrintArgDoc(ba, "--factory-startup"); printf("\n"); BLI_argsPrintArgDoc(ba, "--env-system-datafiles"); @@ -991,6 +994,22 @@ static int arg_handle_debug_fpe_set(int UNUSED(argc), const char **UNUSED(argv), return 0; } +static const char arg_handle_app_template_doc[] = +"\n\tSet the application template, use 'default' for none." +; +static int arg_handle_app_template(int argc, const char **argv, void *UNUSED(data)) +{ + if (argc > 1) { + const char *app_template = STREQ(argv[1], "default") ? "" : argv[1]; + WM_init_state_app_template_set(app_template); + return 1; + } + else { + printf("\nError: App template must follow '--app-template'.\n"); + return 0; + } +} + static const char arg_handle_factory_startup_set_doc[] = "\n\tSkip reading the " STRINGIFY(BLENDER_STARTUP_FILE) " in the users home directory." ; @@ -1474,11 +1493,11 @@ static int arg_handle_ge_parameters_set(int argc, const char **argv, void *data) #endif /* doMipMap */ if (STREQ(argv[a], "nomipmap")) { - GPU_set_mipmap(0); //doMipMap = 0; + GPU_set_mipmap(G_MAIN, 0); //doMipMap = 0; } /* linearMipMap */ if (STREQ(argv[a], "linearmipmap")) { - GPU_set_mipmap(1); + GPU_set_mipmap(G_MAIN, 1); GPU_set_linear_mipmap(1); //linearMipMap = 1; } @@ -1588,6 +1607,16 @@ static int arg_handle_scene_set(int argc, const char **argv, void *data) Scene *scene = BKE_scene_set_name(CTX_data_main(C), argv[1]); if (scene) { CTX_data_scene_set(C, scene); + + /* Set the scene of the first window, see: T55991, + * otherwise scrips that run later won't get this scene back from the context. */ + wmWindow *win = CTX_wm_window(C); + if (win == NULL) { + win = CTX_wm_manager(C)->windows.first; + } + if (win != NULL) { + win->screen->scene = scene; + } } return 1; } @@ -2031,6 +2060,7 @@ void main_args_setup(bContext *C, bArgs *ba, SYS_SystemHandle *syshandle) BLI_argsAdd(ba, 1, NULL, "--verbose", CB(arg_handle_verbosity_set), NULL); + BLI_argsAdd(ba, 1, NULL, "--app-template", CB(arg_handle_app_template), NULL); BLI_argsAdd(ba, 1, NULL, "--factory-startup", CB(arg_handle_factory_startup_set), NULL); /* TODO, add user env vars? */ diff --git a/source/creator/creator_signals.c b/source/creator/creator_signals.c index 1cec6297c87b..17728ee02d5e 100644 --- a/source/creator/creator_signals.c +++ b/source/creator/creator_signals.c @@ -130,7 +130,7 @@ static void sig_handle_crash(int signum) } else { BLI_strncpy(fname, G_MAIN->name, sizeof(fname)); - BLI_replace_extension(fname, sizeof(fname), ".crash.blend"); + BLI_path_extension_replace(fname, sizeof(fname), ".crash.blend"); } printf("Writing: %s\n", fname); @@ -151,7 +151,7 @@ static void sig_handle_crash(int signum) } else { BLI_join_dirfile(fname, sizeof(fname), BKE_tempdir_base(), BLI_path_basename(G_MAIN->name)); - BLI_replace_extension(fname, sizeof(fname), ".crash.txt"); + BLI_path_extension_replace(fname, sizeof(fname), ".crash.txt"); } printf("Writing: %s\n", fname); diff --git a/source/gameengine/GamePlayer/GPG_ghost.cpp b/source/gameengine/GamePlayer/GPG_ghost.cpp index 245341e3a530..7c40d7089948 100644 --- a/source/gameengine/GamePlayer/GPG_ghost.cpp +++ b/source/gameengine/GamePlayer/GPG_ghost.cpp @@ -1350,11 +1350,11 @@ int main(int argc, GPU_init(); if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) { - GPU_set_mipmap(0); + GPU_set_mipmap(G.main, 0); } - GPU_set_anisotropic(U.anisotropic_filter); - GPU_set_gpu_mipmapping(U.use_gpu_mipmap); + GPU_set_anisotropic(G.main, U.anisotropic_filter); + GPU_set_gpu_mipmapping(G.main, U.use_gpu_mipmap); GPU_set_linear_mipmap(true); } diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp index 0bacecbebe55..aa1d29c47bcf 100644 --- a/source/gameengine/Ketsji/KX_PythonInit.cpp +++ b/source/gameengine/Ketsji/KX_PythonInit.cpp @@ -549,7 +549,7 @@ static PyObject *gPyGetBlendFileList(PyObject *, PyObject *args) } while ((dirp = readdir(dp)) != nullptr) { - if (BLI_testextensie(dirp->d_name, ".blend")) { + if (BLI_path_extension_check(dirp->d_name, ".blend")) { value = PyC_UnicodeFromByte(dirp->d_name); PyList_Append(list, value); Py_DECREF(value); @@ -1113,7 +1113,7 @@ static PyObject *gPySetGLSLMaterialSetting(PyObject *, /* display lists and GLSL materials need to be remade */ if (sceneflag != gs->glslflag) { - GPU_materials_free(); + GPU_materials_free(G.main); if (KX_GetActiveEngine()) { EXP_ListValue *scenes = KX_GetActiveEngine()->CurrentScenes(); @@ -2662,7 +2662,7 @@ std::string pathGamePythonConfig() int len = path.size(); /* replace extension */ - if (BLI_testextensie(path.c_str(), ".blend")) { + if (BLI_path_extension_check(path.c_str(), ".blend")) { path = path.substr(0, len - 6) + std::string(".bgeconf"); } else { diff --git a/source/gameengine/Rasterizer/RAS_Rasterizer.cpp b/source/gameengine/Rasterizer/RAS_Rasterizer.cpp index 2956a0a7f051..48f53abd5fd6 100644 --- a/source/gameengine/Rasterizer/RAS_Rasterizer.cpp +++ b/source/gameengine/Rasterizer/RAS_Rasterizer.cpp @@ -54,6 +54,7 @@ #include "BLI_math_vector.h" extern "C" { +# include "BKE_global.h" # include "BLF_api.h" } @@ -990,7 +991,7 @@ void RAS_Rasterizer::SetInvertFrontFace(bool invert) void RAS_Rasterizer::SetAnisotropicFiltering(short level) { - GPU_set_anisotropic((float)level); + GPU_set_anisotropic(G.main, (float)level); } short RAS_Rasterizer::GetAnisotropicFiltering() @@ -1004,19 +1005,19 @@ void RAS_Rasterizer::SetMipmapping(MipmapOption val) case RAS_Rasterizer::RAS_MIPMAP_LINEAR: { GPU_set_linear_mipmap(1); - GPU_set_mipmap(1); + GPU_set_mipmap(G.main, 1); break; } case RAS_Rasterizer::RAS_MIPMAP_NEAREST: { GPU_set_linear_mipmap(0); - GPU_set_mipmap(1); + GPU_set_mipmap(G.main, 1); break; } default: { GPU_set_linear_mipmap(0); - GPU_set_mipmap(0); + GPU_set_mipmap(G.main, 0); } } } diff --git a/tests/check_deprecated.py b/tests/check_deprecated.py index 6e07f8fdb31f..7595bb4ff816 100644 --- a/tests/check_deprecated.py +++ b/tests/check_deprecated.py @@ -142,5 +142,6 @@ def main(): else: print("\nnone found!") + if __name__ == '__main__': main() diff --git a/tests/gtests/blenlib/BLI_array_utils_test.cc b/tests/gtests/blenlib/BLI_array_utils_test.cc index c4601e00fbde..6daa400a478c 100644 --- a/tests/gtests/blenlib/BLI_array_utils_test.cc +++ b/tests/gtests/blenlib/BLI_array_utils_test.cc @@ -187,4 +187,3 @@ TEST(array_utils, BinaryOrInt4Mix) BINARY_OR_TEST(data_cmp, data_a, data_b, data_combine, ARRAY_SIZE(data_cmp)); } #undef BINARY_OR_TEST - diff --git a/tests/gtests/guardedalloc/guardedalloc_overflow_test.cc b/tests/gtests/guardedalloc/guardedalloc_overflow_test.cc index 18cf57bd6ea7..6f4df4fd047d 100644 --- a/tests/gtests/guardedalloc/guardedalloc_overflow_test.cc +++ b/tests/gtests/guardedalloc/guardedalloc_overflow_test.cc @@ -58,4 +58,3 @@ TEST(guardedalloc, GuardedIntegerOverflow) EXPECT_EXIT(MallocArray(SIZE_MAX, 12345567), ABORT_PREDICATE, ""); EXPECT_EXIT(CallocArray(SIZE_MAX, SIZE_MAX), ABORT_PREDICATE, ""); } - diff --git a/tests/gtests/testing/testing_main.cc b/tests/gtests/testing/testing_main.cc index e8104a2a026f..6f506d1a0cf5 100644 --- a/tests/gtests/testing/testing_main.cc +++ b/tests/gtests/testing/testing_main.cc @@ -33,4 +33,3 @@ int main(int argc, char **argv) { return RUN_ALL_TESTS(); } - diff --git a/tests/python/alembic_tests.py b/tests/python/alembic_tests.py index b9dc78a821fd..d872e699cea6 100755 --- a/tests/python/alembic_tests.py +++ b/tests/python/alembic_tests.py @@ -33,7 +33,6 @@ ) - class AbcPropError(Exception): """Raised when AbstractAlembicTest.abcprop() finds an error.""" diff --git a/tests/python/bl_alembic_import_test.py b/tests/python/bl_alembic_import_test.py index 1b526b3ebba8..177541692793 100644 --- a/tests/python/bl_alembic_import_test.py +++ b/tests/python/bl_alembic_import_test.py @@ -107,7 +107,6 @@ def test_inherit_or_not(self): self.assertAlmostEqual(0, y) self.assertAlmostEqual(2, z) - def test_select_after_import(self): # Add a sphere, so that there is something in the scene, selected, and active, # before we do the Alembic import. diff --git a/tests/python/bl_load_addons.py b/tests/python/bl_load_addons.py index 29304400005c..16ddea247563 100644 --- a/tests/python/bl_load_addons.py +++ b/tests/python/bl_load_addons.py @@ -33,7 +33,7 @@ BLACKLIST_DIRS = ( os.path.join(bpy.utils.resource_path('USER'), "scripts"), - ) + tuple(addon_utils.paths()[1:]) +) + tuple(addon_utils.paths()[1:]) BLACKLIST_ADDONS = set() @@ -54,9 +54,10 @@ def _init_addon_blacklist(): def addon_modules_sorted(): modules = addon_utils.modules({}) modules[:] = [ - mod for mod in modules - if not (mod.__file__.startswith(BLACKLIST_DIRS)) - if not (mod.__name__ in BLACKLIST_ADDONS)] + mod for mod in modules + if not (mod.__file__.startswith(BLACKLIST_DIRS)) + if not (mod.__name__ in BLACKLIST_ADDONS) + ] modules.sort(key=lambda mod: mod.__name__) return modules diff --git a/tests/python/bl_load_py_modules.py b/tests/python/bl_load_py_modules.py index 39e7bd33d447..437a425a36d6 100644 --- a/tests/python/bl_load_py_modules.py +++ b/tests/python/bl_load_py_modules.py @@ -39,20 +39,20 @@ # The unpacked wheel is only loaded when actually used, not directly on import: os.path.join("io_blend_utils", "blender_bam-unpacked.whl"), - } +} # Some modules need to add to the `sys.path`. MODULE_SYS_PATHS = { # Runs in a Python subprocess, so its expected its basedir can be imported. "io_blend_utils.blendfile_pack": ".", - } +} if not bpy.app.build_options.freestyle: BLACKLIST.add("render_freestyle_svg") BLACKLIST_DIRS = ( os.path.join(bpy.utils.resource_path('USER'), "scripts"), - ) + tuple(addon_utils.paths()[1:]) +) + tuple(addon_utils.paths()[1:]) def module_names_recursive(mod_dir, *, parent=None): @@ -168,7 +168,7 @@ def load_modules(): os.sep + "presets" + os.sep, os.sep + "templates" + os.sep, ] + ([(os.sep + f + os.sep) for f in BLACKLIST] + - [(os.sep + f + ".py") for f in BLACKLIST]) + [(os.sep + f + ".py") for f in BLACKLIST]) # # now submodules @@ -185,7 +185,7 @@ def load_modules(): sys.path.extend([ os.path.normpath(os.path.join(mod_dir, f)) for f in MODULE_SYS_PATHS.get(mod_name_full, ()) - ]) + ]) try: __import__(mod_name_full) @@ -248,6 +248,7 @@ def main(): load_addons() load_modules() + if __name__ == "__main__": # So a python error exits(1) try: diff --git a/tests/python/bl_mesh_modifiers.py b/tests/python/bl_mesh_modifiers.py index bff2c31984c7..619fdc77801a 100644 --- a/tests/python/bl_mesh_modifiers.py +++ b/tests/python/bl_mesh_modifiers.py @@ -61,11 +61,11 @@ def ctx_viewport_shade(context, shade): ctx_viewport_shade(context, shade) - #~ # stop to inspect! - #~ if filepath == "test_cube_shell_solidify_subsurf_wp_wire": - #~ assert(0) - #~ else: - #~ return + # stop to inspect! + # if filepath == "test_cube_shell_solidify_subsurf_wp_wire": + # assert(0) + # else: + # return bpy.ops.render.opengl(write_still=True, view_context=True) @@ -219,6 +219,7 @@ def mesh_bmesh_poly_elems(poly, elems): vert_total = poly.loop_total return elems[vert_start:vert_start + vert_total] + def mesh_bmesh_poly_vertices(poly): return [loop.vertex_index for loop in mesh_bmesh_poly_elems(poly, poly.id_data.loops)] @@ -505,7 +506,7 @@ def modifier_mask_add(scene, obj): (-1, 1, 3), (0, 1, 3), (0, 0, 3), - ) +) cube_like_faces = ( @@ -547,7 +548,7 @@ def modifier_mask_add(scene, obj): (31, 30, 36, 33), (32, 31, 33, 34), (35, 34, 33, 36), - ) +) # useful since its a shell for solidify and it can be mirrored @@ -564,7 +565,7 @@ def modifier_mask_add(scene, obj): (0, -1, 0), (0, 0, -1), (0, 1, -1), - ) +) cube_shell_face = ( @@ -577,7 +578,7 @@ def modifier_mask_add(scene, obj): (6, 5, 11), (7, 4, 9, 8), (10, 7, 6, 11), - ) +) def make_cube(scene): @@ -678,59 +679,77 @@ def make_monkey_extra(scene): global_tests = [] -global_tests.append(("none", - (), - )) - +global_tests.append( + ("none", + (), + ) +) # single -global_tests.append(("subsurf_single", - ((modifier_subsurf_add, dict(levels=2)), ), - )) - - -global_tests.append(("armature_single", - ((modifier_armature_add, dict()), ), - )) - - -global_tests.append(("mirror_single", - ((modifier_mirror_add, dict()), ), - )) - -global_tests.append(("hook_single", - ((modifier_hook_add, dict()), ), - )) - -global_tests.append(("decimate_single", - ((modifier_decimate_add, dict()), ), - )) - -global_tests.append(("build_single", - ((modifier_build_add, dict()), ), - )) - -global_tests.append(("mask_single", - ((modifier_mask_add, dict()), ), - )) +global_tests.append( + ("subsurf_single", + ((modifier_subsurf_add, dict(levels=2)), ), + ) +) + +global_tests.append( + ("armature_single", + ((modifier_armature_add, dict()), ), + ) +) + +global_tests.append( + ("mirror_single", + ((modifier_mirror_add, dict()), ), + ) +) + +global_tests.append( + ("hook_single", + ((modifier_hook_add, dict()), ), + ) +) + +global_tests.append( + ("decimate_single", + ((modifier_decimate_add, dict()), ), + ) +) + +global_tests.append( + ("build_single", + ((modifier_build_add, dict()), ), + ) +) + +global_tests.append( + ("mask_single", + ((modifier_mask_add, dict()), ), + ) +) # combinations -global_tests.append(("mirror_subsurf", - ((modifier_mirror_add, dict()), - (modifier_subsurf_add, dict(levels=2))), - )) - -global_tests.append(("solidify_subsurf", - ((modifier_solidify_add, dict()), - (modifier_subsurf_add, dict(levels=2))), - )) - - -def apply_test(test, scene, obj, - render_func=None, - render_args=None, - render_kwargs=None, - ): +global_tests.append( + ("mirror_subsurf", + ((modifier_mirror_add, dict()), + (modifier_subsurf_add, dict(levels=2))), + ) +) + +global_tests.append( + ("solidify_subsurf", + ((modifier_solidify_add, dict()), + (modifier_subsurf_add, dict(levels=2))), + ) +) + + +def apply_test( + test, scene, obj, + render_func=None, + render_args=None, + render_kwargs=None, +): test_name, test_funcs = test @@ -756,10 +775,12 @@ def test_cube(context, test): obj = make_cube_extra(scene) ctx_camera_setup(context, location=(3, 3, 3)) - apply_test(test, scene, obj, - render_func=render_gl_all_modes, - render_args=(context, obj), - render_kwargs=dict(filepath=whoami())) + apply_test( + test, scene, obj, + render_func=render_gl_all_modes, + render_args=(context, obj), + render_kwargs=dict(filepath=whoami()) + ) def test_cube_like(context, test): @@ -767,10 +788,12 @@ def test_cube_like(context, test): obj = make_cube_like_extra(scene) ctx_camera_setup(context, location=(5, 5, 5)) - apply_test(test, scene, obj, - render_func=render_gl_all_modes, - render_args=(context, obj), - render_kwargs=dict(filepath=whoami())) + apply_test( + test, scene, obj, + render_func=render_gl_all_modes, + render_args=(context, obj), + render_kwargs=dict(filepath=whoami()) + ) def test_cube_shell(context, test): @@ -778,10 +801,12 @@ def test_cube_shell(context, test): obj = make_cube_shell_extra(scene) ctx_camera_setup(context, location=(4, 4, 4)) - apply_test(test, scene, obj, - render_func=render_gl_all_modes, - render_args=(context, obj), - render_kwargs=dict(filepath=whoami())) + apply_test( + test, scene, obj, + render_func=render_gl_all_modes, + render_args=(context, obj), + render_kwargs=dict(filepath=whoami()) + ) # ----------------------------------------------------------------------------- diff --git a/tests/python/bl_mesh_validate.py b/tests/python/bl_mesh_validate.py index ac5be7d08d70..e1dd097b2e0a 100644 --- a/tests/python/bl_mesh_validate.py +++ b/tests/python/bl_mesh_validate.py @@ -45,20 +45,20 @@ ( # Edges ), ( # Loops - 0, 1, 4, 3, - 3, 4, 6, - 1, 2, 5, 4, - 3, 4, 6, - 4, 7, 6, - 4, 5, 9, 4, 8, 7, + 0, 1, 4, 3, + 3, 4, 6, + 1, 2, 5, 4, + 3, 4, 6, + 4, 7, 6, + 4, 5, 9, 4, 8, 7, ), ( # Polygons - (0, 4), - (4, 3), - (7, 4), - (11, 3), - (14, 3), - (16, 6), + (0, 4), + (4, 3), + (7, 4), + (11, 3), + (14, 3), + (16, 6), ), ), ), @@ -66,17 +66,17 @@ BUILTINS = ( - "primitive_plane_add", - "primitive_cube_add", - "primitive_circle_add", - "primitive_uv_sphere_add", - "primitive_ico_sphere_add", - "primitive_cylinder_add", - "primitive_cone_add", - "primitive_grid_add", - "primitive_monkey_add", - "primitive_torus_add", - ) + "primitive_plane_add", + "primitive_cube_add", + "primitive_circle_add", + "primitive_uv_sphere_add", + "primitive_ico_sphere_add", + "primitive_cylinder_add", + "primitive_cone_add", + "primitive_grid_add", + "primitive_monkey_add", + "primitive_torus_add", +) BUILTINS_NBR = 4 BUILTINS_NBRCHANGES = 5 diff --git a/tests/python/bl_pyapi_bpy_utils_units.py b/tests/python/bl_pyapi_bpy_utils_units.py index 251419cb9ef2..88d5cb941bdf 100644 --- a/tests/python/bl_pyapi_bpy_utils_units.py +++ b/tests/python/bl_pyapi_bpy_utils_units.py @@ -5,25 +5,26 @@ from bpy.utils import units + class UnitsTesting(unittest.TestCase): # From user typing to 'internal' Blender value. INPUT_TESTS = ( # system, type, ref, input, value - ##### LENGTH + # LENGTH ('IMPERIAL', 'LENGTH', "", "1ft", 0.3048), ('IMPERIAL', 'LENGTH', "", "(1+1)ft", 0.3048 * 2), ('IMPERIAL', 'LENGTH', "", "1mi4\"", 1609.344 + 0.0254 * 4), - ('METRIC', 'LENGTH', "", "0.005µm", 0.000001 * 0.005), - ('METRIC', 'LENGTH', "", "1e6km", 1000.0 * 1e6), + ('METRIC', 'LENGTH', "", "0.005µm", 0.000001 * 0.005), + ('METRIC', 'LENGTH', "", "1e6km", 1000.0 * 1e6), ('IMPERIAL', 'LENGTH', "", "1ft5cm", 0.3048 + 0.01 * 5), - ('METRIC', 'LENGTH', "", "1ft5cm", 0.3048 + 0.01 * 5), + ('METRIC', 'LENGTH', "", "1ft5cm", 0.3048 + 0.01 * 5), # Using reference string to find a unit when none is given. ('IMPERIAL', 'LENGTH', "33.3ft", "1", 0.3048), - ('METRIC', 'LENGTH', "33.3dm", "1", 0.1), + ('METRIC', 'LENGTH', "33.3dm", "1", 0.1), ('IMPERIAL', 'LENGTH', "33.3cm", "1", 0.3048), # ref unit is not in IMPERIAL system, default to feet... ('IMPERIAL', 'LENGTH', "33.3ft", "1\"", 0.0254), # unused ref unit, since one is given already! ('IMPERIAL', 'LENGTH', "", "1+1ft", 0.3048 * 2), # default unit taken from current string (feet). - ('METRIC', 'LENGTH', "", "1+1ft", 1.3048), # no metric units, we default to meters. + ('METRIC', 'LENGTH', "", "1+1ft", 1.3048), # no metric units, we default to meters. ('IMPERIAL', 'LENGTH', "", "3+1in+1ft", 0.3048 * 4 + 0.0254), # bigger unit becomes default one! ('IMPERIAL', 'LENGTH', "", "(3+1)in+1ft", 0.3048 + 0.0254 * 4), ) @@ -31,18 +32,18 @@ class UnitsTesting(unittest.TestCase): # From 'internal' Blender value to user-friendly printing OUTPUT_TESTS = ( # system, type, prec, sep, compat, value, output - ##### LENGTH + # LENGTH # Note: precision handling is a bit complicated when using multi-units... ('IMPERIAL', 'LENGTH', 3, False, False, 0.3048, "1'"), - ('IMPERIAL', 'LENGTH', 3, False, True, 0.3048, "1ft"), - ('IMPERIAL', 'LENGTH', 4, True, False, 0.3048 * 2 + 0.0254 * 5.5, "2' 5.5\""), + ('IMPERIAL', 'LENGTH', 3, False, True, 0.3048, "1ft"), + ('IMPERIAL', 'LENGTH', 4, True, False, 0.3048 * 2 + 0.0254 * 5.5, "2' 5.5\""), ('IMPERIAL', 'LENGTH', 3, False, False, 1609.344 * 1e6, "1000000mi"), ('IMPERIAL', 'LENGTH', 6, False, False, 1609.344 * 1e6, "1000000mi"), - ('METRIC', 'LENGTH', 3, True, False, 1000 * 2 + 0.001 * 15, "2km 2cm"), - ('METRIC', 'LENGTH', 5, True, False, 1234.56789, "1km 234.6m"), - ('METRIC', 'LENGTH', 6, True, False, 1234.56789, "1km 234.57m"), - ('METRIC', 'LENGTH', 9, False, False, 1234.56789, "1.234568km"), - ('METRIC', 'LENGTH', 9, True, False, 1000.000123456789, "1km 0.123mm"), + ('METRIC', 'LENGTH', 3, True, False, 1000 * 2 + 0.001 * 15, "2km 2cm"), + ('METRIC', 'LENGTH', 5, True, False, 1234.56789, "1km 234.6m"), + ('METRIC', 'LENGTH', 6, True, False, 1234.56789, "1km 234.57m"), + ('METRIC', 'LENGTH', 9, False, False, 1234.56789, "1.234568km"), + ('METRIC', 'LENGTH', 9, True, False, 1000.000123456789, "1km 0.123mm"), ) def test_units_inputs(self): @@ -63,9 +64,13 @@ def similar_values(v1, v2, e): def test_units_outputs(self): for usys, utype, prec, sep, compat, val, output in self.OUTPUT_TESTS: opt_str = units.to_string(usys, utype, val, prec, sep, compat) - self.assertEqual(opt_str, output, - msg="%s, %s: %f (precision: %d, separate units: %d, compat units: %d) => " - "\"%s\", expected \"%s\"" % (usys, utype, val, prec, sep, compat, opt_str, output)) + self.assertEqual( + opt_str, output, + msg=( + "%s, %s: %f (precision: %d, separate units: %d, compat units: %d) => " + "\"%s\", expected \"%s\"" + ) % (usys, utype, val, prec, sep, compat, opt_str, output) + ) if __name__ == '__main__': diff --git a/tests/python/bl_pyapi_idprop.py b/tests/python/bl_pyapi_idprop.py index 7bf68c16cc72..063d68fae201 100644 --- a/tests/python/bl_pyapi_idprop.py +++ b/tests/python/bl_pyapi_idprop.py @@ -198,6 +198,7 @@ def assertEqualMemviews(self, view1, view2): self.assertEqual(list(view1), list(view2)) self.assertEqual(view1.tobytes(), view2.tobytes()) + if __name__ == '__main__': import sys sys.argv = [__file__] + (sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) diff --git a/tests/python/bl_pyapi_idprop_datablock.py b/tests/python/bl_pyapi_idprop_datablock.py index 4acfb83bd953..4b46bea7c00c 100644 --- a/tests/python/bl_pyapi_idprop_datablock.py +++ b/tests/python/bl_pyapi_idprop_datablock.py @@ -61,8 +61,10 @@ class TestClass(bpy.types.PropertyGroup): def get_scene(lib_name, sce_name): for s in bpy.data.scenes: if s.name == sce_name: - if (s.library and s.library.name == lib_name) or \ - (lib_name == None and s.library == None): + if ( + (s.library and s.library.name == lib_name) or + (lib_name is None and s.library is None) + ): return s @@ -309,6 +311,7 @@ class TestPrefs(bpy.types.AddonPreferences): class TestUIList(UIList): test = bpy.props.PointerProperty(type=bpy.types.Object) + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): layout.prop(item, "name", text="", emboss=False, icon_value=icon) diff --git a/tests/python/bl_pyapi_mathutils.py b/tests/python/bl_pyapi_mathutils.py index b2d3d79fd56d..57bbbc7e73e8 100644 --- a/tests/python/bl_pyapi_mathutils.py +++ b/tests/python/bl_pyapi_mathutils.py @@ -21,22 +21,22 @@ (-0.854645, 0.518036, 0.033936), (0.42514, -0.437866, -0.792114), (-0.358948, 0.597046, 0.717377), - (-0.985413,0.144714, 0.089294), - ) + (-0.985413, 0.144714, 0.089294), +) # get data at different scales vector_data = sum( (tuple(tuple(a * scale for a in v) for v in vector_data) - for scale in (s * sign for s in (0.0001, 0.1, 1.0, 10.0, 1000.0, 100000.0) - for sign in (1.0, -1.0))), ()) + ((0.0, 0.0, 0.0),) + for scale in (s * sign for s in (0.0001, 0.1, 1.0, 10.0, 1000.0, 100000.0) + for sign in (1.0, -1.0))), ()) + ((0.0, 0.0, 0.0),) class MatrixTesting(unittest.TestCase): def test_matrix_column_access(self): - #mat = - #[ 1 2 3 4 ] - #[ 1 2 3 4 ] - #[ 1 2 3 4 ] + # mat = + # [ 1 2 3 4 ] + # [ 1 2 3 4 ] + # [ 1 2 3 4 ] mat = Matrix(((1, 11, 111), (2, 22, 222), (3, 33, 333), @@ -81,11 +81,11 @@ def test_item_assignment(self): self.assertIn(item, indices) def test_matrix_to_3x3(self): - #mat = - #[ 1 2 3 4 ] - #[ 2 4 6 8 ] - #[ 3 6 9 12 ] - #[ 4 8 12 16 ] + # mat = + # [ 1 2 3 4 ] + # [ 2 4 6 8 ] + # [ 3 6 9 12 ] + # [ 4 8 12 16 ] mat = Matrix(tuple((i, 2 * i, 3 * i, 4 * i) for i in range(1, 5))) mat_correct = Matrix(((1, 2, 3), (2, 4, 6), (3, 6, 9))) self.assertEqual(mat.to_3x3(), mat_correct) @@ -372,7 +372,6 @@ def test_kdtree_grid_filter_pairs(self): ret_filter = k_all.find(co, lambda i: (i % 2) == 0) self.assertAlmostEqualVector(ret_regular, ret_filter) - # filter out all values (search odd tree for even values and the reverse) co = (0,) * 3 ret_filter = k_odd.find(co, lambda i: (i % 2) == 0) diff --git a/tests/python/bl_rna_defaults.py b/tests/python/bl_rna_defaults.py index 72f50a827f0b..6038ef34d783 100644 --- a/tests/python/bl_rna_defaults.py +++ b/tests/python/bl_rna_defaults.py @@ -8,7 +8,7 @@ DUMMY_PATH = __file__ GLOBALS = { "error_num": 0, - } +} def as_float_32(f): @@ -142,5 +142,6 @@ def main(): print("Error (total): %d" % GLOBALS["error_num"]) + if __name__ == "__main__": main() diff --git a/tests/python/bl_rna_manual_reference.py b/tests/python/bl_rna_manual_reference.py index c67b6c1532bb..00e40fe571b7 100644 --- a/tests/python/bl_rna_manual_reference.py +++ b/tests/python/bl_rna_manual_reference.py @@ -155,5 +155,6 @@ def main(): test_language_coverage() test_urls() + if __name__ == "__main__": main() diff --git a/tests/python/bl_run_operators.py b/tests/python/bl_run_operators.py index 7b6b97e5ad1d..aae78a841320 100644 --- a/tests/python/bl_run_operators.py +++ b/tests/python/bl_run_operators.py @@ -36,7 +36,7 @@ STATE = { "counter": 0, - } +} op_blacklist = ( @@ -91,7 +91,7 @@ "wm.keymap_restore", # another annoying one "wm.addon_*", # harmless, but dont change state "console.*", # just annoying - but harmless - ) +) def blend_list(mainpath): @@ -114,6 +114,7 @@ def is_blend(filename): return list(sorted(file_list(mainpath, is_blend))) + if USE_FILES: USE_FILES_LS = blend_list(USE_FILES) # print(USE_FILES_LS) @@ -176,7 +177,7 @@ def build_property_typemap(skip_classes): CLS_BLACKLIST = ( bpy.types.BrushTextureSlot, bpy.types.Brush, - ) + ) property_typemap = build_property_typemap(CLS_BLACKLIST) bpy_struct_type = bpy.types.Struct.__base__ @@ -228,7 +229,7 @@ def id_walk(value, parent): {0: "", 1: "hello", 2: "test"}, {"": 0, "hello": 1, "test": 2}, set(), {"", "test", "."}, {None, ..., type}, range(10), (" " * i for i in range(10)), - ) + ) def attrset_data(): for attr in dir(bpy.data): @@ -480,8 +481,9 @@ def main(): print("Finished %r" % __file__) + if __name__ == "__main__": - #~ for i in range(200): - #~ RANDOM_SEED[0] += 1 + # ~ for i in range(200): + # ~ RANDOM_SEED[0] += 1 #~ main() main() diff --git a/tests/python/collada/animation/test_animation_simple.py b/tests/python/collada/animation/test_animation_simple.py index bdfae03aafb1..6b18313c3cd6 100644 --- a/tests/python/collada/animation/test_animation_simple.py +++ b/tests/python/collada/animation/test_animation_simple.py @@ -31,6 +31,7 @@ import pathlib from pathlib import Path + def with_tempdir(wrapped): """Creates a temporary directory for the function, cleaning up after it returns normally. @@ -56,8 +57,10 @@ def decorator(*args, **kwargs): return decorator + LINE = "+----------------------------------------------------------------" + class AbstractColladaTest(unittest.TestCase): @classmethod @@ -71,33 +74,33 @@ def checkdae(self, reference, export): ref = open(reference) exp = open(export) - diff=difflib.unified_diff(ref.readlines(), exp.readlines(), lineterm='', n=0) + diff = difflib.unified_diff(ref.readlines(), exp.readlines(), lineterm='', n=0) ref.close() exp.close() - diff_count = 0; + diff_count = 0 for line in diff: error = True for prefix in ('---', '+++', '@@'): # Ignore diff metadata if line.startswith(prefix): - error=False + error = False break else: # Ignore time stamps for ignore in ('', '', ''): if line[1:].strip().startswith(ignore): - error=False + error = False break if error: - diff_count +=1 + diff_count += 1 pline = line.strip() if diff_count == 1: print("\n%s" % LINE) print("|Test has errors:") print(LINE) pre = "reference" if pline[0] == "-" else "generated" - print ("| %s:%s"% (pre, pline[1:])) + print("| %s:%s" % (pre, pline[1:])) if diff_count > 0: print(LINE) @@ -107,14 +110,16 @@ def checkdae(self, reference, export): return diff_count == 0 + class MeshExportTest4(AbstractColladaTest): @with_tempdir def test_export_animation_suzannes_sample_matrix(self, tempdir: pathlib.Path): test = "suzannes_parent_inverse_sample_10_matrix" reference_dae = self.testdir / Path("%s.dae" % test) - outfile = tempdir / Path("%s_out.dae" % test) + outfile = tempdir / Path("%s_out.dae" % test) - bpy.ops.wm.collada_export(filepath="%s" % str(outfile), + bpy.ops.wm.collada_export( + filepath="%s" % str(outfile), check_existing=True, filemode=8, display_type='DEFAULT', @@ -142,20 +147,23 @@ def test_export_animation_suzannes_sample_matrix(self, tempdir: pathlib.Path): export_texture_type_selection='mat', open_sim=False, limit_precision=True, - keep_bind_info=False) + keep_bind_info=False, + ) # Now check the resulting Collada file. if not self.checkdae(reference_dae, outfile): self.fail() + class MeshExportTest3(AbstractColladaTest): @with_tempdir def test_export_animation_suzannes_sample_locrotscale(self, tempdir: pathlib.Path): test = "suzannes_parent_inverse_sample_10_channels" reference_dae = self.testdir / Path("%s.dae" % test) - outfile = tempdir / Path("%s_out.dae" % test) + outfile = tempdir / Path("%s_out.dae" % test) - bpy.ops.wm.collada_export(filepath="%s" % str(outfile), + bpy.ops.wm.collada_export( + filepath="%s" % str(outfile), check_existing=True, filemode=8, display_type='DEFAULT', @@ -183,20 +191,23 @@ def test_export_animation_suzannes_sample_locrotscale(self, tempdir: pathlib.Pat export_texture_type_selection='mat', open_sim=False, limit_precision=True, - keep_bind_info=False) + keep_bind_info=False, + ) # Now check the resulting Collada file. if not self.checkdae(reference_dae, outfile): self.fail() + class MeshExportTest2(AbstractColladaTest): @with_tempdir def test_export_animation_suzannes_keyframe_matrix(self, tempdir: pathlib.Path): test = "suzannes_parent_inverse_keyframes_matrix" reference_dae = self.testdir / Path("%s.dae" % test) - outfile = tempdir / Path("%s_out.dae" % test) + outfile = tempdir / Path("%s_out.dae" % test) - bpy.ops.wm.collada_export(filepath="%s" % str(outfile), + bpy.ops.wm.collada_export( + filepath="%s" % str(outfile), check_existing=True, filemode=8, display_type='DEFAULT', @@ -224,20 +235,23 @@ def test_export_animation_suzannes_keyframe_matrix(self, tempdir: pathlib.Path): export_texture_type_selection='mat', open_sim=False, limit_precision=True, - keep_bind_info=False) + keep_bind_info=False, + ) # Now check the resulting Collada file. if not self.checkdae(reference_dae, outfile): self.fail() + class MeshExportTest1(AbstractColladaTest): @with_tempdir def test_export_animation_suzannes_keyframe_locrotscale(self, tempdir: pathlib.Path): test = "suzannes_parent_inverse_keyframes_channels" reference_dae = self.testdir / Path("%s.dae" % test) - outfile = tempdir / Path("%s_out.dae" % test) + outfile = tempdir / Path("%s_out.dae" % test) - bpy.ops.wm.collada_export(filepath="%s" % str(outfile), + bpy.ops.wm.collada_export( + filepath="%s" % str(outfile), check_existing=True, filemode=8, display_type='DEFAULT', @@ -265,7 +279,8 @@ def test_export_animation_suzannes_keyframe_locrotscale(self, tempdir: pathlib.P export_texture_type_selection='mat', open_sim=False, limit_precision=True, - keep_bind_info=False) + keep_bind_info=False, + ) # Now check the resulting Collada file. if not self.checkdae(reference_dae, outfile): @@ -277,4 +292,4 @@ def test_export_animation_suzannes_keyframe_locrotscale(self, tempdir: pathlib.P parser = argparse.ArgumentParser() parser.add_argument('--testdir', required=True) args, remaining = parser.parse_known_args() - unittest.main(argv=sys.argv[0:1]+remaining) + unittest.main(argv=sys.argv[0:1] + remaining) diff --git a/tests/python/collada/mesh/test_mesh_simple.py b/tests/python/collada/mesh/test_mesh_simple.py index 213c6177fde2..5899d986a14c 100644 --- a/tests/python/collada/mesh/test_mesh_simple.py +++ b/tests/python/collada/mesh/test_mesh_simple.py @@ -31,6 +31,7 @@ import pathlib from pathlib import Path + def with_tempdir(wrapped): """Creates a temporary directory for the function, cleaning up after it returns normally. @@ -56,8 +57,10 @@ def decorator(*args, **kwargs): return decorator + LINE = "+----------------------------------------------------------------" + class AbstractColladaTest(unittest.TestCase): @classmethod @@ -71,33 +74,33 @@ def checkdae(self, reference, export): ref = open(reference) exp = open(export) - diff=difflib.unified_diff(ref.readlines(), exp.readlines(), lineterm='', n=0) + diff = difflib.unified_diff(ref.readlines(), exp.readlines(), lineterm='', n=0) ref.close() exp.close() - diff_count = 0; + diff_count = 0 for line in diff: error = True for prefix in ('---', '+++', '@@'): # Ignore diff metadata if line.startswith(prefix): - error=False + error = False break else: # Ignore time stamps for ignore in ('', '', ''): if line[1:].strip().startswith(ignore): - error=False + error = False break if error: - diff_count +=1 + diff_count += 1 pline = line.strip() if diff_count == 1: print("\n%s" % LINE) print("|Test has errors:") print(LINE) pre = "reference" if pline[0] == "-" else "generated" - print ("| %s:%s"% (pre, pline[1:])) + print("| %s:%s" % (pre, pline[1:])) if diff_count > 0: print(LINE) @@ -107,14 +110,16 @@ def checkdae(self, reference, export): return diff_count == 0 + class MeshExportTest(AbstractColladaTest): @with_tempdir def test_export_single_mesh(self, tempdir: pathlib.Path): test = "mesh_simple_001" reference_dae = self.testdir / Path("%s.dae" % test) - outfile = tempdir / Path("%s_out.dae" % test) + outfile = tempdir / Path("%s_out.dae" % test) - bpy.ops.wm.collada_export(filepath="%s" % str(outfile), + bpy.ops.wm.collada_export( + filepath="%s" % str(outfile), check_existing=True, filemode=8, display_type="DEFAULT", @@ -140,15 +145,17 @@ def test_export_single_mesh(self, tempdir: pathlib.Path): export_texture_type_selection="mat", open_sim=False, limit_precision=False, - keep_bind_info=False) + keep_bind_info=False, + ) # Now check the resulting Collada file. if not self.checkdae(reference_dae, outfile): self.fail() + if __name__ == '__main__': sys.argv = [__file__] + (sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) parser = argparse.ArgumentParser() parser.add_argument('--testdir', required=True) args, remaining = parser.parse_known_args() - unittest.main(argv=sys.argv[0:1]+remaining) + unittest.main(argv=sys.argv[0:1] + remaining) diff --git a/tests/python/modules/render_report.py b/tests/python/modules/render_report.py index 5ccd5076fbc3..6c71e8dcb741 100755 --- a/tests/python/modules/render_report.py +++ b/tests/python/modules/render_report.py @@ -23,6 +23,7 @@ class COLORS_DUMMY: GREEN = '' ENDC = '' + COLORS = COLORS_DUMMY @@ -55,10 +56,12 @@ def blend_list(dirpath): filepath = os.path.join(dirpath, filename) yield filepath + def test_get_name(filepath): filename = os.path.basename(filepath) return os.path.splitext(filename)[0] + def test_get_images(output_dir, filepath): testname = test_get_name(filepath) dirpath = os.path.dirname(filepath) @@ -96,7 +99,7 @@ class Report: 'update', 'failed_tests', 'passed_tests' - ) + ) def __init__(self, title, output_dir, idiff): self.title = title @@ -257,7 +260,6 @@ def _write_test_html(self, testname, filepath, error): else: self.passed_tests += test_html - def _diff_output(self, filepath, tmp_filepath): old_img, ref_img, new_img, diff_img = test_get_images(self.output_dir, filepath) @@ -280,7 +282,7 @@ def _diff_output(self, filepath, tmp_filepath): "-failpercent", "1", ref_img, tmp_filepath, - ) + ) try: subprocess.check_output(command) failed = False @@ -307,7 +309,7 @@ def _diff_output(self, filepath, tmp_filepath): "-abs", "-scale", "16", ref_img, tmp_filepath - ) + ) try: subprocess.check_output(command) @@ -317,7 +319,6 @@ def _diff_output(self, filepath, tmp_filepath): return not failed - def _run_test(self, filepath, render_cb): testname = test_get_name(filepath) print_message(testname, 'SUCCESS', 'RUN') @@ -344,7 +345,7 @@ def _run_test(self, filepath, render_cb): return error elif error == "NO_START": print_message('Can not perform tests because blender fails to start.', - 'Make sure INSTALL target was run.') + 'Make sure INSTALL target was run.') return error elif error == 'VERIFY': print_message("Rendered result is different from reference image") @@ -354,7 +355,6 @@ def _run_test(self, filepath, render_cb): 'FAILURE', 'FAILED') return error - def _run_all_tests(self, dirname, dirpath, render_cb): passed_tests = [] failed_tests = [] @@ -387,11 +387,10 @@ def _run_all_tests(self, dirname, dirpath, render_cb): 'SUCCESS', 'PASSED') if failed_tests: print_message("{} tests, listed below:" . - format(len(failed_tests)), - 'FAILURE', 'FAILED') + format(len(failed_tests)), + 'FAILURE', 'FAILED') failed_tests.sort() for test in failed_tests: print_message("{}" . format(test), 'FAILURE', "FAILED") return not bool(failed_tests) - diff --git a/tests/python/modules/test_utils.py b/tests/python/modules/test_utils.py index c4496c3e3ace..47d720684baf 100755 --- a/tests/python/modules/test_utils.py +++ b/tests/python/modules/test_utils.py @@ -62,7 +62,6 @@ class AbstractBlenderRunnerTest(unittest.TestCase): blender: pathlib.Path = None testdir: pathlib.Path = None - def run_blender(self, filepath: str, python_script: str, timeout: int=300) -> str: """Runs Blender by opening a blendfile and executing a script. @@ -92,7 +91,7 @@ def run_blender(self, filepath: str, python_script: str, timeout: int=300) -> st '-E', 'CYCLES', '--python-exit-code', '47', '--python-expr', python_script, - ] + ] ) proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, @@ -102,4 +101,3 @@ def run_blender(self, filepath: str, python_script: str, timeout: int=300) -> st self.fail('Error %d running Blender:\n%s' % (proc.returncode, output)) return output - diff --git a/tests/python/opengl_draw_tests.py b/tests/python/opengl_draw_tests.py index 999304570dfa..ae7f0dabf747 100755 --- a/tests/python/opengl_draw_tests.py +++ b/tests/python/opengl_draw_tests.py @@ -8,6 +8,7 @@ import subprocess import sys + def screenshot(): import bpy @@ -19,6 +20,7 @@ def screenshot(): bpy.ops.wm.quit_blender() + # When run from inside Blender, take screenshot and exit. try: import bpy @@ -93,5 +95,6 @@ def main(): sys.exit(not ok) + if __name__ == "__main__": main() diff --git a/tests/python/pep8.py b/tests/python/pep8.py index ebf2c5eabb7f..ccc2dddbbd92 100644 --- a/tests/python/pep8.py +++ b/tests/python/pep8.py @@ -93,7 +93,7 @@ def check_files_flake8(files): # times types are compared, # I rather keep them specific "E721", - ) + ) for f, pep8_type in files: @@ -129,10 +129,10 @@ def check_files_pylint(files): "C0413," # import should be placed at the top "W0613," # unused argument, may add this back # but happens a lot for 'context' for eg. - "W0232," # class has no __init__, Operator/Panel/Menu etc + "W0232," # class has no __init__, Operator/Panel/Menu etc "W0142," # Used * or ** magic # even needed in some cases - "R0902," # Too many instance attributes + "R0902," # Too many instance attributes "R0903," # Too many statements "R0911," # Too many return statements "R0912," # Too many branches @@ -204,6 +204,5 @@ def main(): print("Skipping pylint checks (command not found)") - if __name__ == "__main__": main() diff --git a/tests/python/rna_array.py b/tests/python/rna_array.py index dda13d2c3aea..e0d63cf75ea7 100644 --- a/tests/python/rna_array.py +++ b/tests/python/rna_array.py @@ -3,7 +3,7 @@ import unittest import random -test= bpy.data.test +test = bpy.data.test # farr - 1-dimensional array of float # fdarr - dynamic 1-dimensional array of float @@ -12,6 +12,7 @@ # same as above for other types except that the first letter is "i" for int and "b" for bool + class TestArray(unittest.TestCase): # test that assignment works by: assign -> test value # - rvalue = list of float @@ -20,14 +21,14 @@ class TestArray(unittest.TestCase): # bpy.data.test.farr[3], iarr[3], barr[...], fmarr, imarr, bmarr def setUp(self): - test.farr= (1.0, 2.0, 3.0) - test.iarr= (7, 8, 9) - test.barr= (False, True, False) + test.farr = (1.0, 2.0, 3.0) + test.iarr = (7, 8, 9) + test.barr = (False, True, False) # test access # test slice access, negative indices def test_access(self): - rvals= ([1.0, 2.0, 3.0], [7, 8, 9], [False, True, False]) + rvals = ([1.0, 2.0, 3.0], [7, 8, 9], [False, True, False]) for arr, rval in zip((test.farr, test.iarr, test.barr), rvals): self.assertEqual(prop_to_list(arr), rval) self.assertEqual(arr[0:3], rval) @@ -39,12 +40,12 @@ def test_access(self): # fail when index out of bounds def test_access_fail(self): for arr in (test.farr, test.iarr, test.barr): - self.assertRaises(IndexError, lambda : arr[4]) + self.assertRaises(IndexError, lambda: arr[4]) # test assignment of a whole array def test_assign_array(self): # should accept int as float - test.farr= (1, 2, 3) + test.farr = (1, 2, 3) # fail when: unexpected no. of items, invalid item type def test_assign_array_fail(self): @@ -55,20 +56,20 @@ def assign_empty_list(arr): self.assertRaises(ValueError, assign_empty_list, arr) def assign_invalid_float(): - test.farr= (1.0, 2.0, "3.0") + test.farr = (1.0, 2.0, "3.0") def assign_invalid_int(): - test.iarr= ("1", 2, 3) + test.iarr = ("1", 2, 3) def assign_invalid_bool(): - test.barr= (True, 0.123, False) + test.barr = (True, 0.123, False) for func in [assign_invalid_float, assign_invalid_int, assign_invalid_bool]: self.assertRaises(TypeError, func) # shouldn't accept float as int def assign_float_as_int(): - test.iarr= (1, 2, 3.0) + test.iarr = (1, 2, 3.0) self.assertRaises(TypeError, assign_float_as_int) # non-dynamic arrays cannot change size @@ -81,14 +82,14 @@ def assign_different_size(arr, val): def test_assign_item(self): for arr, rand_func in zip((test.farr, test.iarr, test.barr), (rand_float, rand_int, rand_bool)): for i in range(len(arr)): - val= rand_func() + val = rand_func() arr[i] = val self.assertEqual(arr[i], val) # float prop should accept also int for i in range(len(test.farr)): - val= rand_int() + val = rand_int() test.farr[i] = val self.assertEqual(test.farr[i], float(val)) @@ -112,7 +113,7 @@ def test_dynamic_assign_array(self): # test various lengths here for arr, rand_func in zip(("fdarr", "idarr", "bdarr"), (rand_float, rand_int, rand_bool)): for length in range(1, 64): - rval= make_random_array(length, rand_func) + rval = make_random_array(length, rand_func) setattr(test, arr, rval) self.assertEqual(prop_to_list(getattr(test, arr)), rval) @@ -136,7 +137,7 @@ def setUp(self): def test_assign_array(self): for arr, func in zip(("fmarr", "imarr", "bmarr"), (rand_float, rand_int, rand_bool)): # assignment of [3][4][5] - rval= make_random_3d_array((3, 4, 5), func) + rval = make_random_3d_array((3, 4, 5), func) setattr(test, arr, rval) self.assertEqual(prop_to_list(getattr(test, arr)), rval) @@ -144,7 +145,7 @@ def test_assign_array(self): def test_assign_array_fail(self): def assign_empty_array(): - test.fmarr= () + test.fmarr = () self.assertRaises(ValueError, assign_empty_array) def assign_invalid_size(arr, rval): @@ -152,19 +153,19 @@ def assign_invalid_size(arr, rval): # assignment of 3,4,4 or 3,3,5 should raise ex for arr, func in zip(("fmarr", "imarr", "bmarr"), (rand_float, rand_int, rand_bool)): - rval= make_random_3d_array((3, 4, 4), func) + rval = make_random_3d_array((3, 4, 4), func) self.assertRaises(ValueError, assign_invalid_size, arr, rval) - rval= make_random_3d_array((3, 3, 5), func) + rval = make_random_3d_array((3, 3, 5), func) self.assertRaises(ValueError, assign_invalid_size, arr, rval) - rval= make_random_3d_array((3, 3, 3), func) + rval = make_random_3d_array((3, 3, 3), func) self.assertRaises(ValueError, assign_invalid_size, arr, rval) def test_assign_item(self): # arr[i] = x for arr, func in zip(("fmarr", "imarr", "bmarr", "fdmarr", "idmarr", "bdmarr"), (rand_float, rand_int, rand_bool) * 2): - rval= make_random_2d_array((4, 5), func) + rval = make_random_2d_array((4, 5), func) for i in range(3): getattr(test, arr)[i] = rval @@ -173,23 +174,22 @@ def test_assign_item(self): # arr[i][j] = x for arr, func in zip(("fmarr", "imarr", "bmarr", "fdmarr", "idmarr", "bdmarr"), (rand_float, rand_int, rand_bool) * 2): - arr= getattr(test, arr) - rval= make_random_array(5, func) + arr = getattr(test, arr) + rval = make_random_array(5, func) for i in range(3): for j in range(4): arr[i][j] = rval self.assertEqual(prop_to_list(arr[i][j]), rval) - def test_assign_item_fail(self): def assign_wrong_size(arr, i, rval): getattr(test, arr)[i] = rval # assign wrong size at level 2 for arr, func in zip(("fmarr", "imarr", "bmarr"), (rand_float, rand_int, rand_bool)): - rval1= make_random_2d_array((3, 5), func) - rval2= make_random_2d_array((4, 3), func) + rval1 = make_random_2d_array((3, 5), func) + rval2 = make_random_2d_array((4, 3), func) for i in range(3): self.assertRaises(ValueError, assign_wrong_size, arr, i, rval1) @@ -198,22 +198,22 @@ def assign_wrong_size(arr, i, rval): def test_dynamic_assign_array(self): for arr, func in zip(("fdmarr", "idmarr", "bdmarr"), (rand_float, rand_int, rand_bool)): # assignment of [3][4][5] - rval= make_random_3d_array((3, 4, 5), func) + rval = make_random_3d_array((3, 4, 5), func) setattr(test, arr, rval) self.assertEqual(prop_to_list(getattr(test, arr)), rval) # [2][4][5] - rval= make_random_3d_array((2, 4, 5), func) + rval = make_random_3d_array((2, 4, 5), func) setattr(test, arr, rval) self.assertEqual(prop_to_list(getattr(test, arr)), rval) # [1][4][5] - rval= make_random_3d_array((1, 4, 5), func) + rval = make_random_3d_array((1, 4, 5), func) setattr(test, arr, rval) self.assertEqual(prop_to_list(getattr(test, arr)), rval) - # test access + def test_access(self): pass @@ -221,26 +221,32 @@ def test_access(self): def test_access_fail(self): pass + random.seed() + def rand_int(): return random.randint(-1000, 1000) + def rand_float(): return float(rand_int()) + def rand_bool(): return bool(random.randint(0, 1)) + def make_random_array(len, rand_func): - arr= [] + arr = [] for i in range(len): arr.append(rand_func()) return arr + def make_random_2d_array(dimsize, rand_func): - marr= [] + marr = [] for i in range(dimsize[0]): marr.append([]) @@ -249,8 +255,9 @@ def make_random_2d_array(dimsize, rand_func): return marr + def make_random_3d_array(dimsize, rand_func): - marr= [] + marr = [] for i in range(dimsize[0]): marr.append([]) @@ -262,8 +269,9 @@ def make_random_3d_array(dimsize, rand_func): return marr + def prop_to_list(prop): - ret= [] + ret = [] for x in prop: if type(x) not in {bool, int, float}: @@ -273,9 +281,10 @@ def prop_to_list(prop): return ret + def suite(): return unittest.TestSuite([unittest.TestLoader().loadTestsFromTestCase(TestArray), unittest.TestLoader().loadTestsFromTestCase(TestMArray)]) + if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite()) -