From 3d937bd732582ec1017d28ec7f97f8d3c993ddea Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Tue, 19 Sep 2017 23:03:48 +0200
Subject: Haiku patchset


diff --git a/CMakeLists.txt b/CMakeLists.txt
index bfea2dd..ebe6bef 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -195,7 +195,7 @@ endif()
 # Options
 
 # First platform specific non-cached vars
-if(UNIX AND NOT APPLE)
+if(UNIX AND NOT (APPLE OR HAIKU))
 	set(WITH_X11 ON)
 endif()
 
@@ -793,7 +793,9 @@ set(CC_REMOVE_STRICT_FLAGS)
 
 # libraries to link the binary with passed to target_link_libraries()
 # known as LLIBS to scons
-set(PLATFORM_LINKLIBS "")
+if(HAIKU)
+set(PLATFORM_LINKLIBS "-lnetwork")
+endif()
 
 # Added to linker flags in setup_liblinks
 # - CMAKE_EXE_LINKER_FLAGS
diff --git a/build_files/cmake/macros.cmake b/build_files/cmake/macros.cmake
index 6303119..2083683 100644
--- a/build_files/cmake/macros.cmake
+++ b/build_files/cmake/macros.cmake
@@ -1508,6 +1508,7 @@ function(find_python_package
 		  PATH_SUFFIXES
 		    site-packages
 		    dist-packages
+		    vendor-packages
 		   NO_DEFAULT_PATH
 		)
 
@@ -1518,6 +1519,8 @@ function(find_python_package
 				"'${PYTHON_LIBPATH}/python${_PY_VER_MAJOR}/site-packages/${package}', "
 				"'${PYTHON_LIBPATH}/python${PYTHON_VERSION}/dist-packages/${package}', "
 				"'${PYTHON_LIBPATH}/python${_PY_VER_MAJOR}/dist-packages/${package}', "
+                "'${PYTHON_LIBPATH}/python${PYTHON_VERSION}/vendor-packages/${package}', "
+                "'${PYTHON_LIBPATH}/python${_PY_VER_MAJOR}/vendor-packages/${package}', "
 				"\n"
 				"The 'WITH_PYTHON_INSTALL_${_upper_package}' option will be ignored when installing Python.\n"
 				"The build will be usable, only add-ons that depend on this package won't be functional."
diff --git a/build_files/cmake/platform/platform_unix.cmake b/build_files/cmake/platform/platform_unix.cmake
index 62e0caa..9eb6985 100644
--- a/build_files/cmake/platform/platform_unix.cmake
+++ b/build_files/cmake/platform/platform_unix.cmake
@@ -358,7 +358,11 @@ if(WITH_OPENSUBDIV OR WITH_CYCLES_OPENSUBDIV)
 endif()
 
 # OpenSuse needs lutil, ArchLinux not, for now keep, can avoid by using --as-needed
-list(APPEND PLATFORM_LINKLIBS -lutil -lc -lm)
+if(HAIKU)
+	list(APPEND PLATFORM_LINKLIBS -lnetwork)
+else()
+	list(APPEND PLATFORM_LINKLIBS -lutil -lc -lm)
+endif()
 
 find_package(Threads REQUIRED)
 list(APPEND PLATFORM_LINKLIBS ${CMAKE_THREAD_LIBS_INIT})
diff --git a/intern/guardedalloc/intern/mallocn_intern.h b/intern/guardedalloc/intern/mallocn_intern.h
index 4efa236..4b2282a 100644
--- a/intern/guardedalloc/intern/mallocn_intern.h
+++ b/intern/guardedalloc/intern/mallocn_intern.h
@@ -63,6 +63,9 @@
 #elif defined(WIN32)
 #  include <malloc.h>
 #  define malloc_usable_size _msize
+#elif defined(__HAIKU__)
+#  include <malloc.h>
+size_t malloc_usable_size(void *ptr);
 #else
 #  pragma message "We don't know how to use malloc_usable_size on your platform"
 #  undef USE_MALLOC_USABLE_SIZE
diff --git a/intern/libmv/libmv/numeric/numeric.h b/intern/libmv/libmv/numeric/numeric.h
index 1a23d65..6312b4e 100644
--- a/intern/libmv/libmv/numeric/numeric.h
+++ b/intern/libmv/libmv/numeric/numeric.h
@@ -35,7 +35,8 @@
 
 #if !defined(__MINGW64__)
 #  if defined(_WIN32) || defined(__APPLE__) || \
-      defined(__FreeBSD__) || defined(__NetBSD__)
+      defined(__FreeBSD__) || defined(__NetBSD__) || \
+      defined(__HAIKU__)
 inline void sincos(double x, double *sinx, double *cosx) {
   *sinx = sin(x);
   *cosx = cos(x);
diff --git a/source/blender/blenlib/BLI_sys_types.h b/source/blender/blenlib/BLI_sys_types.h
index 9477f61..95c0227 100644
--- a/source/blender/blenlib/BLI_sys_types.h
+++ b/source/blender/blenlib/BLI_sys_types.h
@@ -47,7 +47,7 @@
 extern "C" {
 #endif
 
-#if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD_kernel__) || defined(__GNU__)
+#if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD_kernel__) || defined(__GNU__) || defined(__HAIKU__)
 
 /* Linux-i386, Linux-Alpha, Linux-ppc */
 #include <stdint.h>
diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c
index 1df7f6f..0978420 100644
--- a/source/blender/blenlib/intern/fileops.c
+++ b/source/blender/blenlib/intern/fileops.c
@@ -614,6 +614,11 @@ static int recursive_operation(const char *startfrom, const char *startto,
 		for (i = 0; i < n; i++) {
 			const struct dirent * const dirent = dirlist[i];
 
+#ifdef __HAIKU__
+			struct stat st;
+			char filename[512];
+#endif
+
 			if (FILENAME_IS_CURRPAR(dirent->d_name))
 				continue;
 
@@ -621,7 +626,13 @@ static int recursive_operation(const char *startfrom, const char *startto,
 			if (to)
 				join_dirfile_alloc(&to_path, &to_alloc_len, to, dirent->d_name);
 
+#ifdef __HAIKU__
+			snprintf(filename, sizeof(filename), "%s/%s", startfrom, dirent->d_name);
+			lstat(filename, &st);
+			if (S_ISDIR(st.st_mode)) {
+#else
 			if (dirent->d_type == DT_DIR) {
+#endif
 				/* recursively dig into a subfolder */
 				ret = recursive_operation(from_path, to_path, callback_dir_pre, callback_file, callback_dir_post);
 			}
diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c
index b819c51..9fb3fbf 100644
--- a/source/blender/blenlib/intern/storage.c
+++ b/source/blender/blenlib/intern/storage.c
@@ -37,7 +37,7 @@
 
 #include <sys/stat.h>
 
-#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__sun__) || defined(__sun)
+#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__sun__) || defined(__sun) || defined(__HAIKU__)
    /* Other modern unix os's should probably use this also */
 #  include <sys/statvfs.h>
 #  define USE_STATFS_STATVFS
-- 
2.30.2


From 75ce13adce97d766020f7438333aa5d1cd6542bd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Tue, 19 Sep 2017 23:15:20 +0200
Subject: Haiku SDL2 check fix


diff --git a/build_files/cmake/Modules/FindSDL2.cmake b/build_files/cmake/Modules/FindSDL2.cmake
index 2a835cf..61b7dee 100644
--- a/build_files/cmake/Modules/FindSDL2.cmake
+++ b/build_files/cmake/Modules/FindSDL2.cmake
@@ -43,7 +43,7 @@ FIND_PATH(SDL2_INCLUDE_DIR
   HINTS
     ${_sdl2_SEARCH_DIRS}
   PATH_SUFFIXES
-    include/SDL2 include
+    include/SDL2 include SDL2
 )
 
 FIND_LIBRARY(SDL2_LIBRARY
-- 
2.30.2


From 59f7447e8055eae5636071e56f18da879b15add0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Tue, 19 Sep 2017 23:52:27 +0200
Subject: In-tree glog supporting patches


diff --git a/extern/glog/src/config.h b/extern/glog/src/config.h
index f5c9c0b..2703b7b 100644
--- a/extern/glog/src/config.h
+++ b/extern/glog/src/config.h
@@ -14,4 +14,6 @@
  #include "windows/config.h"
 #elif defined(__GNU__)
  #include "config_hurd.h"
+#elif defined(__HAIKU__)
+ #include "config_haiku.h"
 #endif
diff --git a/extern/glog/src/config_haiku.h b/extern/glog/src/config_haiku.h
new file mode 100644
index 0000000..4e6703b
--- /dev/null
+++ b/extern/glog/src/config_haiku.h
@@ -0,0 +1,172 @@
+/* src/config.h.  Generated from config.h.in by configure.  */
+/* src/config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Namespace for Google classes */
+#define GOOGLE_NAMESPACE google
+
+/* Define if you have the `dladdr' function */
+#define HAVE_DLADDR 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the <execinfo.h> header file. */
+#undef HAVE_EXECINFO_H
+
+/* Define if you have the `fcntl' function */
+#define HAVE_FCNTL 1
+
+/* Define to 1 if you have the <glob.h> header file. */
+#define HAVE_GLOB_H 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `pthread' library (-lpthread). */
+#define HAVE_LIBPTHREAD 1
+
+/* Define to 1 if you have the <libunwind.h> header file. */
+/* #undef HAVE_LIBUNWIND_H */
+
+/* define if you have google gflags library */
+#define HAVE_LIB_GFLAGS 1
+
+/* define if you have google gmock library */
+/* #undef HAVE_LIB_GMOCK */
+
+/* define if you have google gtest library */
+/* #undef HAVE_LIB_GTEST */
+
+/* define if you have libunwind */
+/* #undef HAVE_LIB_UNWIND */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* define if the compiler implements namespaces */
+#define HAVE_NAMESPACES 1
+
+/* Define if you have the 'pread' function */
+#define HAVE_PREAD 1
+
+/* Define if you have POSIX threads libraries and header files. */
+#define HAVE_PTHREAD 1
+
+/* Define to 1 if you have the <pwd.h> header file. */
+#define HAVE_PWD_H 1
+
+/* Define if you have the 'pwrite' function */
+#define HAVE_PWRITE 1
+
+/* define if the compiler implements pthread_rwlock_* */
+#define HAVE_RWLOCK 1
+
+/* Define if you have the `sigaltstack' function */
+#define HAVE_SIGALTSTACK 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <syscall.h> header file. */
+/* #undef HAVE_SYSCALL_H */
+
+/* Define to 1 if you have the <syslog.h> header file. */
+#define HAVE_SYSLOG_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/syscall.h> header file. */
+/* #undef HAVE_SYS_SYSCALL_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/ucontext.h> header file. */
+/* #undef HAVE_SYS_UCONTEXT_H */
+
+/* Define to 1 if you have the <sys/utsname.h> header file. */
+#define HAVE_SYS_UTSNAME_H 1
+
+/* Define to 1 if you have the <ucontext.h> header file. */
+/* #undef HAVE_UCONTEXT_H */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* define if the compiler supports using expression for operator */
+#define HAVE_USING_OPERATOR 1
+
+/* define if your compiler has __attribute__ */
+#define HAVE___ATTRIBUTE__ 1
+
+/* define if your compiler has __builtin_expect */
+#define HAVE___BUILTIN_EXPECT 1
+
+/* define if your compiler has __sync_val_compare_and_swap */
+/* #undef HAVE___SYNC_VAL_COMPARE_AND_SWAP */
+
+/* Name of package */
+#define PACKAGE "glog"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "opensource@google.com"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "glog"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "glog 0.3.4"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "glog"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "0.3.4"
+
+/* How to access the PC from a struct ucontext */
+/* #define PC_FROM_UCONTEXT uc_mcontext.gregs[REG_RIP] */
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+   your system. */
+/* #undef PTHREAD_CREATE_JOINABLE */
+
+/* The size of `void *', as computed by sizeof. */
+#define SIZEOF_VOID_P 8
+
+/* Define to 1 if you have the ANSI C header files. */
+/* #undef STDC_HEADERS */
+
+#define STDC_HEADERS 1
+/* the namespace where STL code like vector<> is defined */
+#define STL_NAMESPACE std
+
+/* location of source code */
+#define TEST_SRC_DIR "."
+
+/* Version number of package */
+#define VERSION "0.3.4"
+
+/* Stops putting the code inside the Google namespace */
+#define _END_GOOGLE_NAMESPACE_ }
+
+/* Puts following code inside the Google namespace */
+#define _START_GOOGLE_NAMESPACE_ namespace google {
+
+/* isn't getting defined by configure script when clang compilers are used
+   and cuases compilation errors in stactrace/unwind modules */
+#ifdef __clang__
+#  define NO_FRAME_POINTER
+#endif
-- 
2.30.2


From 76b48d2aa793c30ce358158e48e1476fbea55ded Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Sat, 16 Dec 2017 17:04:56 +0100
Subject: OpenCollada support


diff --git a/build_files/cmake/Modules/FindOpenCOLLADA.cmake b/build_files/cmake/Modules/FindOpenCOLLADA.cmake
index 63bc520..28cf0b9 100644
--- a/build_files/cmake/Modules/FindOpenCOLLADA.cmake
+++ b/build_files/cmake/Modules/FindOpenCOLLADA.cmake
@@ -67,6 +67,7 @@ SET(_opencollada_SEARCH_DIRS
   /opt/local # DarwinPorts
   /opt/csw # Blastwave
   /opt/lib/opencollada
+  /system/develop
 )
 
 SET(_opencollada_INCLUDES)
@@ -84,6 +85,7 @@ FOREACH(COMPONENT ${_opencollada_FIND_INCLUDES})
       include/opencollada/${COMPONENT}
       include/${COMPONENT}/include
       include/${COMPONENT}
+      headers/opencollada
     HINTS
       ${_opencollada_SEARCH_DIRS}
     )
-- 
2.30.2


From 433f32fa2ae04138d74259041c6278889c97382d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Sat, 4 Aug 2018 12:42:53 +0200
Subject: FFMPEG4 patches


diff --git a/intern/audaspace/ffmpeg/AUD_FFMPEGReader.cpp b/intern/audaspace/ffmpeg/AUD_FFMPEGReader.cpp
index e9eea19..84aea33 100644
--- a/intern/audaspace/ffmpeg/AUD_FFMPEGReader.cpp
+++ b/intern/audaspace/ffmpeg/AUD_FFMPEGReader.cpp
@@ -264,9 +264,9 @@ AUD_FFMPEGReader::AUD_FFMPEGReader(boost::shared_ptr<AUD_Buffer> buffer) :
 		m_membuffer(buffer),
 		m_membufferpos(0)
 {
-	m_membuf = reinterpret_cast<data_t*>(av_malloc(FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE));
+	m_membuf = reinterpret_cast<data_t*>(av_malloc(AV_INPUT_BUFFER_MIN_SIZE + AV_INPUT_BUFFER_PADDING_SIZE));
 
-	m_aviocontext = avio_alloc_context(m_membuf, FF_MIN_BUFFER_SIZE, 0, this,
+	m_aviocontext = avio_alloc_context(m_membuf, AV_INPUT_BUFFER_MIN_SIZE, 0, this,
 									   read_packet, NULL, seek_packet);
 
 	if(!m_aviocontext)
diff --git a/intern/audaspace/ffmpeg/AUD_FFMPEGWriter.cpp b/intern/audaspace/ffmpeg/AUD_FFMPEGWriter.cpp
index 3f95ac7..2c2f091 100644
--- a/intern/audaspace/ffmpeg/AUD_FFMPEGWriter.cpp
+++ b/intern/audaspace/ffmpeg/AUD_FFMPEGWriter.cpp
@@ -163,7 +163,7 @@ AUD_FFMPEGWriter::AUD_FFMPEGWriter(std::string filename, AUD_DeviceSpecs specs,
 		try
 		{
 			if(m_formatCtx->oformat->flags & AVFMT_GLOBALHEADER)
-				m_codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
+				m_codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 
 			AVCodec* codec = avcodec_find_encoder(m_codecCtx->codec_id);
 			if(!codec)
@@ -185,11 +185,11 @@ AUD_FFMPEGWriter::AUD_FFMPEGWriter(std::string filename, AUD_DeviceSpecs specs,
 			if(avcodec_open2(m_codecCtx, codec, NULL))
 				AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
 
-			m_output_buffer.resize(FF_MIN_BUFFER_SIZE);
+			m_output_buffer.resize(AV_INPUT_BUFFER_MIN_SIZE);
 			int samplesize = AUD_MAX(AUD_SAMPLE_SIZE(m_specs), AUD_DEVICE_SAMPLE_SIZE(m_specs));
 
 			if(m_codecCtx->frame_size <= 1) {
-				m_input_size = FF_MIN_BUFFER_SIZE * 8 / m_codecCtx->bits_per_coded_sample / m_codecCtx->channels;
+				m_input_size = AV_INPUT_BUFFER_MIN_SIZE * 8 / m_codecCtx->bits_per_coded_sample / m_codecCtx->channels;
 				m_input_buffer.resize(m_input_size * samplesize);
 			}
 			else
diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c
index a19e414..d586979 100644
--- a/source/blender/blenkernel/intern/writeffmpeg.c
+++ b/source/blender/blenkernel/intern/writeffmpeg.c
@@ -605,8 +605,6 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int
 	c->rc_buffer_aggressivity = 1.0;
 #endif
 
-	c->me_method = ME_EPZS;
-	
 	codec = avcodec_find_encoder(c->codec_id);
 	if (!codec)
 		return NULL;
@@ -668,14 +666,14 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int
 	    )
 	{
 		PRINT("Using global header\n");
-		c->flags |= CODEC_FLAG_GLOBAL_HEADER;
+		c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 	}
 	
 	/* Determine whether we are encoding interlaced material or not */
 	if (rd->mode & R_FIELDS) {
 		PRINT("Encoding interlaced video\n");
-		c->flags |= CODEC_FLAG_INTERLACED_DCT;
-		c->flags |= CODEC_FLAG_INTERLACED_ME;
+		c->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
+		c->flags |= AV_CODEC_FLAG_INTERLACED_ME;
 	}
 
 	/* xasp & yasp got float lately... */
@@ -765,7 +763,7 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, RenderData *rd, int
 	}
 
 	if (of->oformat->flags & AVFMT_GLOBALHEADER) {
-		c->flags |= CODEC_FLAG_GLOBAL_HEADER;
+		c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 	}
 
 	set_ffmpeg_properties(rd, c, "audio", &opts);
@@ -784,14 +782,14 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, RenderData *rd, int
 	st->codec->time_base.den = st->codec->sample_rate;
 
 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
-	context->audio_outbuf_size = FF_MIN_BUFFER_SIZE;
+	context->audio_outbuf_size = AV_INPUT_BUFFER_MIN_SIZE;
 #endif
 
 	if (c->frame_size == 0)
 		// used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
 		// not sure if that is needed anymore, so let's try out if there are any
 		// complaints regarding some ffmpeg versions users might have
-		context->audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels;
+		context->audio_input_samples = AV_INPUT_BUFFER_MIN_SIZE * 8 / c->bits_per_coded_sample / c->channels;
 	else {
 		context->audio_input_samples = c->frame_size;
 #ifndef FFMPEG_HAVE_ENCODE_AUDIO2
diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c
index e1b3abc..1850ffd 100644
--- a/source/blender/imbuf/intern/indexer.c
+++ b/source/blender/imbuf/intern/indexer.c
@@ -537,7 +537,7 @@ static struct proxy_output_ctx *alloc_proxy_output_ffmpeg(
 	av_opt_set_int(rv->c, "qmax", ffmpeg_quality, 0);
 
 	if (rv->of->flags & AVFMT_GLOBALHEADER) {
-		rv->c->flags |= CODEC_FLAG_GLOBAL_HEADER;
+		rv->c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 	}
 
 	if (avio_open(&rv->of->pb, fname, AVIO_FLAG_WRITE) < 0) {
-- 
2.30.2


From 3495a84d45f730a480034d697c3e67b8860507cf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20Mizsei?= <zmizsei@extrowerk.com>
Date: Thu, 22 Aug 2019 18:07:13 +0200
Subject: Build fixes from FreeBSD


diff --git a/source/blender/collada/DocumentImporter.cpp b/source/blender/collada/DocumentImporter.cpp
index 435eaa0..8708926 100644
--- a/source/blender/collada/DocumentImporter.cpp
+++ b/source/blender/collada/DocumentImporter.cpp
@@ -1340,6 +1340,11 @@ bool DocumentImporter::writeAnimationList(const COLLADAFW::AnimationList *animat
 	return anim_importer.write_animation_list(animationList);
 }
 
+bool DocumentImporter::writeAnimationClip(const COLLADAFW::AnimationClip *AnimationClip)
+{
+	return true;
+}
+
 /** When this method is called, the writer must write the skin controller data.
  * \return The writer should return true, if writing succeeded, false otherwise.*/
 bool DocumentImporter::writeSkinControllerData(const COLLADAFW::SkinControllerData *skin)
diff --git a/source/blender/collada/DocumentImporter.h b/source/blender/collada/DocumentImporter.h
index 62f76db..1f3b64f 100644
--- a/source/blender/collada/DocumentImporter.h
+++ b/source/blender/collada/DocumentImporter.h
@@ -108,6 +108,8 @@ public:
 
 	bool writeAnimationList(const COLLADAFW::AnimationList*);
 
+	bool writeAnimationClip( const COLLADAFW::AnimationClip* );
+
 	bool writeGeometry(const COLLADAFW::Geometry*);
 
 	bool writeMaterial(const COLLADAFW::Material*);
-- 
2.30.2


From e8b2d163fa8dea54a1452d50acd1bd86cd0e2055 Mon Sep 17 00:00:00 2001
From: Jerome Duval <jerome.duval@gmail.com>
Date: Thu, 7 Nov 2019 18:35:57 +0100
Subject: applying patch blender-2.79b-gcc-8.patch


diff --git a/intern/cycles/util/util_sseb.h b/intern/cycles/util/util_sseb.h
index 6e66970..9ffe391 100644
--- a/intern/cycles/util/util_sseb.h
+++ b/intern/cycles/util/util_sseb.h
@@ -116,7 +116,7 @@ __forceinline const sseb unpacklo( const sseb& a, const sseb& b ) { return _mm_u
 __forceinline const sseb unpackhi( const sseb& a, const sseb& b ) { return _mm_unpackhi_ps(a, b); }
 
 template<size_t i0, size_t i1, size_t i2, size_t i3> __forceinline const sseb shuffle( const sseb& a ) {
-	return _mm_shuffle_epi32(a, _MM_SHUFFLE(i3, i2, i1, i0));
+	return _mm_castsi128_ps(_mm_shuffle_epi32(a, _MM_SHUFFLE(i3, i2, i1, i0)));
 }
 
 template<> __forceinline const sseb shuffle<0, 1, 0, 1>( const sseb& a ) {
diff --git a/intern/itasc/kdl/tree.hpp b/intern/itasc/kdl/tree.hpp
index c8a253f..bd35f82 100644
--- a/intern/itasc/kdl/tree.hpp
+++ b/intern/itasc/kdl/tree.hpp
@@ -34,7 +34,7 @@ namespace KDL
     //Forward declaration
     class TreeElement;
     // Eigen allocator is needed for alignment of Eigen data types
-    typedef std::map<std::string,TreeElement, std::less<std::string>, Eigen::aligned_allocator<std::pair<std::string, TreeElement> > > SegmentMap;
+    typedef std::map<std::string,TreeElement, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, TreeElement> > > SegmentMap;
 
     class TreeElement
     {
-- 
2.30.2


From e146e78c8cb1a88b36a2329a201d0896d738c695 Mon Sep 17 00:00:00 2001
From: Sergey Sharybin <sergey.vfx@gmail.com>
Date: Tue, 11 Dec 2018 12:17:26 +0100
Subject: Update code to be compatible with OIIO 2.0

There are some changes in API of OpenImageIO, but those are quite
simple to keep working with older and newer library versions.

Reviewers: brecht

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D4064

diff --git a/intern/cycles/blender/blender_python.cpp b/intern/cycles/blender/blender_python.cpp
index 54973fd..bee6dd1 100644
--- a/intern/cycles/blender/blender_python.cpp
+++ b/intern/cycles/blender/blender_python.cpp
@@ -493,7 +493,7 @@ static PyObject *osl_update_node_func(PyObject * /*self*/, PyObject *args)
 				socket_type = "NodeSocketString";
 				data_type = BL::NodeSocket::type_STRING;
 				if(param->validdefault)
-					default_string = param->sdefault[0];
+					default_string = param->sdefault[0].string();
 			}
 			else
 				continue;
diff --git a/intern/cycles/graph/node_xml.cpp b/intern/cycles/graph/node_xml.cpp
index d26b3b2..2a24104 100644
--- a/intern/cycles/graph/node_xml.cpp
+++ b/intern/cycles/graph/node_xml.cpp
@@ -250,7 +250,7 @@ void xml_read_node(XMLReader& reader, Node *node, xml_node xml_node)
 		}
 	}
 
-	if(node->name)
+	if(!node->name.empty())
 		reader.node_map[node->name] = node;
 }
 
diff --git a/intern/cycles/render/buffers.cpp b/intern/cycles/render/buffers.cpp
index cf402c3..6df6325 100644
--- a/intern/cycles/render/buffers.cpp
+++ b/intern/cycles/render/buffers.cpp
@@ -27,6 +27,7 @@
 #include "util/util_opengl.h"
 #include "util/util_time.h"
 #include "util/util_types.h"
+#include "util/util_unique_ptr.h"
 
 CCL_NAMESPACE_BEGIN
 
@@ -453,7 +454,7 @@ void DisplayBuffer::write(Device *device, const string& filename)
 	device->pixels_copy_from(rgba, 0, w, h);
 
 	/* write image */
-	ImageOutput *out = ImageOutput::create(filename);
+	unique_ptr<ImageOutput> out(ImageOutput::create(filename));
 	ImageSpec spec(w, h, 4, TypeDesc::UINT8);
 	int scanlinesize = w*4*sizeof(uchar);
 
@@ -467,8 +468,6 @@ void DisplayBuffer::write(Device *device, const string& filename)
 		AutoStride);
 
 	out->close();
-
-	delete out;
 }
 
 device_memory& DisplayBuffer::rgba_data()
diff --git a/intern/cycles/render/image.cpp b/intern/cycles/render/image.cpp
index 595eb46..7829df9 100644
--- a/intern/cycles/render/image.cpp
+++ b/intern/cycles/render/image.cpp
@@ -23,6 +23,7 @@
 #include "util/util_path.h"
 #include "util/util_progress.h"
 #include "util/util_texture.h"
+#include "util/util_unique_ptr.h"
 
 #ifdef WITH_OSL
 #include <OSL/oslexec.h>
@@ -148,7 +149,7 @@ ImageDataType ImageManager::get_image_metadata(const string& filename,
 		return IMAGE_DATA_TYPE_BYTE4;
 	}
 
-	ImageInput *in = ImageInput::create(filename);
+	unique_ptr<ImageInput> in(ImageInput::create(filename));
 
 	if(in) {
 		ImageSpec spec;
@@ -194,7 +195,6 @@ ImageDataType ImageManager::get_image_metadata(const string& filename,
 			in->close();
 		}
 
-		delete in;
 	}
 
 	if(is_half) {
@@ -449,7 +449,7 @@ void ImageManager::tag_reload_image(const string& filename,
 }
 
 bool ImageManager::file_load_image_generic(Image *img,
-                                           ImageInput **in,
+                                           unique_ptr<ImageInput> *in,
                                            int &width,
                                            int &height,
                                            int &depth,
@@ -465,7 +465,7 @@ bool ImageManager::file_load_image_generic(Image *img,
 		}
 
 		/* load image from file through OIIO */
-		*in = ImageInput::create(img->filename);
+		*in = unique_ptr<ImageInput>(ImageInput::create(img->filename));
 
 		if(!*in)
 			return false;
@@ -477,8 +477,6 @@ bool ImageManager::file_load_image_generic(Image *img,
 			config.attribute("oiio:UnassociatedAlpha", 1);
 
 		if(!(*in)->open(img->filename, spec, config)) {
-			delete *in;
-			*in = NULL;
 			return false;
 		}
 
@@ -500,10 +498,7 @@ bool ImageManager::file_load_image_generic(Image *img,
 	if(!(components >= 1 && components <= 4)) {
 		if(*in) {
 			(*in)->close();
-			delete *in;
-			*in = NULL;
 		}
-
 		return false;
 	}
 
@@ -519,7 +514,7 @@ bool ImageManager::file_load_image(Image *img,
                                    device_vector<DeviceType>& tex_img)
 {
 	const StorageType alpha_one = (FileFormat == TypeDesc::UINT8)? 255 : 1;
-	ImageInput *in = NULL;
+	unique_ptr<ImageInput> in = NULL;
 	int width, height, depth, components;
 	if(!file_load_image_generic(img, &in, width, height, depth, components)) {
 		return false;
@@ -575,7 +570,6 @@ bool ImageManager::file_load_image(Image *img,
 		}
 		cmyk = strcmp(in->format_name(), "jpeg") == 0 && components == 4;
 		in->close();
-		delete in;
 	}
 	else {
 		if(FileFormat == TypeDesc::FLOAT) {
diff --git a/intern/cycles/render/image.h b/intern/cycles/render/image.h
index db7e28a..f4a14f4 100644
--- a/intern/cycles/render/image.h
+++ b/intern/cycles/render/image.h
@@ -23,6 +23,7 @@
 #include "util/util_image.h"
 #include "util/util_string.h"
 #include "util/util_thread.h"
+#include "util/util_unique_ptr.h"
 #include "util/util_vector.h"
 
 CCL_NAMESPACE_BEGIN
@@ -133,7 +134,7 @@ private:
 	bool pack_images;
 
 	bool file_load_image_generic(Image *img,
-	                             ImageInput **in,
+	                             unique_ptr<ImageInput> *in,
 	                             int &width,
 	                             int &height,
 	                             int &depth,
diff --git a/intern/cycles/util/util_unique_ptr.h b/intern/cycles/util/util_unique_ptr.h
new file mode 100644
index 0000000..1ceae73
--- /dev/null
+++ b/intern/cycles/util/util_unique_ptr.h
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+#ifndef __UTIL_UNIQUE_PTR_H__
+#define __UTIL_UNIQUE_PTR_H__
+
+#include <memory>
+
+CCL_NAMESPACE_BEGIN
+
+using std::unique_ptr;
+
+CCL_NAMESPACE_END
+
+#endif  /* __UTIL_UNIQUE_PTR_H__ */
diff --git a/source/blender/imbuf/intern/oiio/openimageio_api.cpp b/source/blender/imbuf/intern/oiio/openimageio_api.cpp
index b123d50..7f2fac9 100644
--- a/source/blender/imbuf/intern/oiio/openimageio_api.cpp
+++ b/source/blender/imbuf/intern/oiio/openimageio_api.cpp
@@ -35,6 +35,11 @@
 #include "utfconv.h"
 #endif
 
+// NOTE: Keep first, BLI_path_util conflicts with OIIO's format.
+#include <memory>
+#include <openimageio_api.h>
+#include <OpenImageIO/imageio.h>
+
 extern "C"
 {
 #include "MEM_guardedalloc.h"
@@ -48,12 +53,10 @@ extern "C"
 #include "IMB_colormanagement_intern.h"
 }
 
-#include <openimageio_api.h>
-#include <OpenImageIO/imageio.h>
-
 OIIO_NAMESPACE_USING
 
 using std::string;
+using std::unique_ptr;
 
 typedef unsigned char uchar;
 
@@ -197,7 +200,6 @@ int imb_save_photoshop(struct ImBuf *ibuf, const char * /*name*/, int flags)
 
 struct ImBuf *imb_load_photoshop(const char *filename, int flags, char colorspace[IM_MAX_SPACE])
 {
-	ImageInput *in = NULL;
 	struct ImBuf *ibuf = NULL;
 	int width, height, components;
 	bool is_float, is_alpha;
@@ -210,7 +212,7 @@ struct ImBuf *imb_load_photoshop(const char *filename, int flags, char colorspac
 
 	colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_BYTE);
 
-	in = ImageInput::create(filename);
+	unique_ptr<ImageInput> in(ImageInput::create(filename));
 	if (!in) {
 		std::cerr << __func__ << ": ImageInput::create() failed:" << std::endl
 		          << OIIO_NAMESPACE::geterror() << std::endl;
@@ -223,7 +225,6 @@ struct ImBuf *imb_load_photoshop(const char *filename, int flags, char colorspac
 	if (!in->open(filename, spec, config)) {
 		std::cerr << __func__ << ": ImageInput::open() failed:" << std::endl
 		          << in->geterror() << std::endl;
-		delete in;
 		return NULL;
 	}
 
@@ -249,19 +250,17 @@ struct ImBuf *imb_load_photoshop(const char *filename, int flags, char colorspac
 	if (!(components >= 1 && components <= 4)) {
 		if (in) {
 			in->close();
-			delete in;
 		}
 		return NULL;
 	}
 
 	if (is_float)
-		ibuf = imb_oiio_load_image_float(in, width, height, components, flags, is_alpha);
+		ibuf = imb_oiio_load_image_float(in.get(), width, height, components, flags, is_alpha);
 	else
-		ibuf = imb_oiio_load_image(in, width, height, components, flags, is_alpha);
+		ibuf = imb_oiio_load_image(in.get(), width, height, components, flags, is_alpha);
 
 	if (in) {
 		in->close();
-		delete in;
 	}
 
 	if (!ibuf)
-- 
2.30.2


From 64392d166b07c2594ad95a9fa419515a533cf586 Mon Sep 17 00:00:00 2001
From: X512 <danger_mail@list.ru>
Date: Wed, 29 Jan 2020 14:07:31 +0900
Subject: Haiku: fix build for 32 bit


diff --git a/intern/cycles/util/util_simd.h b/intern/cycles/util/util_simd.h
index 587febe..d25d7f8 100644
--- a/intern/cycles/util/util_simd.h
+++ b/intern/cycles/util/util_simd.h
@@ -229,7 +229,7 @@ __forceinline int __btr(int v, int i) {
   int r = 0; asm ("btr %1,%0" : "=r"(r) : "r"(i), "0"(v) : "flags"); return r;
 }
 
-#if (defined(__KERNEL_64_BIT__) || defined(__APPLE__)) && !(defined(__ILP32__) && defined(__x86_64__))
+#if (defined(__KERNEL_64_BIT__) || defined(__APPLE__) || defined(__HAIKU__)) && !(defined(__ILP32__) && defined(__x86_64__))
 __forceinline size_t __bsf(size_t v) {
   size_t r = 0; asm ("bsf %1,%0" : "=r"(r) : "r"(v)); return r;
 }
-- 
2.30.2


From 76f03162bc2b06ec62032e2ffb43062c9cb3f462 Mon Sep 17 00:00:00 2001
From: X512 <danger_mail@list.ru>
Date: Wed, 29 Jan 2020 17:30:56 +0900
Subject: Fix TLS for haiku


diff --git a/source/blender/blenlib/BLI_threads.h b/source/blender/blenlib/BLI_threads.h
index 60da6b3..8ad0d69 100644
--- a/source/blender/blenlib/BLI_threads.h
+++ b/source/blender/blenlib/BLI_threads.h
@@ -186,7 +186,7 @@ void BLI_thread_queue_nowait(ThreadQueue *queue);
 
 /* Thread local storage */
 
-#if defined(__APPLE__)
+#if defined(__APPLE__) || defined(__HAIKU__)
 #  define ThreadLocal(type) pthread_key_t
 #  define BLI_thread_local_create(name) pthread_key_create(&name, NULL)
 #  define BLI_thread_local_delete(name) pthread_key_delete(name)
-- 
2.30.2


From f3ac7572d6016fd8b86837c52adadf486343fedd Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Fri, 19 Mar 2021 11:07:00 +1000
Subject: Fix hangs on exit


diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c
index 7608b01..ec274af 100644
--- a/source/blender/windowmanager/intern/wm_init_exit.c
+++ b/source/blender/windowmanager/intern/wm_init_exit.c
@@ -568,6 +568,10 @@ void WM_exit_ext(bContext *C, const bool do_python)
 	
 	ED_file_exit(); /* for fsmenu */
 
+	/* No need to call this early, rather do it late so that other pieces of Blender using sound may exit cleanly,
+	 * see also T50676. */
+	BKE_sound_exit();
+
 	UI_exit();
 	BKE_blender_userdef_data_free(&U, false);
 
@@ -586,10 +590,6 @@ void WM_exit_ext(bContext *C, const bool do_python)
 
 	BLI_threadapi_exit();
 
-	/* No need to call this early, rather do it late so that other pieces of Blender using sound may exit cleanly,
-	 * see also T50676. */
-	BKE_sound_exit();
-
 	BKE_blender_atexit();
 
 	if (MEM_get_memory_blocks_in_use() != 0) {
-- 
2.30.2


From ebff020d31641f7d26fbcdad174c89acb484b7e3 Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Sun, 22 Aug 2021 15:20:53 +1000
Subject: Use OpenEXR 3.x


diff --git a/build_files/cmake/Modules/FindOpenEXR.cmake b/build_files/cmake/Modules/FindOpenEXR.cmake
index 41e60a7..d058986 100644
--- a/build_files/cmake/Modules/FindOpenEXR.cmake
+++ b/build_files/cmake/Modules/FindOpenEXR.cmake
@@ -38,11 +38,10 @@ ENDIF()
 SET(_openexr_libs_ver_init "2.0")
 
 SET(_openexr_FIND_COMPONENTS
-  Half
   Iex
-  IlmImf
-  IlmThread
   Imath
+  OpenEXR
+  IlmThread
 )
 
 SET(_openexr_SEARCH_DIRS
@@ -127,7 +126,7 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenEXR  DEFAULT_MSG
 IF(OPENEXR_FOUND)
   SET(OPENEXR_LIBRARIES ${_openexr_LIBRARIES})
   # Both include paths are needed because of dummy OSL headers mixing #include <OpenEXR/foo.h> and #include <foo.h> :(
-  SET(OPENEXR_INCLUDE_DIRS ${OPENEXR_INCLUDE_DIR} ${OPENEXR_INCLUDE_DIR}/OpenEXR)
+  SET(OPENEXR_INCLUDE_DIRS ${OPENEXR_INCLUDE_DIR} ${OPENEXR_INCLUDE_DIR}/OpenEXR ${OPENEXR_INCLUDE_DIR}/Imath)
 ENDIF()
 
 MARK_AS_ADVANCED(
diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp
index 5ad42bd..76204bc 100644
--- a/source/blender/imbuf/intern/openexr/openexr_api.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp
@@ -49,9 +49,11 @@
 #include <ImfChannelList.h>
 #include <ImfPixelType.h>
 #include <ImfInputFile.h>
+#include <ImfInt64.h>
 #include <ImfOutputFile.h>
 #include <ImfCompression.h>
 #include <ImfCompressionAttribute.h>
+#include <ImfFrameBuffer.h>
 #include <ImfStringAttribute.h>
 #include <ImfStandardAttributes.h>
 
-- 
2.30.2


From b091801032b4f6caad4b2da1acc0ae532b185757 Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Mon, 27 Dec 2021 14:46:03 +1000
Subject: Link with system ICU


diff --git a/build_files/cmake/platform/platform_unix.cmake b/build_files/cmake/platform/platform_unix.cmake
index 9eb6985..0573950 100644
--- a/build_files/cmake/platform/platform_unix.cmake
+++ b/build_files/cmake/platform/platform_unix.cmake
@@ -359,7 +359,7 @@ endif()
 
 # OpenSuse needs lutil, ArchLinux not, for now keep, can avoid by using --as-needed
 if(HAIKU)
-	list(APPEND PLATFORM_LINKLIBS -lnetwork)
+	list(APPEND PLATFORM_LINKLIBS -lnetwork -liconv -licuuc -licui18n)
 else()
 	list(APPEND PLATFORM_LINKLIBS -lutil -lc -lm)
 endif()
-- 
2.30.2


From 9f096917470ff595ab4a4409b03dd821ba7f81be Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Mon, 27 Dec 2021 14:46:55 +1000
Subject: Fix for openexr3


diff --git a/source/blender/alembic/intern/abc_transform.cc b/source/blender/alembic/intern/abc_transform.cc
index 5392387..9dc3200 100644
--- a/source/blender/alembic/intern/abc_transform.cc
+++ b/source/blender/alembic/intern/abc_transform.cc
@@ -22,7 +22,7 @@
 
 #include "abc_transform.h"
 
-#include <OpenEXR/ImathBoxAlgo.h>
+#include <Imath/ImathBoxAlgo.h>
 
 #include "abc_util.h"
 
-- 
2.30.2


From b9e5b97547071a4dede5da58a9b76f7314c4d7ac Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Wed, 12 Jan 2022 22:04:25 +1000
Subject: applying patch blender-2.79-python-3.7-fix.patch


diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c
index 0d3781c..832a872 100644
--- a/source/blender/python/intern/bpy_rna.c
+++ b/source/blender/python/intern/bpy_rna.c
@@ -7385,10 +7385,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)                         \
@@ -7404,6 +7406,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 */
-- 
2.30.2


From 155d0e83a553bad0aeb44cca56a5f84cb5fc59ad Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Wed, 12 Jan 2022 22:04:25 +1000
Subject: applying patch blender-2.79-python-3.8-fix.patch


diff --git a/source/blender/python/bmesh/bmesh_py_api.c b/source/blender/python/bmesh/bmesh_py_api.c
index d5973ba..d7324ea 100644
--- a/source/blender/python/bmesh/bmesh_py_api.c
+++ b/source/blender/python/bmesh/bmesh_py_api.c
@@ -196,7 +196,7 @@ PyObject *BPyInit_bmesh(void)
 {
 	PyObject *mod;
 	PyObject *submodule;
-	PyObject *sys_modules = PyThreadState_GET()->interp->modules;
+	PyObject *sys_modules = PyImport_GetModuleDict();
 
 	BPy_BM_init_types();
 	BPy_BM_init_types_select();
diff --git a/source/blender/python/generic/idprop_py_api.c b/source/blender/python/generic/idprop_py_api.c
index 5d6a7c5..3435c8c 100644
--- a/source/blender/python/generic/idprop_py_api.c
+++ b/source/blender/python/generic/idprop_py_api.c
@@ -1792,7 +1792,7 @@ PyObject *BPyInit_idprop(void)
 {
 	PyObject *mod;
 	PyObject *submodule;
-	PyObject *sys_modules = PyThreadState_GET()->interp->modules;
+	PyObject *sys_modules = PyImport_GetModuleDict();
 
 	mod = PyModule_Create(&IDProp_module_def);
 
diff --git a/source/blender/python/generic/py_capi_utils.c b/source/blender/python/generic/py_capi_utils.c
index 861e2db..a3bcadd 100644
--- a/source/blender/python/generic/py_capi_utils.c
+++ b/source/blender/python/generic/py_capi_utils.c
@@ -638,9 +638,16 @@ PyObject *PyC_UnicodeFromByte(const char *str)
  ****************************************************************************/
 PyObject *PyC_DefaultNameSpace(const char *filename)
 {
+	#if PY_VERSION_HEX >= 0x03080000
+	PyObject *modules = PyImport_GetModuleDict();
+	PyObject *builtins = PyEval_GetBuiltins();
+	#else
 	PyInterpreterState *interp = PyThreadState_GET()->interp;
+	PyObject *modules = interp->modules;
+	PyObject *builtins = interp->builtins;
+	#endif
 	PyObject *mod_main = PyModule_New("__main__");
-	PyDict_SetItemString(interp->modules, "__main__", mod_main);
+	PyDict_SetItemString(modules, "__main__", mod_main);
 	Py_DECREF(mod_main); /* sys.modules owns now */
 	PyModule_AddStringConstant(mod_main, "__name__", "__main__");
 	if (filename) {
@@ -648,23 +655,33 @@ PyObject *PyC_DefaultNameSpace(const char *filename)
 		 * note: this wont map to a real file when executing text-blocks and buttons. */
 		PyModule_AddObject(mod_main, "__file__", PyC_UnicodeFromByte(filename));
 	}
-	PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
-	Py_INCREF(interp->builtins); /* AddObject steals a reference */
+	PyModule_AddObject(mod_main, "__builtins__", builtins);
+	Py_INCREF(builtins); /* AddObject steals a reference */
 	return PyModule_GetDict(mod_main);
 }
 
 /* restore MUST be called after this */
 void PyC_MainModule_Backup(PyObject **main_mod)
 {
+	#if PY_VERSION_HEX >= 0x03080000
+	PyObject *modules = PyImport_GetModuleDict();
+	#else
 	PyInterpreterState *interp = PyThreadState_GET()->interp;
-	*main_mod = PyDict_GetItemString(interp->modules, "__main__");
+	PyObject *modules = interp->modules;
+	#endif
+	*main_mod = PyDict_GetItemString(modules, "__main__");
 	Py_XINCREF(*main_mod); /* don't free */
 }
 
 void PyC_MainModule_Restore(PyObject *main_mod)
 {
+	#if PY_VERSION_HEX >= 0x03080000
+	PyObject *modules = PyImport_GetModuleDict();
+	#else
 	PyInterpreterState *interp = PyThreadState_GET()->interp;
-	PyDict_SetItemString(interp->modules, "__main__", main_mod);
+	PyObject *modules = interp->modules;
+	#endif
+	PyDict_SetItemString(modules, "__main__", main_mod);
 	Py_XDECREF(main_mod);
 }
 
diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c
index 20cfd36..2e99b8b 100644
--- a/source/blender/python/intern/bpy_interface.c
+++ b/source/blender/python/intern/bpy_interface.c
@@ -530,7 +530,7 @@ static bool python_script_exec(
 
 	if (py_dict) {
 #ifdef PYMODULE_CLEAR_WORKAROUND
-		PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
+		PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItemString(PyImport_GetModuleDict(), "__main__");
 		PyObject *dict_back = mmod->md_dict;
 		/* freeing the module will clear the namespace,
 		 * gives problems running classes defined in this namespace being used later. */
diff --git a/source/blender/python/intern/gpu.c b/source/blender/python/intern/gpu.c
index 48230a7..25016c5 100644
--- a/source/blender/python/intern/gpu.c
+++ b/source/blender/python/intern/gpu.c
@@ -323,7 +323,7 @@ PyObject *GPU_initPython(void)
 {
 	PyObject *module;
 	PyObject *submodule;
-	PyObject *sys_modules = PyThreadState_GET()->interp->modules;
+	PyObject *sys_modules = PyImport_GetModuleDict();
 
 	module = PyInit_gpu();
 
@@ -334,7 +334,7 @@ PyObject *GPU_initPython(void)
 	PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
 	Py_INCREF(submodule);
 
-	PyDict_SetItem(PyImport_GetModuleDict(), PyModule_GetNameObject(module), module);
+	PyDict_SetItem(sys_modules, PyModule_GetNameObject(module), module);
 	return module;
 }
 
diff --git a/source/blender/python/mathutils/mathutils.c b/source/blender/python/mathutils/mathutils.c
index 96ae0a9..21d3624 100644
--- a/source/blender/python/mathutils/mathutils.c
+++ b/source/blender/python/mathutils/mathutils.c
@@ -622,7 +622,7 @@ PyMODINIT_FUNC PyInit_mathutils(void)
 {
 	PyObject *mod;
 	PyObject *submodule;
-	PyObject *sys_modules = PyThreadState_GET()->interp->modules;
+	PyObject *sys_modules = PyImport_GetModuleDict();
 
 	if (PyType_Ready(&vector_Type) < 0)
 		return NULL;
diff --git a/source/blender/python/mathutils/mathutils_noise.c b/source/blender/python/mathutils/mathutils_noise.c
index 143e51e..98c5371 100644
--- a/source/blender/python/mathutils/mathutils_noise.c
+++ b/source/blender/python/mathutils/mathutils_noise.c
@@ -840,6 +840,7 @@ static struct PyModuleDef M_Noise_module_def = {
 /*----------------------------MODULE INIT-------------------------*/
 PyMODINIT_FUNC PyInit_mathutils_noise(void)
 {
+	PyObject *sys_modules = PyImport_GetModuleDict();
 	PyObject *submodule = PyModule_Create(&M_Noise_module_def);
 	PyObject *item_types, *item_metrics;
 
@@ -847,11 +848,11 @@ PyMODINIT_FUNC PyInit_mathutils_noise(void)
 	setRndSeed(0);
 
 	PyModule_AddObject(submodule, "types", (item_types = PyInit_mathutils_noise_types()));
-	PyDict_SetItemString(PyThreadState_GET()->interp->modules, "noise.types", item_types);
+	PyDict_SetItemString(sys_modules, "noise.types", item_types);
 	Py_INCREF(item_types);
 
 	PyModule_AddObject(submodule, "distance_metrics", (item_metrics = PyInit_mathutils_noise_metrics()));
-	PyDict_SetItemString(PyThreadState_GET()->interp->modules, "noise.distance_metrics", item_metrics);
+	PyDict_SetItemString(sys_modules, "noise.distance_metrics", item_metrics);
 	Py_INCREF(item_metrics);
 
 	return submodule;
diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp
index 97a7e16..5d21c53 100644
--- a/source/gameengine/Ketsji/KX_PythonInit.cpp
+++ b/source/gameengine/Ketsji/KX_PythonInit.cpp
@@ -2239,7 +2239,7 @@ PyMODINIT_FUNC initBGE(void)
 {
 	PyObject *mod;
 	PyObject *submodule;
-	PyObject *sys_modules = PyThreadState_GET()->interp->modules;
+	PyObject *sys_modules = PyImport_GetModuleDict();
 	const char *mod_full;
 
 	mod = PyModule_Create(&BGE_module_def);
-- 
2.30.2


From 8575097ea31a529e427f8b39c0ab835b8b5d5b16 Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Wed, 12 Jan 2022 22:04:25 +1000
Subject: applying patch python3.9.patch


diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c
index e368e88..ae598bb 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.c
+++ b/source/blender/python/mathutils/mathutils_Matrix.c
@@ -48,7 +48,8 @@ static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix);
 static PyObject *Matrix_copy(MatrixObject *self);
 static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args);
 static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value);
-static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self);
+static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
+                                       MatrixObject *self);
 static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type);
 
 static int matrix_row_vector_check(MatrixObject *mat, VectorObject *vec, int row)
@@ -385,14 +386,15 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 	return NULL;
 }
 
-static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self)
+static PyObject *matrix__apply_to_copy(PyObject *(*matrix_func)(MatrixObject *),
+                                       MatrixObject *self)
 {
 	PyObject *ret = Matrix_copy(self);
 	if (ret) {
-		PyObject *ret_dummy = matrix_func(ret);
+		PyObject *ret_dummy = matrix_func((MatrixObject *)ret);
 		if (ret_dummy) {
 			Py_DECREF(ret_dummy);
-			return (PyObject *)ret;
+			return ret;
 		}
 		else { /* error */
 			Py_DECREF(ret);
@@ -1598,7 +1600,7 @@ PyDoc_STRVAR(Matrix_adjugated_doc,
 );
 static PyObject *Matrix_adjugated(MatrixObject *self)
 {
-	return matrix__apply_to_copy((PyNoArgsFunction)Matrix_adjugate, self);
+	return matrix__apply_to_copy(Matrix_adjugate, self);
 }
 
 PyDoc_STRVAR(Matrix_rotate_doc,
@@ -1795,7 +1797,7 @@ PyDoc_STRVAR(Matrix_transposed_doc,
 );
 static PyObject *Matrix_transposed(MatrixObject *self)
 {
-	return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
+	return matrix__apply_to_copy(Matrix_transpose, self);
 }
 
 /*---------------------------matrix.normalize() ------------------*/
@@ -1842,7 +1844,7 @@ PyDoc_STRVAR(Matrix_normalized_doc,
 );
 static PyObject *Matrix_normalized(MatrixObject *self)
 {
-	return matrix__apply_to_copy((PyNoArgsFunction)Matrix_normalize, self);
+	return matrix__apply_to_copy(Matrix_normalize, self);
 }
 
 /*---------------------------matrix.zero() -----------------------*/
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c
index d283c71..322b578 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.c
+++ b/source/blender/python/mathutils/mathutils_Quaternion.c
@@ -40,7 +40,8 @@
 
 #define QUAT_SIZE 4
 
-static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self);
+static PyObject *quat__apply_to_copy(PyObject *(*quat_func)(QuaternionObject *),
+                                     QuaternionObject *self);
 static void      quat__axis_angle_sanitize(float axis[3], float *angle);
 static PyObject *Quaternion_copy(QuaternionObject *self);
 static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args);
@@ -381,7 +382,7 @@ PyDoc_STRVAR(Quaternion_normalized_doc,
 );
 static PyObject *Quaternion_normalized(QuaternionObject *self)
 {
-	return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
+	return quat__apply_to_copy(Quaternion_normalize, self);
 }
 
 PyDoc_STRVAR(Quaternion_invert_doc,
@@ -409,7 +410,7 @@ PyDoc_STRVAR(Quaternion_inverted_doc,
 );
 static PyObject *Quaternion_inverted(QuaternionObject *self)
 {
-	return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
+	return quat__apply_to_copy(Quaternion_invert, self);
 }
 
 PyDoc_STRVAR(Quaternion_identity_doc,
@@ -473,7 +474,7 @@ PyDoc_STRVAR(Quaternion_conjugated_doc,
 );
 static PyObject *Quaternion_conjugated(QuaternionObject *self)
 {
-	return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
+	return quat__apply_to_copy(Quaternion_conjugate, self);
 }
 
 PyDoc_STRVAR(Quaternion_copy_doc,
@@ -1146,10 +1147,11 @@ static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kw
 	return Quaternion_CreatePyObject(quat, type);
 }
 
-static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self)
+static PyObject *quat__apply_to_copy(PyObject *(*quat_func)(QuaternionObject *),
+                                     QuaternionObject *self)
 {
 	PyObject *ret = Quaternion_copy(self);
-	PyObject *ret_dummy = quat_func(ret);
+	PyObject *ret_dummy = quat_func((QuaternionObject *)ret);
 	if (ret_dummy) {
 		Py_DECREF(ret_dummy);
 		return ret;
diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c
index afc8a30..2f50330 100644
--- a/source/blender/python/mathutils/mathutils_Vector.c
+++ b/source/blender/python/mathutils/mathutils_Vector.c
@@ -92,10 +92,10 @@ static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 	return Vector_CreatePyObject_alloc(vec, size, type);
 }
 
-static PyObject *vec__apply_to_copy(PyNoArgsFunction vec_func, VectorObject *self)
+static PyObject *vec__apply_to_copy(PyObject *(*vec_func)(VectorObject *), VectorObject *self)
 {
 	PyObject *ret = Vector_copy(self);
-	PyObject *ret_dummy = vec_func(ret);
+	PyObject *ret_dummy = vec_func((VectorObject *)ret);
 	if (ret_dummy) {
 		Py_DECREF(ret_dummy);
 		return (PyObject *)ret;
@@ -378,7 +378,7 @@ PyDoc_STRVAR(Vector_normalized_doc,
 );
 static PyObject *Vector_normalized(VectorObject *self)
 {
-	return vec__apply_to_copy((PyNoArgsFunction)Vector_normalize, self);
+	return vec__apply_to_copy(Vector_normalize, self);
 }
 
 PyDoc_STRVAR(Vector_resize_doc,
-- 
2.30.2


From 9d0b29f31d6a5fec243e6d651fa64e0e3b55c165 Mon Sep 17 00:00:00 2001
From: Gerasim Troeglazov <3dEyes@gmail.com>
Date: Wed, 12 Jan 2022 22:04:26 +1000
Subject: applying patch python3.9_2.patch


diff --git a/source/blender/python/generic/bpy_threads.c b/source/blender/python/generic/bpy_threads.c
index fbc1456..628e28f 100644
--- a/source/blender/python/generic/bpy_threads.c
+++ b/source/blender/python/generic/bpy_threads.c
@@ -35,14 +35,11 @@
 /* analogue of PyEval_SaveThread() */
 BPy_ThreadStatePtr BPY_thread_save(void)
 {
-	PyThreadState *tstate = PyThreadState_Swap(NULL);
-	/* note: tstate can be NULL when quitting Blender */
-
-	if (tstate && PyEval_ThreadsInitialized()) {
-		PyEval_ReleaseLock();
+	/* The thread-state can be NULL when quitting Blender. */
+	if (_PyThreadState_UncheckedGet()) {
+		return (BPy_ThreadStatePtr)PyEval_SaveThread();
 	}
-
-	return (BPy_ThreadStatePtr)tstate;
+	return NULL;
 }
 
 /* analogue of PyEval_RestoreThread() */
-- 
2.30.2

